"use client"

import { useState, useEffect } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card"
import { Label } from "@/components/ui/label"
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 { ArrowLeft, ArrowRight, Building2, MapPin, Phone, Mail, FileCheck, CheckCircle, AlertCircle, Loader2, User, Building, FileText } from "lucide-react"
import { DocumentUploader } from "@/components/ui/document-uploader"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { useToast } from "@/components/ui/toast"
import { DataAPI } from "@/lib/data-api"
import Link from "next/link"

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 = ["Corporation", "LLC", "Individual", "Partnership", "Other"]

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

interface UploadedDocument {
  type: string
  name: string
  url: string
  size?: number
  uploadedAt?: Date
}

interface FormData {
  // STEP 1: Owner Information (REQUIRED)
  phone: string
  ownerName: string
  ownerWebsite: string // Owner/Company website
  typeOfEntity: string
  companyName: string // REQUIRED - company name must be provided
  ownerStreet: string
  ownerCity: string
  ownerState: string
  ownerZipCode: string
  fax: string // optional

  // STEP 2: Licensing (REQUIRED)
  licenseNumber: string
  totalLicensed: string
  expirationDate: string
  careTypes: string[]
  licenseDocuments: UploadedDocument[] // REQUIRED - at least one license document must be uploaded
}

export default function CompleteProfilePage() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const toast = useToast()

  // IMMEDIATE FIX: Clear corrupted localStorage before anything else
  if (typeof window !== 'undefined') {
    try {
      const savedDraft = localStorage.getItem('facility-profile-draft')
      if (savedDraft) {
        const draft = JSON.parse(savedDraft)
        // Check if ANY phone field is corrupted (object instead of string)
        const hasCorruptedData =
          (draft.phone && typeof draft.phone !== 'string') ||
          (draft.facilityPhone && typeof draft.facilityPhone !== 'string') ||
          (draft.fax && typeof draft.fax !== 'string')

        if (hasCorruptedData) {
          console.log('🧹 Clearing corrupted draft data...')
          localStorage.removeItem('facility-profile-draft')
          // Force reload to ensure clean state
          window.location.reload()
        }
      }
    } catch (e) {
      console.log('🧹 Clearing invalid draft data...')
      localStorage.removeItem('facility-profile-draft')
      window.location.reload()
    }
  }

  const [currentStep, setCurrentStep] = useState(1)
  const [isLoading, setIsLoading] = useState(false)
  const [errors, setErrors] = useState<Record<string, string>>({})

  const email = searchParams?.get('email') || ""
  const userId = searchParams?.get('userId') || ""

  const [formData, setFormData] = useState<FormData>({
    // Step 1: Owner Info (REQUIRED)
    phone: "",
    ownerName: "",
    ownerWebsite: "",
    typeOfEntity: "",
    companyName: "", // REQUIRED
    ownerStreet: "",
    ownerCity: "",
    ownerState: "",
    ownerZipCode: "",
    fax: "",

    // Step 2: Licensing (REQUIRED)
    licenseNumber: "",
    totalLicensed: "",
    expirationDate: "",
    careTypes: [],
    licenseDocuments: [] // REQUIRED - at least one document must be uploaded
  })

  // Redirect if no email or userId
  useEffect(() => {
    if (!email || !userId) {
      router.push('/register')
    }
  }, [email, userId, router])

  // Clear corrupted localStorage on mount
  useEffect(() => {
    try {
      const savedDraft = localStorage.getItem('facility-profile-draft')
      if (savedDraft) {
        const draft = JSON.parse(savedDraft)
        // Check if phone is corrupted
        if (draft.phone && typeof draft.phone === 'object') {
          console.log('Clearing corrupted draft from localStorage')
          localStorage.removeItem('facility-profile-draft')
        }
      }
    } catch (e) {
      // If JSON parsing fails, clear it
      localStorage.removeItem('facility-profile-draft')
    }
  }, [])

  // Load saved draft from localStorage (only once on mount)
  useEffect(() => {
    const savedDraft = localStorage.getItem('facility-profile-draft')
    if (savedDraft) {
      try {
        const draft = JSON.parse(savedDraft)

        // Sanitize phone values to ensure they're strings
        if (draft.phone && typeof draft.phone === 'object') {
          draft.phone = ''
        }
        if (draft.fax && typeof draft.fax === 'object') {
          draft.fax = ''
        }

        setFormData(prev => ({ ...prev, ...draft }))

        // Show toast notification
        setTimeout(() => {
          toast.success("Your previous progress has been restored.", {
            title: "Draft Restored"
          })
        }, 100)
      } catch (e) {
        console.error('Error loading draft:', e)
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []) // Run only once on mount

  // Auto-save draft to localStorage whenever formData changes (with debounce)
  useEffect(() => {
    // Skip auto-save on initial mount
    const timeoutId = setTimeout(() => {
      try {
        // Ensure phone values are strings before saving
        const sanitizedData = {
          ...formData,
          phone: typeof formData.phone === 'string' ? formData.phone : '',
          fax: typeof formData.fax === 'string' ? formData.fax : ''
        }
        localStorage.setItem('facility-profile-draft', JSON.stringify(sanitizedData))
      } catch (e) {
        console.error('Error saving draft:', e)
      }
    }, 500) // Debounce for 500ms

    return () => clearTimeout(timeoutId)
  }, [formData])

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

  const handleOwnerAddressSelect = (result: AddressResult) => {
    console.log('CompleteProfile - handleOwnerAddressSelect called with:', result)

    setFormData((prev) => ({
      ...prev,
      ownerStreet: result.address,
      ownerCity: result.city,
      ownerState: result.state,
      ownerZipCode: result.zipCode
    }))

    // Clear related errors
    setErrors((prev) => ({
      ...prev,
      ownerStreet: "",
      ownerCity: "",
      ownerState: "",
      ownerZipCode: ""
    }))
  }

  const validateStep1 = (): 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.ownerName.trim()) newErrors.ownerName = "Owner name is required"
    if (!formData.typeOfEntity) newErrors.typeOfEntity = "Entity type is required"
    
    // Company Name is now REQUIRED
    if (!formData.companyName.trim()) {
      newErrors.companyName = "Company name is required"
    }
    
    if (!formData.ownerStreet.trim()) newErrors.ownerStreet = "Street address is required"
    if (!formData.ownerCity.trim()) newErrors.ownerCity = "City is required"
    if (!formData.ownerState) newErrors.ownerState = "State is required"
    if (!formData.ownerZipCode.trim()) newErrors.ownerZipCode = "ZIP code is required"
    else if (!/^\d{5}(-\d{4})?$/.test(formData.ownerZipCode)) {
      newErrors.ownerZipCode = "Invalid ZIP code format"
    }

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

  const validateStep2 = (): 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"
    } else {
      const expirationDate = new Date(formData.expirationDate)
      const today = new Date()
      today.setHours(0, 0, 0, 0)

      if (expirationDate < today) {
        newErrors.expirationDate = "License expiration date cannot be in the past"
      }
    }

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

    // License Upload is now REQUIRED - at least one document must be uploaded
    if (!formData.licenseDocuments || formData.licenseDocuments.length === 0) {
      newErrors.licenseDocuments = "At least one license document is required. Please upload your business license or facility license document."
    }

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

  const handleNext = () => {
    let isValid = false

    if (currentStep === 1) {
      isValid = validateStep1()
    } else if (currentStep === 2) {
      isValid = validateStep2()
    }

    if (isValid) {
      setCurrentStep(prev => Math.min(prev + 1, 2))
      window.scrollTo({ top: 0, behavior: 'smooth' })
    } else {
      toast.error("Please fix the errors before proceeding", {
        title: "Validation Error"
      })
    }
  }

  const handleBack = () => {
    setCurrentStep(prev => Math.max(prev - 1, 1))
    window.scrollTo({ top: 0, behavior: 'smooth' })
  }

  const handleSubmit = async () => {
    // Validate Step 2 (licensing) before submitting
    if (!validateStep2()) {
      toast.error("Please fix the errors before submitting", {
        title: "Validation Error"
      })
      return
    }

    setIsLoading(true)

    try {
      // STEP 1: Owner Info (REQUIRED)
      const payload: any = {
        userId,
        phone: getCleanPhoneNumber(formData.phone),
        ownerName: formData.ownerName.trim(),
        ownerWebsite: formData.ownerWebsite.trim(), // Owner/Company website
        typeOfEntity: formData.typeOfEntity,
        companyName: formData.companyName.trim(), // REQUIRED
        ownerStreet: formData.ownerStreet.trim(),
        ownerCity: formData.ownerCity.trim(),
        ownerState: formData.ownerState,
        ownerZipCode: formData.ownerZipCode.trim(),
        fax: formData.fax || undefined,
        
        // Facility basic info - using company name (REQUIRED)
        facilityName: formData.companyName.trim(),
        facilityType: formData.careTypes[0] || "Assisted Living",
        licenseNumber: formData.licenseNumber.trim(),
        description: `${formData.companyName.trim()} - A senior living facility`,
        
        // Facility location - using owner address as default
        address: formData.ownerStreet.trim(),
        city: formData.ownerCity.trim(),
        state: formData.ownerState,
        zipCode: formData.ownerZipCode.trim(),
        
        // Facility contact
        facilityPhone: getCleanPhoneNumber(formData.phone),
        facilityEmail: email,
        website: "",
        
        // Capacity - using license info
        totalCapacity: parseInt(formData.totalLicensed.trim()) || 0,
        availableCapacity: parseInt(formData.totalLicensed.trim()) || 0,
        
        // Pricing - defaults
        minPrice: 0,
        maxPrice: 0,
        
        // Services
        amenities: [],
        careTypes: formData.careTypes,
        medicalServices: [],
        
        // License documents (REQUIRED)
        licenseDocuments: formData.licenseDocuments.map(doc => ({
          type: 'business_license', // Default type for license documents
          name: doc.name,
          url: doc.url,
          uploadedAt: doc.uploadedAt || new Date()
        }))
      }

      console.log('Submitting profile:', payload)

      const response = await DataAPI.auth.completeFacilityProfile(payload)

      if (response.success) {
        // Clear draft
        localStorage.removeItem('facility-profile-draft')

        toast.success("Your profile is pending admin approval.", {
          title: "Profile Submitted Successfully!"
        })

        setTimeout(() => {
          router.push('/facility/registration-complete')
        }, 1000)
      } else {
        throw new Error(response.message || 'Failed to submit profile')
      }
    } catch (error: any) {
      console.error('Profile submission error:', error)
      toast.error(error.message || "An error occurred. Please try again.", {
        title: "Submission Failed"
      })
    } finally {
      setIsLoading(false)
    }
  }

  const toggleCareType = (type: string) => {
    setFormData(prev => ({
      ...prev,
      careTypes: prev.careTypes.includes(type)
        ? prev.careTypes.filter(t => t !== type)
        : [...prev.careTypes, type]
    }))
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-orange-50 py-8 px-4">
      <div className="max-w-4xl mx-auto">
        {/* Header */}
        <div className="text-center mb-8">
          <Link href="/login" className="inline-flex items-center text-blue-600 hover:text-blue-700 mb-4">
            <ArrowLeft className="h-4 w-4 mr-2" />
            Back to Login
          </Link>
          <h1 className="text-3xl font-bold text-gray-900 mb-2">Complete Your Profile</h1>
          <p className="text-gray-600">Please provide your facility information to continue</p>
          <p className="text-sm text-gray-500 mt-2">
            Fields marked with <span className="text-red-500">*</span> are required
          </p>
        </div>

        {/* Progress Indicator */}
        <div className="mb-8">
          <div className="flex items-center justify-center">
            {[1, 2].map((step) => (
              <div key={step} className="flex items-center">
                <div className={`flex items-center justify-center w-12 h-12 rounded-full border-2 ${step === currentStep
                    ? 'border-blue-600 bg-blue-600 text-white'
                    : step < currentStep
                      ? 'border-green-600 bg-green-600 text-white'
                      : 'border-gray-300 bg-white text-gray-400'
                  }`}>
                  {step < currentStep ? (
                    <CheckCircle className="h-6 w-6" />
                  ) : step === 1 ? (
                    <User className="h-6 w-6" />
                  ) : (
                    <FileCheck className="h-6 w-6" />
                  )}
                </div>
                {step < 2 && (
                  <div className={`w-32 h-1 mx-2 ${step < currentStep ? 'bg-green-600' : 'bg-gray-300'
                    }`} />
                )}
              </div>
            ))}
          </div>
          <div className="flex justify-center mt-2 space-x-24">
            <span className={`text-sm ${currentStep === 1 ? 'font-semibold text-blue-600' : currentStep > 1 ? 'text-green-600' : 'text-gray-400'}`}>
              Owner Info
            </span>
            <span className={`text-sm ${currentStep === 2 ? 'font-semibold text-blue-600' : currentStep > 2 ? 'text-green-600' : 'text-gray-400'}`}>
              Licensing
            </span>
          </div>
        </div>

        {/* Form Card */}
        <Card className="shadow-lg border-t-4 border-t-blue-600">
          <CardHeader>
            <CardTitle>
              {currentStep === 1 && "Step 1: Owner Information (Required)"}
              {currentStep === 2 && "Step 2: Licensing (Required)"}
            </CardTitle>
            <CardDescription>
              {currentStep === 1 && "Tell us about yourself and your company"}
              {currentStep === 2 && "Complete licensing information for your facility"}
            </CardDescription>
          </CardHeader>
          <CardContent>
            {/* STEP 1: Owner Information */}
            {currentStep === 1 && (
              <div className="space-y-6">
                {/* Phone Number */}
                <div>
                  <Label htmlFor="phone">Your Phone Number <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>

                {/* Owner Name and Website */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor="ownerName">Owner/Administrator Name <span className="text-red-500">*</span></Label>
                    <Input
                      id="ownerName"
                      value={formData.ownerName}
                      onChange={(e) => handleInputChange('ownerName', e.target.value)}
                      placeholder="John Smith"
                      className={errors.ownerName ? "border-red-500" : ""}
                    />
                    {errors.ownerName && <p className="text-sm text-red-500 mt-1">{errors.ownerName}</p>}
                  </div>
                  
                  <div>
                    <Label htmlFor="ownerWebsite">Company Website</Label>
                    <Input
                      id="ownerWebsite"
                      type="url"
                      value={formData.ownerWebsite}
                      onChange={(e) => handleInputChange('ownerWebsite', e.target.value)}
                      placeholder="https://www.example.com"
                      className={errors.ownerWebsite ? "border-red-500" : ""}
                    />
                    {errors.ownerWebsite && <p className="text-sm text-red-500 mt-1">{errors.ownerWebsite}</p>}
                    <p className="text-xs text-gray-500 mt-1">Optional: Your company or business website</p>
                  </div>
                </div>

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

                {/* Company Name (REQUIRED) */}
                <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="Smith Senior Living LLC"
                    className={errors.companyName ? "border-red-500" : ""}
                  />
                  {errors.companyName && <p className="text-sm text-red-500 mt-1">{errors.companyName}</p>}
                  <p className="text-xs text-gray-500 mt-1">Required for facility listing claims</p>
                </div>

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

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

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

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

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

                {/* Fax (Optional) */}
                <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>
            )}

            {/* STEP 2: Licensing & Details */}
            {currentStep === 2 && (
              <div className="space-y-6">
                {/* License Information */}
                <div className="space-y-4 p-4 bg-green-50 rounded-lg">
                  <h3 className="font-semibold text-gray-900 flex items-center">
                    <FileCheck className="h-5 w-5 mr-2 text-green-600" />
                    License Information
                  </h3>

                  <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>
                </div>

                {/* Care Types (REQUIRED) */}
                <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>

                {/* License Document Upload (REQUIRED) */}
                <div className="space-y-2">
                  <div className="flex items-center gap-2">
                    <FileText className="h-5 w-5 text-blue-600" />
                    <Label>
                      License Document Upload <span className="text-red-500">*</span>
                    </Label>
                  </div>
                  {errors.licenseDocuments && (
                    <Alert variant="destructive" className="mt-2">
                      <AlertCircle className="h-4 w-4" />
                      <AlertDescription>{errors.licenseDocuments}</AlertDescription>
                    </Alert>
                  )}
                  <DocumentUploader
                    documents={formData.licenseDocuments}
                    onDocumentsChange={(docs) => {
                      handleInputChange('licenseDocuments', docs)
                      // Clear error when documents are uploaded
                      if (docs.length > 0 && errors.licenseDocuments) {
                        setErrors((prev) => ({ ...prev, licenseDocuments: "" }))
                      }
                    }}
                    maxFiles={3}
                    maxSizeInMB={10}
                    defaultDocumentType="business_license"
                    userId={userId}
                  />
                  <p className="text-xs text-gray-500 mt-2">
                    Upload your business license or facility license document (PDF, DOC, DOCX, JPG, PNG). 
                    This is required to verify your legitimacy for listing claims.
                  </p>
                  {formData.licenseDocuments.length > 0 && (
                    <p className="text-xs text-green-600 mt-1 flex items-center gap-1">
                      <CheckCircle className="h-3 w-3" />
                      {formData.licenseDocuments.length} document(s) uploaded
                    </p>
                  )}
                </div>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Navigation Buttons */}
        <div className="flex justify-between mt-6">
          <Button
            onClick={handleBack}
            disabled={currentStep === 1 || isLoading}
            variant="outline"
            className="px-6"
          >
            <ArrowLeft className="h-4 w-4 mr-2" />
            Back
          </Button>

          {currentStep < 2 ? (
            <Button
              onClick={handleNext}
              disabled={isLoading}
              className="px-6 bg-blue-600 hover:bg-blue-700"
            >
              Next
              <ArrowRight className="h-4 w-4 ml-2" />
            </Button>
          ) : (
            <Button
              onClick={handleSubmit}
              disabled={isLoading}
              className="px-6 bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800"
            >
              {isLoading ? (
                <>
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                  Submitting...
                </>
              ) : (
                <>
                  Submit Profile
                  <CheckCircle className="h-4 w-4 ml-2" />
                </>
              )}
            </Button>
          )}
        </div>

        {/* Help Text */}
        <div className="mt-6 text-center">
          <p className="text-sm text-gray-500">
            Need help? Contact us at{" "}
            <a href="mailto:support@geezerguide.com" className="text-blue-600 hover:underline">
              support@geezerguide.com
            </a>
          </p>
        </div>
      </div>
    </div>
  )
}
