"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Badge } from "@/components/ui/badge"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { PhoneInput, isValidPhoneNumber, getCleanPhoneNumber } from "@/components/ui/phone-input"
import SmartAddressInput, { AddressResult } from "@/components/ui/smart-address-input"
import { useToast } from "@/components/ui/toast"
import {
  User,
  Lock,
  Eye,
  EyeOff,
  Save,
  CheckCircle,
  ShieldCheck,
  Building2,
  FileCheck,
  Loader2
} from "lucide-react"

import { DataAPI } from "@/lib/data-api"
import { useFacilityOwnerProfile, ProfileFormData } from "@/hooks/useFacilityOwnerProfile"

const US_STATES = [
  "AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "FL", "GA",
  "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD",
  "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ",
  "NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC",
  "SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY"
]

const ENTITY_TYPES = ["individual", "llc", "corporation", "partnership", "non-profit"]

const CARE_TYPES = [
  "Independent Living",
  "Assisted Living",
  "Memory Care",
  "Skilled Nursing",
  "Rehabilitation",
  "Hospice Care",
  "Adult Day Care",
  "Home Care"
]

/**
 * Helper function to get user ID from user object
 * Handles both `id` (from auth API) and `_id` (from DB) fields
 */
function getUserId(user: any): string | undefined {
  if (!user) return undefined
  return user.id || user._id
}

export default function SettingsPage() {
  const router = useRouter()
  const toast = useToast()

  // Use custom hook for profile management
  const {
    formData,
    user,
    ownerProfile,
    isLoading: isFetching,
    isSaving,
    errors,
    setFormData,
    setErrors,
    refetchProfile
  } = useFacilityOwnerProfile()

  const [activeTab, setActiveTab] = useState("account")
  const [showCurrentPassword, setShowCurrentPassword] = useState(false)
  const [showNewPassword, setShowNewPassword] = useState(false)
  const [showConfirmPassword, setShowConfirmPassword] = useState(false)
  const [isLoading, setIsLoading] = useState(false)

  const [passwordData, setPasswordData] = useState({
    current: "",
    new: "",
    confirm: ""
  })

  const handleInputChange = (field: keyof ProfileFormData, value: string | string[]) => {
    setFormData((prev) => ({ ...prev, [field]: value }))
    // Clear error when user starts typing
    if (errors[field]) {
      setErrors((prev) => ({ ...prev, [field]: "" }))
    }
  }

  const handleAddressSelect = (result: AddressResult) => {
    setFormData((prev) => ({
      ...prev,
      street: result.address,
      city: result.city,
      state: result.state,
      zipCode: result.zipCode
    }))

    // Clear related errors
    setErrors((prev) => ({
      ...prev,
      street: "",
      city: "",
      state: "",
      zipCode: ""
    }))
  }

  const validateOwnerInfo = (): boolean => {
    const newErrors: Record<string, string> = {}

    if (!formData.phone.trim()) newErrors.phone = "Phone number is required"
    else if (!isValidPhoneNumber(formData.phone)) newErrors.phone = "Invalid phone number"

    if (!formData.companyName.trim()) newErrors.companyName = "Company name is required"
    if (!formData.businessType) newErrors.businessType = "Business type is required"
    if (!formData.street.trim()) newErrors.street = "Street address is required"
    if (!formData.city.trim()) newErrors.city = "City is required"
    if (!formData.state) newErrors.state = "State is required"
    if (!formData.zipCode.trim()) newErrors.zipCode = "ZIP code is required"
    else if (!/^\d{5}(-\d{4})?$/.test(formData.zipCode)) {
      newErrors.zipCode = "Invalid ZIP code format"
    }

    setErrors(newErrors)
    return Object.keys(newErrors).length === 0
  }

  const validateLicensing = (): boolean => {
    const newErrors: Record<string, string> = {}

    if (!formData.licenseNumber.trim()) newErrors.licenseNumber = "License number is required"
    if (!formData.totalLicensed.trim()) newErrors.totalLicensed = "Total licensed capacity is required"
    else if (parseInt(formData.totalLicensed) <= 0) {
      newErrors.totalLicensed = "Capacity must be greater than 0"
    }

    if (!formData.expirationDate) {
      newErrors.expirationDate = "License expiration date is required"
    }

    if (formData.careTypes.length === 0) {
      newErrors.careTypes = "At least one care type is required"
    }

    setErrors(newErrors)
    return Object.keys(newErrors).length === 0
  }

  const handleSaveAccount = async () => {
    if (!validateOwnerInfo()) {
      toast.error("Please fix the errors before saving", {
        title: "Validation Error"
      })
      return
    }

    // Check authentication
    const userId = getUserId(user)
    if (!userId) {
      toast.error("Session expired. Please log in again.", {
        title: "Authentication Required"
      })
      router.push('/login')
      return
    }

    setIsLoading(true)

    try {
      console.log('💾 [Settings] Saving owner info...')

      // Prepare profile data with nested structure
      const profileData = {
        businessInfo: {
          companyName: formData.companyName.trim(),
          businessType: formData.businessType
        },
        businessAddress: {
          street: formData.street.trim(),
          city: formData.city.trim(),
          state: formData.state,
          zipCode: formData.zipCode.trim(),
          country: "USA"
        },
        businessContact: {
          phone: getCleanPhoneNumber(formData.phone),
          fax: formData.fax.trim() || undefined,
          website: formData.website.trim() || undefined,
          email: formData.email
        }
      }

      console.log('📤 [Settings] Sending profile data:', profileData)

      let response
      if (ownerProfile) {
        // Update existing profile
        response = await DataAPI.ownerProfile.updateProfile(userId, profileData)
      } else {
        // Create new profile
        response = await DataAPI.ownerProfile.createProfile(userId, profileData)
      }

      if (response.success) {
        console.log('✅ [Settings] Profile saved successfully')
        toast.success("Profile updated successfully!", {
          title: "Success"
        })
        // Refresh profile data
        await refetchProfile()
      } else {
        console.error('❌ [Settings] Save failed:', response.message)
        throw new Error(response.message || "Failed to update profile")
      }
    } catch (error: any) {
      console.error('❌ [Settings] Save error:', error)
      toast.error(error.message || "An error occurred while saving", {
        title: "Error"
      })
    } finally {
      setIsLoading(false)
    }
  }

  const handleSaveLicensing = async () => {
    if (!validateLicensing()) {
      toast.error("Please fix the errors before saving", {
        title: "Validation Error"
      })
      return
    }

    // Check authentication
    const userId = getUserId(user)
    if (!userId) {
      toast.error("Session expired. Please log in again.", {
        title: "Authentication Required"
      })
      router.push('/login')
      return
    }

    setIsLoading(true)

    try {
      console.log('💾 [Settings] Saving licensing info to FacilityOwnerProfile...')

      // Prepare licensing data for FacilityOwnerProfile
      const licensingData = {
        licensing: {
          licenseNumber: formData.licenseNumber.trim(),
          totalLicensedCapacity: parseInt(formData.totalLicensed),
          expirationDate: new Date(formData.expirationDate),
          careTypesAuthorized: formData.careTypes,
          licenseStatus: 'active',
          renewalReminder: true
        }
      }

      console.log('📤 [Settings] Sending licensing data to owner profile:', licensingData)

      let response
      if (ownerProfile) {
        // Update existing profile
        response = await DataAPI.ownerProfile.updateProfile(userId, licensingData)
      } else {
        // Create new profile with licensing data
        const fullProfileData = {
          businessInfo: {
            companyName: formData.companyName || "My Company",
            businessType: formData.businessType || "llc"
          },
          businessAddress: {
            street: formData.street || "",
            city: formData.city || "",
            state: formData.state || "",
            zipCode: formData.zipCode || "",
            country: "USA"
          },
          businessContact: {
            phone: formData.phone || "",
            email: formData.email || user?.email || ""
          },
          ...licensingData
        }
        response = await DataAPI.ownerProfile.createProfile(userId, fullProfileData)
      }

      if (response.success) {
        console.log('✅ [Settings] Licensing info saved successfully to FacilityOwnerProfile')
        toast.success("Licensing information updated successfully!", {
          title: "Success"
        })
        // Refresh data
        await refetchProfile()
      } else {
        console.error('❌ [Settings] Licensing save failed:', response.message)
        throw new Error(response.message || "Failed to update licensing information")
      }
    } catch (error: any) {
      console.error('❌ [Settings] Licensing save error:', error)
      toast.error(error.message || "An error occurred while saving", {
        title: "Error"
      })
    } finally {
      setIsLoading(false)
    }
  }

  const handlePasswordChange = async () => {
    if (passwordData.new !== passwordData.confirm) {
      toast.error("New passwords don't match", {
        title: "Error"
      })
      return
    }
    if (passwordData.new.length < 8) {
      toast.error("Password must be at least 8 characters", {
        title: "Error"
      })
      return
    }

    setIsLoading(true)
    try {
      const response = await DataAPI.auth.changePassword({
        currentPassword: passwordData.current,
        newPassword: passwordData.new
      })

      if (response.success) {
        setPasswordData({ current: "", new: "", confirm: "" })
        toast.success("Password updated successfully!", {
          title: "Success"
        })
      } else {
        toast.error(response.message || "Failed to update password", {
          title: "Error"
        })
      }
    } catch (error: any) {
      toast.error(error.message || "An error occurred", {
        title: "Error"
      })
    } finally {
      setIsLoading(false)
    }
  }

  const toggleCareType = (type: string) => {
    setFormData(prev => ({
      ...prev,
      careTypes: prev.careTypes.includes(type)
        ? prev.careTypes.filter(t => t !== type)
        : [...prev.careTypes, type]
    }))
    // Clear error
    if (errors.careTypes) {
      setErrors(prev => ({ ...prev, careTypes: "" }))
    }
  }

  // Show loading state while fetching initial data
  if (isFetching) {
    return (
      <div className="max-w-4xl mx-auto space-y-8 pb-12">
        <div className="flex flex-col items-center justify-center py-20 gap-4">
          <Loader2 className="h-10 w-10 animate-spin text-blue-600" />
          <p className="text-gray-600 font-medium">Loading your profile...</p>
        </div>
      </div>
    )
  }

  // Redirect if not authenticated (after loading)
  if (!isFetching && !user) {
    router.push('/login')
    return (
      <div className="max-w-4xl mx-auto space-y-8 pb-12">
        <div className="flex items-center justify-center py-12">
          <p className="text-gray-600">Redirecting to login...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="max-w-4xl mx-auto space-y-8 pb-12">
      {/* Header */}
      <div className="flex flex-col gap-2">
        <h1 className="font-primary text-3xl md:text-4xl font-bold text-gray-900 tracking-tight">
          Account Settings
        </h1>
        <p className="font-body text-lg text-gray-500">
          Manage your profile information and account security
        </p>
      </div>

      {/* Settings Tabs */}
      <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
        <TabsList className="grid w-full grid-cols-3 h-12 p-1 bg-gray-100/80 backdrop-blur-sm rounded-xl mb-8">
          <TabsTrigger
            value="account"
            className="rounded-lg data-[state=active]:bg-white data-[state=active]:text-[#3F5CEA] data-[state=active]:shadow-sm transition-all duration-200 font-medium"
          >
            <User className="h-4 w-4 mr-2" />
            Owner Info
          </TabsTrigger>
          <TabsTrigger
            value="licensing"
            className="rounded-lg data-[state=active]:bg-white data-[state=active]:text-[#3F5CEA] data-[state=active]:shadow-sm transition-all duration-200 font-medium"
          >
            <FileCheck className="h-4 w-4 mr-2" />
            Licensing
          </TabsTrigger>
          <TabsTrigger
            value="security"
            className="rounded-lg data-[state=active]:bg-white data-[state=active]:text-[#3F5CEA] data-[state=active]:shadow-sm transition-all duration-200 font-medium"
          >
            <Lock className="h-4 w-4 mr-2" />
            Security
          </TabsTrigger>
        </TabsList>

        {/* Owner Info Tab */}
        <TabsContent value="account" className="space-y-6 focus-visible:outline-none focus-visible:ring-0">
          <Card className="overflow-hidden border-none shadow-lg bg-white/80 backdrop-blur-sm ring-1 ring-gray-200/50">
            <CardHeader className="pb-6 pt-8 px-8">
              <div className="flex items-center gap-4">
                <div className="p-3 bg-blue-50 rounded-2xl border border-blue-100">
                  <Building2 className="h-8 w-8 text-[#3F5CEA]" />
                </div>
                <div>
                  <CardTitle className="font-primary text-2xl text-gray-900">Owner Information</CardTitle>
                  <CardDescription className="font-body text-base text-gray-500 mt-1">
                    Update your business and contact information
                  </CardDescription>
                </div>
              </div>
            </CardHeader>
            <CardContent className="p-6 md:p-8 space-y-6 pt-0">
              {/* User Profile Summary */}
              <div className="flex flex-col md:flex-row items-center gap-6 p-6 bg-gradient-to-br from-blue-50 via-indigo-50/50 to-white rounded-2xl border border-blue-100/50">
                <div className="relative">
                  <div className="w-20 h-20 bg-gradient-to-br from-[#3F5CEA] to-indigo-600 rounded-2xl flex items-center justify-center text-white font-bold text-2xl shadow-lg shadow-blue-200">
                    {formData.firstName[0]}{formData.lastName[0]}
                  </div>
                  {user?.verified && (
                    <div className="absolute -bottom-2 -right-2 bg-white p-1 rounded-full shadow-sm">
                      <div className="bg-green-500 rounded-full p-1">
                        <CheckCircle className="h-3 w-3 text-white" />
                      </div>
                    </div>
                  )}
                </div>
                <div className="flex-1 text-center md:text-left space-y-1">
                  <h3 className="font-primary text-2xl font-bold text-gray-900">
                    {formData.firstName} {formData.lastName}
                  </h3>
                  <p className="font-body text-gray-600 font-medium">Facility Owner</p>
                  <p className="font-body text-sm text-gray-500">
                    Member since {user?.createdAt ? new Date(user.createdAt).toLocaleDateString('en-US', { month: 'long', year: 'numeric' }) : 'N/A'}
                  </p>
                </div>
                {user?.verified && (
                  <Badge variant="secondary" className="bg-green-100 text-green-700 px-3 py-1.5 rounded-full text-sm font-medium border border-green-200">
                    Verified Account
                  </Badge>
                )}
              </div>

              {/* Basic Info - Read Only */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="space-y-2">
                  <Label htmlFor="firstName" className="text-sm font-medium text-gray-700">First Name</Label>
                  <Input
                    id="firstName"
                    value={formData.firstName}
                    disabled
                    className="h-11 bg-gray-100 border-gray-200"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="lastName" className="text-sm font-medium text-gray-700">Last Name</Label>
                  <Input
                    id="lastName"
                    value={formData.lastName}
                    disabled
                    className="h-11 bg-gray-100 border-gray-200"
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="email" className="text-sm font-medium text-gray-700">Email Address</Label>
                <Input
                  id="email"
                  type="email"
                  value={formData.email}
                  disabled
                  className="h-11 bg-gray-100 border-gray-200"
                />
                <p className="text-xs text-gray-500">Contact support to change your email address</p>
              </div>

              {/* Business Information */}
              <div className="pt-6 border-t border-gray-200">
                <h3 className="font-semibold text-lg text-gray-900 mb-4">Business Information</h3>

                <div className="space-y-6">
                  <div>
                    <Label htmlFor="phone">Business Phone <span className="text-red-500">*</span></Label>
                    <PhoneInput
                      id="phone"
                      value={formData.phone}
                      onChange={(value) => handleInputChange('phone', value)}
                      className={errors.phone ? "border-red-500" : ""}
                    />
                    {errors.phone && <p className="text-sm text-red-500 mt-1">{errors.phone}</p>}
                  </div>

                  <div>
                    <Label htmlFor="companyName">Company Name <span className="text-red-500">*</span></Label>
                    <Input
                      id="companyName"
                      value={formData.companyName}
                      onChange={(e) => handleInputChange('companyName', e.target.value)}
                      placeholder="Your Company LLC"
                      className={errors.companyName ? "border-red-500" : ""}
                    />
                    {errors.companyName && <p className="text-sm text-red-500 mt-1">{errors.companyName}</p>}
                  </div>

                  <div>
                    <Label htmlFor="businessType">Business Type <span className="text-red-500">*</span></Label>
                    <Select value={formData.businessType} onValueChange={(value) => handleInputChange('businessType', value)}>
                      <SelectTrigger className={errors.businessType ? "border-red-500" : ""}>
                        <SelectValue placeholder="Select business type" />
                      </SelectTrigger>
                      <SelectContent>
                        {ENTITY_TYPES.map((type) => (
                          <SelectItem key={type} value={type}>
                            {type.charAt(0).toUpperCase() + type.slice(1)}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    {errors.businessType && <p className="text-sm text-red-500 mt-1">{errors.businessType}</p>}
                  </div>

                  <div>
                    <Label htmlFor="website">Website <span className="text-gray-400 text-sm">(Optional)</span></Label>
                    <Input
                      id="website"
                      value={formData.website}
                      onChange={(e) => handleInputChange('website', e.target.value)}
                      placeholder="https://yourwebsite.com"
                    />
                  </div>

                  {/* Business Address */}
                  <div className="space-y-4 p-4 bg-gray-50 rounded-lg">
                    <h4 className="font-semibold text-gray-900">Business Address <span className="text-red-500">*</span></h4>

                    <div>
                      <Label htmlFor="street">Street Address <span className="text-red-500">*</span></Label>
                      <SmartAddressInput
                        value={formData.street}
                        onChange={(result) => handleAddressSelect(result)}
                        onAddressChange={(value) => handleInputChange('street', value)}
                        placeholder="Start typing your address..."
                        className={errors.street ? "border-red-500" : ""}
                      />
                      {errors.street && <p className="text-sm text-red-500 mt-1">{errors.street}</p>}
                    </div>

                    <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                      <div>
                        <Label htmlFor="city">City <span className="text-red-500">*</span></Label>
                        <Input
                          id="city"
                          value={formData.city}
                          onChange={(e) => handleInputChange('city', e.target.value)}
                          placeholder="Austin"
                          className={errors.city ? "border-red-500" : ""}
                        />
                        {errors.city && <p className="text-sm text-red-500 mt-1">{errors.city}</p>}
                      </div>

                      <div>
                        <Label htmlFor="state">State <span className="text-red-500">*</span></Label>
                        <Select value={formData.state} onValueChange={(value) => handleInputChange('state', value)}>
                          <SelectTrigger className={errors.state ? "border-red-500" : ""}>
                            <SelectValue placeholder="State" />
                          </SelectTrigger>
                          <SelectContent>
                            {US_STATES.map((state) => (
                              <SelectItem key={state} value={state}>{state}</SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                        {errors.state && <p className="text-sm text-red-500 mt-1">{errors.state}</p>}
                      </div>

                      <div>
                        <Label htmlFor="zipCode">ZIP Code <span className="text-red-500">*</span></Label>
                        <Input
                          id="zipCode"
                          value={formData.zipCode}
                          onChange={(e) => handleInputChange('zipCode', e.target.value)}
                          placeholder="78701"
                          className={errors.zipCode ? "border-red-500" : ""}
                        />
                        {errors.zipCode && <p className="text-sm text-red-500 mt-1">{errors.zipCode}</p>}
                      </div>
                    </div>
                  </div>

                  <div>
                    <Label htmlFor="fax">Fax Number <span className="text-gray-400 text-sm">(Optional)</span></Label>
                    <PhoneInput
                      id="fax"
                      value={formData.fax}
                      onChange={(value) => handleInputChange('fax', value)}
                    />
                  </div>
                </div>
              </div>

              <div className="pt-6 border-t border-gray-100 flex justify-end">
                <Button
                  onClick={handleSaveAccount}
                  disabled={isLoading}
                  className="bg-[#3F5CEA] hover:bg-[#324ac0] text-white px-8 h-11 rounded-xl shadow-lg shadow-blue-200 hover:shadow-blue-300 transition-all duration-300"
                >
                  {isLoading ? (
                    <span className="flex items-center gap-2">
                      <Loader2 className="w-4 h-4 animate-spin" />
                      Saving...
                    </span>
                  ) : (
                    <span className="flex items-center gap-2">
                      <Save className="h-4 w-4" />
                      Save Changes
                    </span>
                  )}
                </Button>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Licensing Tab */}
        <TabsContent value="licensing" className="space-y-6 focus-visible:outline-none focus-visible:ring-0">
          <Card className="overflow-hidden border-none shadow-lg bg-white/80 backdrop-blur-sm ring-1 ring-gray-200/50">
            <CardHeader className="pb-6 pt-8 px-8">
              <div className="flex items-center gap-4">
                <div className="p-3 bg-green-50 rounded-2xl border border-green-100">
                  <FileCheck className="h-8 w-8 text-green-600" />
                </div>
                <div>
                  <CardTitle className="font-primary text-2xl text-gray-900">Licensing Information</CardTitle>
                  <CardDescription className="font-body text-base text-gray-500 mt-1">
                    Manage your facility licensing details
                  </CardDescription>
                </div>
              </div>
            </CardHeader>
            <CardContent className="p-6 md:p-8 space-y-6 pt-0">
              {/* Info message if no licensing data exists yet */}
              {!formData.licenseNumber && !formData.totalLicensed && !formData.expirationDate && (
                <div className="p-4 bg-blue-50 border border-blue-200 rounded-lg">
                  <div className="flex items-start gap-3">
                    <FileCheck className="h-5 w-5 text-blue-600 mt-0.5" />
                    <div>
                      <p className="text-sm font-medium text-blue-900">No Licensing Information Yet</p>
                      <p className="text-sm text-blue-700 mt-1">
                        Add your facility owner license information below. This is your operating license that authorizes
                        you to manage care facilities.
                      </p>
                    </div>
                  </div>
                </div>
              )}

              <div className="space-y-6">
                <div>
                  <Label htmlFor="licenseNumber">License Number <span className="text-red-500">*</span></Label>
                  <Input
                    id="licenseNumber"
                    value={formData.licenseNumber}
                    onChange={(e) => handleInputChange('licenseNumber', e.target.value)}
                    placeholder="ALF-12345"
                    className={errors.licenseNumber ? "border-red-500" : ""}
                  />
                  {errors.licenseNumber && <p className="text-sm text-red-500 mt-1">{errors.licenseNumber}</p>}
                </div>

                <div>
                  <Label htmlFor="totalLicensed">Total Licensed Capacity <span className="text-red-500">*</span></Label>
                  <Input
                    id="totalLicensed"
                    type="number"
                    min="1"
                    value={formData.totalLicensed}
                    onChange={(e) => handleInputChange('totalLicensed', e.target.value)}
                    placeholder="50"
                    className={errors.totalLicensed ? "border-red-500" : ""}
                  />
                  {errors.totalLicensed && <p className="text-sm text-red-500 mt-1">{errors.totalLicensed}</p>}
                  <p className="text-xs text-gray-500 mt-1">Total number of licensed beds</p>
                </div>

                <div>
                  <Label htmlFor="expirationDate">License Expiration Date <span className="text-red-500">*</span></Label>
                  <Input
                    id="expirationDate"
                    type="date"
                    value={formData.expirationDate}
                    onChange={(e) => handleInputChange('expirationDate', e.target.value)}
                    className={errors.expirationDate ? "border-red-500" : ""}
                    min={new Date().toISOString().split('T')[0]}
                  />
                  {errors.expirationDate && <p className="text-sm text-red-500 mt-1">{errors.expirationDate}</p>}
                  <p className="text-xs text-gray-500 mt-1">We'll remind you before it expires</p>
                </div>

                {/* Care Types */}
                <div>
                  <Label>Care Types Offered <span className="text-red-500">*</span></Label>
                  {errors.careTypes && <p className="text-sm text-red-500 mt-1">{errors.careTypes}</p>}
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-3 mt-2">
                    {CARE_TYPES.map((type) => (
                      <div
                        key={type}
                        onClick={() => toggleCareType(type)}
                        className={`p-3 border-2 rounded-lg cursor-pointer transition-all ${formData.careTypes.includes(type)
                          ? 'border-blue-500 bg-blue-50'
                          : 'border-gray-200 hover:border-gray-300'
                          }`}
                      >
                        <div className="flex items-center">
                          <div className={`w-5 h-5 rounded-md border-2 flex items-center justify-center mr-3 ${formData.careTypes.includes(type)
                            ? 'border-blue-500 bg-blue-500'
                            : 'border-gray-300'
                            }`}>
                            {formData.careTypes.includes(type) && (
                              <CheckCircle className="h-4 w-4 text-white" />
                            )}
                          </div>
                          <span className="text-sm font-medium">{type}</span>
                        </div>
                      </div>
                    ))}
                  </div>
                  <p className="text-xs text-gray-500 mt-1">Select at least one care type</p>
                </div>
              </div>

              <div className="pt-6 border-t border-gray-100 flex justify-end">
                <Button
                  onClick={handleSaveLicensing}
                  disabled={isLoading}
                  className="bg-[#3F5CEA] hover:bg-[#324ac0] text-white px-8 h-11 rounded-xl shadow-lg shadow-blue-200 hover:shadow-blue-300 transition-all duration-300"
                >
                  {isLoading ? (
                    <span className="flex items-center gap-2">
                      <Loader2 className="w-4 h-4 animate-spin" />
                      Saving...
                    </span>
                  ) : (
                    <span className="flex items-center gap-2">
                      <Save className="h-4 w-4" />
                      Save Changes
                    </span>
                  )}
                </Button>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Security Tab */}
        <TabsContent value="security" className="space-y-6 focus-visible:outline-none focus-visible:ring-0">
          <Card className="overflow-hidden border-none shadow-lg bg-white/80 backdrop-blur-sm ring-1 ring-gray-200/50">
            <CardHeader className="pb-6 pt-8 px-8">
              <div className="flex items-center gap-4">
                <div className="p-3 bg-amber-100 rounded-2xl border border-amber-200">
                  <ShieldCheck className="h-8 w-8 text-amber-600" />
                </div>
                <div>
                  <CardTitle className="font-primary text-2xl text-gray-900">Password & Security</CardTitle>
                  <CardDescription className="font-body text-base text-gray-500 mt-1">
                    Manage your password and security preferences
                  </CardDescription>
                </div>
              </div>
            </CardHeader>
            <CardContent className="p-6 md:p-8 space-y-8 pt-0">
              <div className="space-y-6">
                <div className="flex items-center justify-between">
                  <h3 className="font-primary text-lg font-semibold text-gray-900">Change Password</h3>
                </div>

                <div className="space-y-4">
                  <div className="space-y-2">
                    <Label htmlFor="currentPassword" className="text-sm font-medium text-gray-700">Current Password</Label>
                    <div className="relative">
                      <Input
                        id="currentPassword"
                        type={showCurrentPassword ? "text" : "password"}
                        value={passwordData.current}
                        onChange={(e) => setPasswordData(prev => ({ ...prev, current: e.target.value }))}
                        className="h-11 bg-gray-50/50 border-gray-200 focus:bg-white transition-colors pr-10"
                        placeholder="Enter your current password"
                      />
                      <Button
                        variant="ghost"
                        size="sm"
                        className="absolute right-2 top-1.5 h-8 w-8 p-0 hover:bg-gray-100 hover:text-gray-900 rounded-full text-gray-500"
                        onClick={() => setShowCurrentPassword(!showCurrentPassword)}
                        type="button"
                      >
                        {showCurrentPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                      </Button>
                    </div>
                  </div>

                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div className="space-y-2">
                      <Label htmlFor="newPassword" className="text-sm font-medium text-gray-700">New Password</Label>
                      <div className="relative">
                        <Input
                          id="newPassword"
                          type={showNewPassword ? "text" : "password"}
                          value={passwordData.new}
                          onChange={(e) => setPasswordData(prev => ({ ...prev, new: e.target.value }))}
                          className="h-11 bg-gray-50/50 border-gray-200 focus:bg-white transition-colors pr-10"
                          placeholder="Min. 8 characters"
                        />
                        <Button
                          variant="ghost"
                          size="sm"
                          className="absolute right-2 top-1.5 h-8 w-8 p-0 hover:bg-gray-100 hover:text-gray-900 rounded-full text-gray-500"
                          onClick={() => setShowNewPassword(!showNewPassword)}
                          type="button"
                        >
                          {showNewPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                        </Button>
                      </div>
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="confirmPassword" className="text-sm font-medium text-gray-700">Confirm New Password</Label>
                      <div className="relative">
                        <Input
                          id="confirmPassword"
                          type={showConfirmPassword ? "text" : "password"}
                          value={passwordData.confirm}
                          onChange={(e) => setPasswordData(prev => ({ ...prev, confirm: e.target.value }))}
                          className="h-11 bg-gray-50/50 border-gray-200 focus:bg-white transition-colors pr-10"
                          placeholder="Re-enter new password"
                        />
                        <Button
                          variant="ghost"
                          size="sm"
                          className="absolute right-2 top-1.5 h-8 w-8 p-0 hover:bg-gray-100 hover:text-gray-900 rounded-full text-gray-500"
                          onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                          type="button"
                        >
                          {showConfirmPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                        </Button>
                      </div>
                    </div>
                  </div>
                </div>

                <div className="pt-4 flex justify-end">
                  <Button
                    onClick={handlePasswordChange}
                    disabled={isLoading || !passwordData.current || !passwordData.new || !passwordData.confirm}
                    className="bg-[#3F5CEA] hover:bg-[#324ac0] text-white px-8 h-11 rounded-xl shadow-lg shadow-blue-200 hover:shadow-blue-300 transition-all duration-300"
                  >
                    {isLoading ? "Updating..." : "Update Password"}
                  </Button>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  )
}
