"use client"

import { useState, useEffect } from "react"
import { useParams, useRouter } from "next/navigation"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Checkbox } from "@/components/ui/checkbox"
import { Badge } from "@/components/ui/badge"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import {
  Building, MapPin, Phone, Mail, Globe, FileText, Users, Bed, DollarSign,
  Image as ImageIcon, Award, ClipboardCheck, Loader2, Save, ArrowLeft,
  AlertCircle, Plus, X, Calendar, CheckCircle
} from "lucide-react"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import Link from "next/link"
import { DataAPI } from "@/lib/data-api"
import { useToast } from "@/components/ui/toast"
import { useSubscription } from "@/hooks/use-subscription"
import { SubscriptionPrompt } from "@/components/subscription/subscription-prompt"
import { FacilityImageUploader } from "@/components/facility/facility-image-uploader"

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 CARE_TYPES = [
  'Independent Living',
  'Assisted Living',
  'Memory Care',
  'Skilled Nursing',
  'Rehabilitation',
  'Hospice Care',
  'Adult Day Care',
  'Home Care'
]

const AMENITIES = [
  'Private Rooms', 'Semi-Private Rooms', 'Wheelchair Accessible', 
  'Emergency Call System', ' 24-Hour Staff', 'Security System',
  'Dining Room', 'Activity Room', 'Library', 'Chapel',
  'Beauty/Barber Shop', 'Garden/Patio', 'Fitness Center', 'Pool',
  'WiFi', 'Cable TV', 'Pet Friendly', 'Transportation Services',
  'Housekeeping', 'Laundry Services', 'Meal Services'
]

const MEDICAL_SERVICES = [
  'Medication Management', 'Physical Therapy', 'Occupational Therapy',
  'Speech Therapy', 'Wound Care', 'Pain Management',
  'Diabetes Care', 'Dementia Care', 'Hospice Services',
  'Dental Services', 'Podiatry', 'Vision Care',
  'On-site Physician', 'Nursing Services', 'Emergency Response'
]

export default function EditFacilityPage() {
  const params = useParams()
  const toast = useToast()
  const router = useRouter()
  const facilityId = params?.id as string

  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [activeTab, setActiveTab] = useState('basic')
  const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false)
  const [initialFormState, setInitialFormState] = useState<any>(null)
  const [showSuccessDialog, setShowSuccessDialog] = useState(false)
  const [updatedSections, setUpdatedSections] = useState<string[]>([])
  
  // Subscription checks
  const { canEdit, isLoading: subscriptionLoading } = useSubscription()
  const [showSubscriptionPrompt, setShowSubscriptionPrompt] = useState(false)
  
  // Basic Information
  const [name, setName] = useState('')
  const [description, setDescription] = useState('')
  const [programType, setProgramType] = useState('')
  const [serviceType, setServiceType] = useState('')
  const [facilityExternalId, setFacilityExternalId] = useState('')
  
  // Location
  const [address, setAddress] = useState('')
  const [city, setCity] = useState('')
  const [state, setState] = useState('')
  const [zipCode, setZipCode] = useState('')
  const [county, setCounty] = useState('')
  const [stateRegion, setStateRegion] = useState('')
  const [hhscSubOffice, setHhscSubOffice] = useState('')
  const [latitude, setLatitude] = useState('')
  const [longitude, setLongitude] = useState('')
  
  // Contact
  const [phone, setPhone] = useState('')
  const [email, setEmail] = useState('')
  const [website, setWebsite] = useState('')
  const [fax, setFax] = useState('')
  const [providerEmail, setProviderEmail] = useState('')
  
  // Licensing
  const [licenseNumber, setLicenseNumber] = useState('')
  const [licenseType, setLicenseType] = useState('')
  const [effectiveDate, setEffectiveDate] = useState('')
  const [expirationDate, setExpirationDate] = useState('')
  const [initialLicenseDate, setInitialLicenseDate] = useState('')
  const [facilityLicensed, setFacilityLicensed] = useState(true)
  const [facilityCertified, setFacilityCertified] = useState(false)
  const [medicareProviderNumber, setMedicareProviderNumber] = useState('')
  const [medicaidProviderNumber, setMedicaidProviderNumber] = useState('')
  const [alzheimerCertified, setAlzheimerCertified] = useState(false)
  const [alzheimerCertificateNo, setAlzheimerCertificateNo] = useState('')
  const [alzheimerCertEffectiveDate, setAlzheimerCertEffectiveDate] = useState('')
  const [alzheimerCertExpirationDate, setAlzheimerCertExpirationDate] = useState('')
  
  // Care Types
  const [selectedCareTypes, setSelectedCareTypes] = useState<string[]>([])
  
  // Capacity
  const [totalLicensed, setTotalLicensed] = useState(6)
  const [licensedOnlyBeds, setLicensedOnlyBeds] = useState(0)
  const [medicaidOnlyBeds, setMedicaidOnlyBeds] = useState(0)
  const [medicareOnlyBeds, setMedicareOnlyBeds] = useState(0)
  const [medicaidMedicareBeds, setMedicaidMedicareBeds] = useState(0)
  const [icfiidBeds, setIcfiidBeds] = useState(0)
  const [alzheimerCapacity, setAlzheimerCapacity] = useState(0)
  const [availableBeds, setAvailableBeds] = useState(0)
  
  // Pricing
  const [minPrice, setMinPrice] = useState(0)
  const [maxPrice, setMaxPrice] = useState(0)
  const [currency, setCurrency] = useState('USD')
  const [pricingPeriod, setPricingPeriod] = useState('monthly')
  const [pricingDetails, setPricingDetails] = useState('')
  
  // Images & Media
  const [images, setImages] = useState<string[]>([])
  const [virtualTour, setVirtualTour] = useState('')
  
  // Amenities & Services
  const [selectedAmenities, setSelectedAmenities] = useState<string[]>([])
  const [selectedMedicalServices, setSelectedMedicalServices] = useState<string[]>([])
  
  // Staffing
  const [totalStaff, setTotalStaff] = useState(0)
  const [medicalStaff, setMedicalStaff] = useState(0)
  const [certifiedStaff, setCertifiedStaff] = useState(0)
  const [staffToResidentRatio, setStaffToResidentRatio] = useState('')
  const [administrator, setAdministrator] = useState('')
  
  // Certifications
  const [certifications, setCertifications] = useState<any[]>([])
  
  // Inspection Scores
  const [inspectionScores, setInspectionScores] = useState<any[]>([])
  
  // Status
  const [facilityStatus, setFacilityStatus] = useState('active')

  useEffect(() => {
    loadFacility()
  }, [facilityId])

  // Track unsaved changes
  useEffect(() => {
    if (initialFormState) {
      const currentState = {
        name, description, programType, serviceType, facilityExternalId,
        address, city, state, zipCode, county, stateRegion, hhscSubOffice,
        phone, email, website, fax, providerEmail,
        licenseNumber, selectedCareTypes, totalLicensed, minPrice, maxPrice
      }
      const hasChanges = JSON.stringify(currentState) !== JSON.stringify(initialFormState)
      setHasUnsavedChanges(hasChanges)
    }
  }, [
    name, description, programType, serviceType, facilityExternalId,
    address, city, state, zipCode, county, stateRegion, hhscSubOffice,
    phone, email, website, fax, providerEmail,
    licenseNumber, selectedCareTypes, totalLicensed, minPrice, maxPrice,
    initialFormState
  ])

  // Warn before leaving page with unsaved changes
  useEffect(() => {
    const handleBeforeUnload = (e: BeforeUnloadEvent) => {
      if (hasUnsavedChanges && !saving) {
        e.preventDefault()
        e.returnValue = ''
        return ''
      }
    }

    window.addEventListener('beforeunload', handleBeforeUnload)
    return () => window.removeEventListener('beforeunload', handleBeforeUnload)
  }, [hasUnsavedChanges, saving])

  const loadFacility = async () => {
    try {
      setLoading(true)
      const response = await DataAPI.facilities.getFacility(facilityId)

      if (response.success && response.data) {
        const facility = response.data.facility as any
        
        // Basic Information
        setName(facility.name || '')
        setDescription(facility.description || '')
        setProgramType(facility.programType || '')
        setServiceType(facility.serviceType || '')
        setFacilityExternalId(facility.facilityId || '')
        
        // Location
        setAddress(facility.location?.address || '')
        setCity(facility.location?.city || '')
        setState(facility.location?.state || '')
        setZipCode(facility.location?.zipCode || '')
        setCounty(facility.location?.county || '')
        setStateRegion(facility.location?.stateRegion || '')
        setHhscSubOffice(facility.location?.hhscSubOffice || '')
        setLatitude(facility.location?.coordinates?.lat?.toString() || '')
        setLongitude(facility.location?.coordinates?.lng?.toString() || '')
        
        // Contact
        setPhone(facility.contact?.phone || '')
        setEmail(facility.contact?.email || '')
        setWebsite(facility.contact?.website || '')
        setFax(facility.contact?.fax || '')
        setProviderEmail(facility.contact?.providerEmail || '')
        
        // Licensing
        setLicenseNumber(facility.licensing?.licenseNumber || '')
        setLicenseType(facility.licensing?.licenseType || '')
        setEffectiveDate(facility.licensing?.effectiveDate ? new Date(facility.licensing.effectiveDate).toISOString().split('T')[0] : '')
        setExpirationDate(facility.licensing?.expirationDate ? new Date(facility.licensing.expirationDate).toISOString().split('T')[0] : '')
        setInitialLicenseDate(facility.licensing?.initialLicenseDate ? new Date(facility.licensing.initialLicenseDate).toISOString().split('T')[0] : '')
        setFacilityLicensed(facility.licensing?.facilityLicensed || false)
        setFacilityCertified(facility.licensing?.facilityCertified || false)
        setMedicareProviderNumber(facility.licensing?.medicareProviderNumber || '')
        setMedicaidProviderNumber(facility.licensing?.medicaidProviderNumber || '')
        setAlzheimerCertified(facility.licensing?.alzheimerCertified || false)
        setAlzheimerCertificateNo(facility.licensing?.alzheimerCertificateNo || '')
        setAlzheimerCertEffectiveDate(facility.licensing?.alzheimerCertEffectiveDate ? new Date(facility.licensing.alzheimerCertEffectiveDate).toISOString().split('T')[0] : '')
        setAlzheimerCertExpirationDate(facility.licensing?.alzheimerCertExpirationDate ? new Date(facility.licensing.alzheimerCertExpirationDate).toISOString().split('T')[0] : '')
        
        // Care Types
        setSelectedCareTypes(facility.careTypes || [])
        
        // Capacity
        setTotalLicensed(facility.capacity?.totalLicensed || 6)
        setLicensedOnlyBeds(facility.capacity?.licensedOnlyBeds || 0)
        setMedicaidOnlyBeds(facility.capacity?.medicaidOnlyBeds || 0)
        setMedicareOnlyBeds(facility.capacity?.medicareOnlyBeds || 0)
        setMedicaidMedicareBeds(facility.capacity?.medicaidMedicareBeds || 0)
        setIcfiidBeds(facility.capacity?.icfiidBeds || 0)
        setAlzheimerCapacity(facility.capacity?.alzheimerCapacity || 0)
        setAvailableBeds(facility.capacity?.available || 0)
        
        // Pricing
        setMinPrice(facility.pricing?.min || 0)
        setMaxPrice(facility.pricing?.max || 0)
        setCurrency(facility.pricing?.currency || 'USD')
        setPricingPeriod(facility.pricing?.period || 'monthly')
        setPricingDetails(facility.pricing?.details || '')
        
        // Images & Media
        setImages(facility.images || [])
        setVirtualTour(facility.virtualTour || '')
        
        // Amenities & Services
        setSelectedAmenities(facility.amenities || [])
        setSelectedMedicalServices(facility.medicalServices || [])
        
        // Staffing
        setTotalStaff(facility.staffing?.totalStaff || 0)
        setMedicalStaff(facility.staffing?.medicalStaff || 0)
        setCertifiedStaff(facility.staffing?.certifiedStaff || 0)
        setStaffToResidentRatio(facility.staffing?.staffToResidentRatio || '')
        setAdministrator(facility.staffing?.administrator || '')
        
        // Certifications & Inspections
        setCertifications(facility.certifications || [])
        setInspectionScores(facility.inspectionScores || [])
        
        // Status
        setFacilityStatus(facility.status || 'active')

        // Set initial form state for change tracking
        setInitialFormState({
          name: facility.name || '',
          description: facility.description || '',
          programType: facility.programType || '',
          serviceType: facility.serviceType || '',
          facilityExternalId: facility.facilityId || '',
          address: facility.location?.address || '',
          city: facility.location?.city || '',
          state: facility.location?.state || '',
          zipCode: facility.location?.zipCode || '',
          county: facility.location?.county || '',
          stateRegion: facility.location?.stateRegion || '',
          hhscSubOffice: facility.location?.hhscSubOffice || '',
          phone: facility.contact?.phone || '',
          email: facility.contact?.email || '',
          website: facility.contact?.website || '',
          fax: facility.contact?.fax || '',
          providerEmail: facility.contact?.providerEmail || '',
          licenseNumber: facility.licensing?.licenseNumber || '',
          selectedCareTypes: facility.careTypes || [],
          totalLicensed: facility.capacity?.totalLicensed || 0,
          minPrice: facility.pricing?.min || 0,
          maxPrice: facility.pricing?.max || 0
        })
        
      } else {
        throw new Error(response.message || 'Failed to load facility')
      }
    } catch (error: any) {
      console.error('Failed to load facility:', error)
      toast.error("Failed to load facility details. Please try again.", { title: "Error" })
    } finally {
      setLoading(false)
    }
  }

  // Validation helper functions
  const validateEmail = (email: string): boolean => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    return emailRegex.test(email)
  }

  const validatePhone = (phone: string): boolean => {
    // Accepts formats: xxx-xxx-xxxx, (xxx) xxx-xxxx, xxx.xxx.xxxx, or 10 digits
    const phoneRegex = /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/
    return phoneRegex.test(phone.replace(/\s/g, ''))
  }

  const validateZipCode = (zip: string): boolean => {
    // Accepts 5-digit or 9-digit ZIP codes
    const zipRegex = /^\d{5}(-\d{4})?$/
    return zipRegex.test(zip)
  }

  const validateForm = (): { isValid: boolean; errors: string[] } => {
    const errors: string[] = []

    // Required fields validation
    if (!name || name.trim().length < 2) {
      errors.push('Facility name is required and must be at least 2 characters')
    }

    if (!address || address.trim().length < 5) {
      errors.push('Address is required')
    }

    if (!city || city.trim().length < 2) {
      errors.push('City is required')
    }

    if (!state) {
      errors.push('State is required')
    }

    if (!zipCode) {
      errors.push('ZIP code is required')
    } else if (!validateZipCode(zipCode)) {
      errors.push('ZIP code must be in format: 12345 or 12345-6789')
    }

    if (!phone) {
      errors.push('Phone number is required')
    } else if (!validatePhone(phone)) {
      errors.push('Phone number must be in valid format (e.g., 555-123-4567)')
    }

    if (!email) {
      errors.push('Email is required')
    } else if (!validateEmail(email)) {
      errors.push('Email must be a valid email address')
    }

    // Validate secondary email if provided
    if (providerEmail && !validateEmail(providerEmail)) {
      errors.push('Provider email must be a valid email address')
    }

    if (!licenseNumber || licenseNumber.trim().length === 0) {
      errors.push('License number is required')
    }

    // Care types validation
    if (selectedCareTypes.length === 0) {
      errors.push('At least one care type must be selected')
    }

    // Capacity validation - all must be non-negative
    if (Number(totalLicensed) < 0) {
      errors.push('Total licensed capacity cannot be negative')
    }
    if (Number(licensedOnlyBeds) < 0) {
      errors.push('Licensed only beds cannot be negative')
    }
    if (Number(medicaidOnlyBeds) < 0) {
      errors.push('Medicaid only beds cannot be negative')
    }
    if (Number(medicareOnlyBeds) < 0) {
      errors.push('Medicare only beds cannot be negative')
    }
    if (Number(medicaidMedicareBeds) < 0) {
      errors.push('Medicaid/Medicare beds cannot be negative')
    }
    if (Number(icfiidBeds) < 0) {
      errors.push('ICF/IID beds cannot be negative')
    }
    if (Number(alzheimerCapacity) < 0) {
      errors.push('Alzheimer capacity cannot be negative')
    }
    if (Number(availableBeds) < 0) {
      errors.push('Available beds cannot be negative')
    }

    // Pricing validation
    if (minPrice && maxPrice && Number(minPrice) > Number(maxPrice)) {
      errors.push('Minimum price cannot be greater than maximum price')
    }

    // Staffing validation
    if (Number(totalStaff) < 0) {
      errors.push('Total staff cannot be negative')
    }
    if (Number(medicalStaff) < 0) {
      errors.push('Medical staff cannot be negative')
    }
    if (Number(certifiedStaff) < 0) {
      errors.push('Certified staff cannot be negative')
    }

    // Coordinates validation if provided
    if (latitude && (isNaN(parseFloat(latitude)) || parseFloat(latitude) < -90 || parseFloat(latitude) > 90)) {
      errors.push('Latitude must be a number between -90 and 90')
    }
    if (longitude && (isNaN(parseFloat(longitude)) || parseFloat(longitude) < -180 || parseFloat(longitude) > 180)) {
      errors.push('Longitude must be a number between -180 and 180')
    }

    // Image URL validation
    const urlRegex = /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/
    for (const imageUrl of images) {
      if (imageUrl && !urlRegex.test(imageUrl)) {
        errors.push(`Invalid image URL: ${imageUrl.substring(0, 50)}...`)
        break // Only show first invalid URL
      }
    }

    return {
      isValid: errors.length === 0,
      errors
    }
  }

  const handleSave = async () => {
    // Check subscription before allowing save
    if (!canEdit(facilityId) && !subscriptionLoading) {
      setShowSubscriptionPrompt(true)
      return
    }

    // Validate form before saving
    const validation = validateForm()
    if (!validation.isValid) {
      const errorMessage = validation.errors.slice(0, 5).map((error, index) => 
        `${index + 1}. ${error}`
      ).join('\n')
      
      const moreErrors = validation.errors.length > 5 
        ? `\n...and ${validation.errors.length - 5} more errors` 
        : ''
      
      toast.error(
        errorMessage + moreErrors,
        { 
          title: "⚠️ Validation Error",
          duration: 7000
        }
      )
      return
    }
    
    try {
      setSaving(true)

      const updates = {
        name,
        description,
        programType,
        serviceType,
        facilityId: facilityExternalId,
        location: {
          address,
          city,
          state,
          zipCode,
          county,
          stateRegion,
          hhscSubOffice,
          ...(latitude && longitude ? {
            coordinates: {
              lat: parseFloat(latitude),
              lng: parseFloat(longitude)
            }
          } : {})
        },
        contact: {
          phone,
          email,
          website,
          fax,
          providerEmail
        },
        licensing: {
          licenseNumber,
          licenseType,
          ...(effectiveDate ? { effectiveDate: new Date(effectiveDate) } : {}),
          ...(expirationDate ? { expirationDate: new Date(expirationDate) } : {}),
          ...(initialLicenseDate ? { initialLicenseDate: new Date(initialLicenseDate) } : {}),
          facilityLicensed,
          facilityCertified,
          medicareProviderNumber,
          medicaidProviderNumber,
          alzheimerCertified,
          alzheimerCertificateNo,
          ...(alzheimerCertEffectiveDate ? { alzheimerCertEffectiveDate: new Date(alzheimerCertEffectiveDate) } : {}),
          ...(alzheimerCertExpirationDate ? { alzheimerCertExpirationDate: new Date(alzheimerCertExpirationDate) } : {})
        },
        careTypes: selectedCareTypes,
        capacity: {
          totalLicensed: Number(totalLicensed),
          licensedOnlyBeds: Number(licensedOnlyBeds),
          medicaidOnlyBeds: Number(medicaidOnlyBeds),
          medicareOnlyBeds: Number(medicareOnlyBeds),
          medicaidMedicareBeds: Number(medicaidMedicareBeds),
          icfiidBeds: Number(icfiidBeds),
          alzheimerCapacity: Number(alzheimerCapacity),
          available: Number(availableBeds)
        },
        pricing: {
          min: Number(minPrice),
          max: Number(maxPrice),
          currency,
          period: pricingPeriod,
          details: pricingDetails
        },
        images,
        virtualTour,
        amenities: selectedAmenities,
        medicalServices: selectedMedicalServices,
        staffing: {
          totalStaff: Number(totalStaff),
          medicalStaff: Number(medicalStaff),
          certifiedStaff: Number(certifiedStaff),
          staffToResidentRatio,
          administrator
        },
        certifications,
        inspectionScores,
        status: facilityStatus
      }

      const response = await DataAPI.facilities.updateFacility(facilityId, updates)

      if (response.success) {
        // Reset unsaved changes flag
        setHasUnsavedChanges(false)
        
        // Determine which sections were updated
        const sections: string[] = []
        if (initialFormState) {
          if (name !== initialFormState.name || description !== initialFormState.description) {
            sections.push('Basic Information')
          }
          if (address !== initialFormState.address || city !== initialFormState.city || state !== initialFormState.state) {
            sections.push('Location & Contact')
          }
          if (licenseNumber !== initialFormState.licenseNumber) {
            sections.push('Licensing & Certifications')
          }
          if (JSON.stringify(selectedCareTypes) !== JSON.stringify(initialFormState.selectedCareTypes)) {
            sections.push('Capacity & Care Types')
          }
          if (minPrice !== initialFormState.minPrice || maxPrice !== initialFormState.maxPrice) {
            sections.push('Pricing Information')
          }
        }
        
        setUpdatedSections(sections.length > 0 ? sections : ['Facility Details'])
        setShowSuccessDialog(true)
      } else {
        throw new Error(response.message || 'Failed to update facility')
      }
    } catch (error: any) {
      console.error('Failed to update facility:', error)
      toast.error(error.message || "Failed to update facility. Please try again.", { title: "Error" })
    } finally {
      setSaving(false)
    }
  }

  const toggleCareType = (type: string) => {
    if (selectedCareTypes.includes(type)) {
      setSelectedCareTypes(selectedCareTypes.filter(t => t !== type))
    } else {
      setSelectedCareTypes([...selectedCareTypes, type])
    }
  }

  const toggleAmenity = (amenity: string) => {
    if (selectedAmenities.includes(amenity)) {
      setSelectedAmenities(selectedAmenities.filter(a => a !== amenity))
    } else {
      setSelectedAmenities([...selectedAmenities, amenity])
    }
  }

  const toggleMedicalService = (service: string) => {
    if (selectedMedicalServices.includes(service)) {
      setSelectedMedicalServices(selectedMedicalServices.filter(s => s !== service))
    } else {
      setSelectedMedicalServices([...selectedMedicalServices, service])
    }
  }

  // Image management is now handled by FacilityImageUploader component

  const addCertification = () => {
    setCertifications([...certifications, {
      name: '',
      issuedBy: '',
      issuedDate: '',
      expiryDate: ''
    }])
  }

  const updateCertification = (index: number, field: string, value: string) => {
    const updated = [...certifications]
    updated[index][field] = value
    setCertifications(updated)
  }

  const removeCertification = (index: number) => {
    setCertifications(certifications.filter((_, i) => i !== index))
  }

  const addInspectionScore = () => {
    setInspectionScores([...inspectionScores, {
      type: '',
      score: 0,
      maxScore: 100,
      date: '',
      inspector: ''
    }])
  }

  const updateInspectionScore = (index: number, field: string, value: any) => {
    const updated = [...inspectionScores]
    updated[index][field] = value
    setInspectionScores(updated)
  }

  const removeInspectionScore = (index: number) => {
    setInspectionScores(inspectionScores.filter((_, i) => i !== index))
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <Loader2 className="h-10 w-10 animate-spin mx-auto mb-4 text-[#3F5CEA]" />
          <p className="text-gray-600">Loading facility details...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="p-6 md:p-8 space-y-8">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <Link href="/facility-owner/dashboard">
            <Button variant="outline" size="sm" className="mb-3">
              <ArrowLeft className="h-4 w-4 mr-2" />
              Back to Dashboard
            </Button>
          </Link>
          <h1 className="text-3xl font-bold text-gray-900">Edit Facility</h1>
          <p className="text-gray-600 mt-2">
            Update your facility information to keep it current
          </p>
        </div>
        <Button
          onClick={handleSave}
          disabled={saving}
          className="bg-[#3F5CEA] hover:bg-[#3F5CEA]/90 h-11 px-8"
        >
          {saving ? (
            <>
              <Loader2 className="h-4 w-4 mr-2 animate-spin" />
              Saving...
            </>
          ) : (
            <>
              <Save className="h-4 w-4 mr-2" />
              Save Changes
            </>
          )}
        </Button>
      </div>

      {/* Tabs */}
      <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-6">
        <TabsList className="grid grid-cols-2 lg:grid-cols-5 gap-2 h-auto p-2 bg-gray-100">
          <TabsTrigger value="basic" className="py-3">
            <Building className="h-4 w-4 mr-2" />
            Basic Info
          </TabsTrigger>
          <TabsTrigger value="location" className="py-3">
            <MapPin className="h-4 w-4 mr-2" />
            Location
          </TabsTrigger>
          <TabsTrigger value="licensing" className="py-3">
            <FileText className="h-4 w-4 mr-2" />
            Licensing
          </TabsTrigger>
          <TabsTrigger value="capacity" className="py-3">
            <Bed className="h-4 w-4 mr-2" />
            Capacity & Care
          </TabsTrigger>
          <TabsTrigger value="amenities" className="py-3">
            <Award className="h-4 w-4 mr-2" />
            Amenities
          </TabsTrigger>
          <TabsTrigger value="pricing" className="py-3">
            <DollarSign className="h-4 w-4 mr-2" />
            Pricing
          </TabsTrigger>
          <TabsTrigger value="media" className="py-3">
            <ImageIcon className="h-4 w-4 mr-2" />
            Media
          </TabsTrigger>
          <TabsTrigger value="staffing" className="py-3">
            <Users className="h-4 w-4 mr-2" />
            Staffing
          </TabsTrigger>
          <TabsTrigger value="certifications" className="py-3">
            <ClipboardCheck className="h-4 w-4 mr-2" />
            Certifications
          </TabsTrigger>
        </TabsList>

        {/* Basic Information Tab */}
        <TabsContent value="basic" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Building className="h-5 w-5 text-[#3F5CEA]" />
                Basic Information
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-6">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="md:col-span-2">
                  <Label htmlFor="name">Facility Name *</Label>
                  <Input
                    id="name"
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                    className="mt-2"
                    placeholder="Enter facility name"
                  />
                </div>

                <div className="md:col-span-2">
                  <Label htmlFor="description">Description</Label>
                  <Textarea
                    id="description"
                    value={description}
                    onChange={(e) => setDescription(e.target.value)}
                    className="mt-2 min-h-[120px]"
                    placeholder="Describe your facility, its mission, and what makes it special..."
                  />
                </div>

                <div>
                  <Label htmlFor="programType">Program Type</Label>
                  <Input
                    id="programType"
                    value={programType}
                    onChange={(e) => setProgramType(e.target.value)}
                    className="mt-2"
                    placeholder="e.g., Assisted Living"
                  />
                </div>

                <div>
                  <Label htmlFor="serviceType">Service Type</Label>
                  <Input
                    id="serviceType"
                    value={serviceType}
                    onChange={(e) => setServiceType(e.target.value)}
                    className="mt-2"
                    placeholder="e.g., Type B"
                  />
                </div>

                <div>
                  <Label htmlFor="facilityId">External Facility ID</Label>
                  <Input
                    id="facilityId"
                    value={facilityExternalId}
                    onChange={(e) => setFacilityExternalId(e.target.value)}
                    className="mt-2"
                    placeholder="Government or system ID"
                  />
                </div>

                <div>
                  <Label htmlFor="status">Facility Status</Label>
                  <Select value={facilityStatus} onValueChange={setFacilityStatus}>
                    <SelectTrigger className="mt-2">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="active">Active</SelectItem>
                      <SelectItem value="pending">Pending</SelectItem>
                      <SelectItem value="suspended">Suspended</SelectItem>
                      <SelectItem value="closed">Closed</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Location Tab */}
        <TabsContent value="location" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <MapPin className="h-5 w-5 text-[#3F5CEA]" />
                Location & Contact Information
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-6">
              <div className="space-y-2">
                <h3 className="text-lg font-semibold text-gray-900">Address</h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div className="md:col-span-2">
                    <Label htmlFor="address">Street Address *</Label>
                    <Input
                      id="address"
                      value={address}
                      onChange={(e) => setAddress(e.target.value)}
                      className="mt-2"
                      placeholder="123 Main Street"
                    />
                  </div>

                  <div>
                    <Label htmlFor="city">City *</Label>
                    <Input
                      id="city"
                      value={city}
                      onChange={(e) => setCity(e.target.value)}
                      className="mt-2"
                      placeholder="City name"
                    />
                  </div>

                  <div>
                    <Label htmlFor="state">State *</Label>
                    <Select value={state} onValueChange={setState}>
                      <SelectTrigger className="mt-2">
                        <SelectValue placeholder="Select state" />
                      </SelectTrigger>
                      <SelectContent>
                        {US_STATES.map(s => (
                          <SelectItem key={s} value={s}>{s}</SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>

                  <div>
                    <Label htmlFor="zipCode">ZIP Code *</Label>
                    <Input
                      id="zipCode"
                      value={zipCode}
                      onChange={(e) => setZipCode(e.target.value)}
                      className="mt-2"
                      placeholder="12345"
                    />
                  </div>

                  <div>
                    <Label htmlFor="county">County</Label>
                    <Input
                      id="county"
                      value={county}
                      onChange={(e) => setCounty(e.target.value)}
                      className="mt-2"
                      placeholder="County name"
                    />
                  </div>

                  <div>
                    <Label htmlFor="stateRegion">State Region</Label>
                    <Input
                      id="stateRegion"
                      value={stateRegion}
                      onChange={(e) => setStateRegion(e.target.value)}
                      className="mt-2"
                      placeholder="e.g., North Texas"
                    />
                  </div>

                  <div>
                    <Label htmlFor="hhscSubOffice">HHSC Sub Office</Label>
                    <Input
                      id="hhscSubOffice"
                      value={hhscSubOffice}
                      onChange={(e) => setHhscSubOffice(e.target.value)}
                      className="mt-2"
                      placeholder="Sub office name"
                    />
                  </div>
                </div>
              </div>

              <div className="space-y-2 pt-4 border-t">
                <h3 className="text-lg font-semibold text-gray-900">Coordinates (Optional)</h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <Label htmlFor="latitude">Latitude</Label>
                    <Input
                      id="latitude"
                      type="number"
                      step="any"
                      value={latitude}
                      onChange={(e) => setLatitude(e.target.value)}
                      className="mt-2"
                      placeholder="32.7767"
                    />
                  </div>

                  <div>
                    <Label htmlFor="longitude">Longitude</Label>
                    <Input
                      id="longitude"
                      type="number"
                      step="any"
                      value={longitude}
                      onChange={(e) => setLongitude(e.target.value)}
                      className="mt-2"
                      placeholder="-96.7970"
                    />
                  </div>
                </div>
              </div>

              <div className="space-y-2 pt-4 border-t">
                <h3 className="text-lg font-semibold text-gray-900 flex items-center gap-2">
                  <Phone className="h-5 w-5" />
                  Contact Information
                </h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <Label htmlFor="phone">Phone Number *</Label>
                    <Input
                      id="phone"
                      type="tel"
                      value={phone}
                      onChange={(e) => setPhone(e.target.value)}
                      className="mt-2"
                      placeholder="(555) 123-4567"
                    />
                  </div>

                  <div>
                    <Label htmlFor="fax">Fax Number</Label>
                    <Input
                      id="fax"
                      type="tel"
                      value={fax}
                      onChange={(e) => setFax(e.target.value)}
                      className="mt-2"
                      placeholder="(555) 123-4568"
                    />
                  </div>

                  <div>
                    <Label htmlFor="email">Email *</Label>
                    <Input
                      id="email"
                      type="email"
                      value={email}
                      onChange={(e) => setEmail(e.target.value)}
                      className="mt-2"
                      placeholder="contact@facility.com"
                    />
                  </div>

                  <div>
                    <Label htmlFor="providerEmail">Provider Email</Label>
                    <Input
                      id="providerEmail"
                      type="email"
                      value={providerEmail}
                      onChange={(e) => setProviderEmail(e.target.value)}
                      className="mt-2"
                      placeholder="provider@facility.com"
                    />
                  </div>

                  <div className="md:col-span-2">
                    <Label htmlFor="website">Website</Label>
                    <Input
                      id="website"
                      type="url"
                      value={website}
                      onChange={(e) => setWebsite(e.target.value)}
                      className="mt-2"
                      placeholder="https://www.facility.com"
                    />
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Licensing Tab */}
        <TabsContent value="licensing" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <FileText className="h-5 w-5 text-[#3F5CEA]" />
                Licensing & Certifications
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-6">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <Label htmlFor="licenseNumber">License Number *</Label>
                  <Input
                    id="licenseNumber"
                    value={licenseNumber}
                    onChange={(e) => setLicenseNumber(e.target.value)}
                    className="mt-2"
                    placeholder="License number"
                  />
                </div>

                <div>
                  <Label htmlFor="licenseType">License Type</Label>
                  <Input
                    id="licenseType"
                    value={licenseType}
                    onChange={(e) => setLicenseType(e.target.value)}
                    className="mt-2"
                    placeholder="Type of license"
                  />
                </div>

                <div>
                  <Label htmlFor="effectiveDate">Effective Date</Label>
                  <Input
                    id="effectiveDate"
                    type="date"
                    value={effectiveDate}
                    onChange={(e) => setEffectiveDate(e.target.value)}
                    className="mt-2"
                  />
                </div>

                <div>
                  <Label htmlFor="expirationDate">Expiration Date</Label>
                  <Input
                    id="expirationDate"
                    type="date"
                    value={expirationDate}
                    onChange={(e) => setExpirationDate(e.target.value)}
                    className="mt-2"
                  />
                </div>

                <div>
                  <Label htmlFor="initialLicenseDate">Initial License Date</Label>
                  <Input
                    id="initialLicenseDate"
                    type="date"
                    value={initialLicenseDate}
                    onChange={(e) => setInitialLicenseDate(e.target.value)}
                    className="mt-2"
                  />
                </div>

                <div className="flex items-center space-x-8 pt-8">
                  <div className="flex items-center space-x-2">
                    <Checkbox
                      id="facilityLicensed"
                      checked={facilityLicensed}
                      onCheckedChange={(checked) => setFacilityLicensed(checked as boolean)}
                    />
                    <Label htmlFor="facilityLicensed" className="cursor-pointer">
                      Licensed
                    </Label>
                  </div>

                  <div className="flex items-center space-x-2">
                    <Checkbox
                      id="facilityCertified"
                      checked={facilityCertified}
                      onCheckedChange={(checked) => setFacilityCertified(checked as boolean)}
                    />
                    <Label htmlFor="facilityCertified" className="cursor-pointer">
                      Certified
                    </Label>
                  </div>
                </div>
              </div>

              <div className="space-y-2 pt-4 border-t">
                <h3 className="text-lg font-semibold text-gray-900">Medicare/Medicaid</h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <Label htmlFor="medicareProviderNumber">Medicare Provider Number</Label>
                    <Input
                      id="medicareProviderNumber"
                      value={medicareProviderNumber}
                      onChange={(e) => setMedicareProviderNumber(e.target.value)}
                      className="mt-2"
                      placeholder="Medicare number"
                    />
                  </div>

                  <div>
                    <Label htmlFor="medicaidProviderNumber">Medicaid Provider Number</Label>
                    <Input
                      id="medicaidProviderNumber"
                      value={medicaidProviderNumber}
                      onChange={(e) => setMedicaidProviderNumber(e.target.value)}
                      className="mt-2"
                      placeholder="Medicaid number"
                    />
                  </div>
                </div>
              </div>

              <div className="space-y-2 pt-4 border-t">
                <div className="flex items-center space-x-2 mb-4">
                  <Checkbox
                    id="alzheimerCertified"
                    checked={alzheimerCertified}
                    onCheckedChange={(checked) => setAlzheimerCertified(checked as boolean)}
                  />
                  <Label htmlFor="alzheimerCertified" className="text-lg font-semibold cursor-pointer">
                    Alzheimer's Certification
                  </Label>
                </div>

                {alzheimerCertified && (
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div className="md:col-span-2">
                      <Label htmlFor="alzheimerCertificateNo">Certificate Number</Label>
                      <Input
                        id="alzheimerCertificateNo"
                        value={alzheimerCertificateNo}
                        onChange={(e) => setAlzheimerCertificateNo(e.target.value)}
                        className="mt-2"
                        placeholder="Certificate number"
                      />
                    </div>

                    <div>
                      <Label htmlFor="alzheimerCertEffectiveDate">Effective Date</Label>
                      <Input
                        id="alzheimerCertEffectiveDate"
                        type="date"
                        value={alzheimerCertEffectiveDate}
                        onChange={(e) => setAlzheimerCertEffectiveDate(e.target.value)}
                        className="mt-2"
                      />
                    </div>

                    <div>
                      <Label htmlFor="alzheimerCertExpirationDate">Expiration Date</Label>
                      <Input
                        id="alzheimerCertExpirationDate"
                        type="date"
                        value={alzheimerCertExpirationDate}
                        onChange={(e) => setAlzheimerCertExpirationDate(e.target.value)}
                        className="mt-2"
                      />
                    </div>
                  </div>
                )}
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Capacity & Care Tab */}
        <TabsContent value="capacity" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Bed className="h-5 w-5 text-[#3F5CEA]" />
                Capacity & Care Types
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-6">
              <div className="space-y-2">
                <h3 className="text-lg font-semibold text-gray-900">Bed Capacity</h3>
                <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
                  <div>
                    <Label htmlFor="totalLicensed">Total Licensed *</Label>
                    <Input
                      id="totalLicensed"
                      type="number"
                      value={totalLicensed}
                      onChange={(e) => setTotalLicensed(Number(e.target.value))}
                      className="mt-2"
                      min="0"
                    />
                  </div>

                  <div>
                    <Label htmlFor="availableBeds">Available Beds</Label>
                    <Input
                      id="availableBeds"
                      type="number"
                      value={availableBeds}
                      onChange={(e) => setAvailableBeds(Number(e.target.value))}
                      className="mt-2"
                      min="0"
                    />
                  </div>

                  <div>
                    <Label htmlFor="licensedOnlyBeds">Licensed Only</Label>
                    <Input
                      id="licensedOnlyBeds"
                      type="number"
                      value={licensedOnlyBeds}
                      onChange={(e) => setLicensedOnlyBeds(Number(e.target.value))}
                      className="mt-2"
                      min="0"
                    />
                  </div>

                  <div>
                    <Label htmlFor="medicaidOnlyBeds">Medicaid Only</Label>
                    <Input
                      id="medicaidOnlyBeds"
                      type="number"
                      value={medicaidOnlyBeds}
                      onChange={(e) => setMedicaidOnlyBeds(Number(e.target.value))}
                      className="mt-2"
                      min="0"
                    />
                  </div>

                  <div>
                    <Label htmlFor="medicareOnlyBeds">Medicare Only</Label>
                    <Input
                      id="medicareOnlyBeds"
                      type="number"
                      value={medicareOnlyBeds}
                      onChange={(e) => setMedicareOnlyBeds(Number(e.target.value))}
                      className="mt-2"
                      min="0"
                    />
                  </div>

                  <div>
                    <Label htmlFor="medicaidMedicareBeds">Medicaid/Medicare</Label>
                    <Input
                      id="medicaidMedicareBeds"
                      type="number"
                      value={medicaidMedicareBeds}
                      onChange={(e) => setMedicaidMedicareBeds(Number(e.target.value))}
                      className="mt-2"
                      min="0"
                    />
                  </div>

                  <div>
                    <Label htmlFor="icfiidBeds">ICF/IID Beds</Label>
                    <Input
                      id="icfiidBeds"
                      type="number"
                      value={icfiidBeds}
                      onChange={(e) => setIcfiidBeds(Number(e.target.value))}
                      className="mt-2"
                      min="0"
                    />
                  </div>

                  <div>
                    <Label htmlFor="alzheimerCapacity">Alzheimer Capacity</Label>
                    <Input
                      id="alzheimerCapacity"
                      type="number"
                      value={alzheimerCapacity}
                      onChange={(e) => setAlzheimerCapacity(Number(e.target.value))}
                      className="mt-2"
                      min="0"
                    />
                  </div>
                </div>
              </div>

              <div className="space-y-2 pt-4 border-t">
                <h3 className="text-lg font-semibold text-gray-900">Care Types Offered *</h3>
                <p className="text-sm text-gray-600">Select all care types your facility provides</p>
                <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 pt-2">
                  {CARE_TYPES.map(type => (
                    <div key={type} className="flex items-center space-x-2">
                      <Checkbox
                        id={`care-${type}`}
                        checked={selectedCareTypes.includes(type)}
                        onCheckedChange={() => toggleCareType(type)}
                      />
                      <Label htmlFor={`care-${type}`} className="cursor-pointer text-sm">
                        {type}
                      </Label>
                    </div>
                  ))}
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Amenities Tab */}
        <TabsContent value="amenities" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Award className="h-5 w-5 text-[#3F5CEA]" />
                Amenities & Medical Services
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-6">
              <div className="space-y-2">
                <h3 className="text-lg font-semibold text-gray-900">Amenities</h3>
                <p className="text-sm text-gray-600">Select all amenities available at your facility</p>
                <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 pt-2">
                  {AMENITIES.map(amenity => (
                    <div key={amenity} className="flex items-center space-x-2">
                      <Checkbox
                        id={`amenity-${amenity}`}
                        checked={selectedAmenities.includes(amenity)}
                        onCheckedChange={() => toggleAmenity(amenity)}
                      />
                      <Label htmlFor={`amenity-${amenity}`} className="cursor-pointer text-sm">
                        {amenity}
                      </Label>
                    </div>
                  ))}
                </div>
              </div>

              <div className="space-y-2 pt-4 border-t">
                <h3 className="text-lg font-semibold text-gray-900">Medical Services</h3>
                <p className="text-sm text-gray-600">Select all medical services you provide</p>
                <div className="grid grid-cols-2 md:grid-cols-3 gap-4 pt-2">
                  {MEDICAL_SERVICES.map(service => (
                    <div key={service} className="flex items-center space-x-2">
                      <Checkbox
                        id={`service-${service}`}
                        checked={selectedMedicalServices.includes(service)}
                        onCheckedChange={() => toggleMedicalService(service)}
                      />
                      <Label htmlFor={`service-${service}`} className="cursor-pointer text-sm">
                        {service}
                      </Label>
                    </div>
                  ))}
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Pricing Tab */}
        <TabsContent value="pricing" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <DollarSign className="h-5 w-5 text-[#3F5CEA]" />
                Pricing Information
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-6">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <Label htmlFor="minPrice">Minimum Price *</Label>
                  <Input
                    id="minPrice"
                    type="number"
                    value={minPrice}
                    onChange={(e) => setMinPrice(Number(e.target.value))}
                    className="mt-2"
                    min="0"
                    step="100"
                  />
                </div>

                <div>
                  <Label htmlFor="maxPrice">Maximum Price *</Label>
                  <Input
                    id="maxPrice"
                    type="number"
                    value={maxPrice}
                    onChange={(e) => setMaxPrice(Number(e.target.value))}
                    className="mt-2"
                    min="0"
                    step="100"
                  />
                </div>

                <div>
                  <Label htmlFor="currency">Currency</Label>
                  <Select value={currency} onValueChange={setCurrency}>
                    <SelectTrigger className="mt-2">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="USD">USD ($)</SelectItem>
                      <SelectItem value="EUR">EUR (€)</SelectItem>
                      <SelectItem value="GBP">GBP (£)</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div>
                  <Label htmlFor="pricingPeriod">Pricing Period</Label>
                  <Select value={pricingPeriod} onValueChange={setPricingPeriod}>
                    <SelectTrigger className="mt-2">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="monthly">Monthly</SelectItem>
                      <SelectItem value="daily">Daily</SelectItem>
                      <SelectItem value="weekly">Weekly</SelectItem>
                      <SelectItem value="annually">Annually</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div className="md:col-span-2">
                  <Label htmlFor="pricingDetails">Pricing Details</Label>
                  <Textarea
                    id="pricingDetails"
                    value={pricingDetails}
                    onChange={(e) => setPricingDetails(e.target.value)}
                    className="mt-2"
                    placeholder="Additional pricing information, included services, extra fees, etc."
                    rows={4}
                  />
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Media Tab */}
        <TabsContent value="media" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <ImageIcon className="h-5 w-5 text-[#3F5CEA]" />
                Images & Virtual Tour
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-6">
              {/* Professional Image Uploader */}
              <div className="space-y-2">
                <Label>Facility Images</Label>
                <p className="text-sm text-gray-600">Upload high-quality images of your facility</p>
                
                <FacilityImageUploader
                  images={images}
                  onImagesChange={setImages}
                  maxImages={20}
                  maxSizeInMB={5}
                />
              </div>

              <div className="space-y-2 pt-6 border-t">
                <Label htmlFor="virtualTour">Virtual Tour URL</Label>
                <Input
                  id="virtualTour"
                  type="url"
                  value={virtualTour}
                  onChange={(e) => setVirtualTour(e.target.value)}
                  className="mt-2"
                  placeholder="https://virtualtour.com/..."
                />
                <p className="text-sm text-gray-500">
                  Link to 360° virtual tour or video walkthrough
                </p>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Staffing Tab */}
        <TabsContent value="staffing" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Users className="h-5 w-5 text-[#3F5CEA]" />
                Staffing Information
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-6">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <Label htmlFor="totalStaff">Total Staff</Label>
                  <Input
                    id="totalStaff"
                    type="number"
                    value={totalStaff}
                    onChange={(e) => setTotalStaff(Number(e.target.value))}
                    className="mt-2"
                    min="0"
                  />
                </div>

                <div>
                  <Label htmlFor="medicalStaff">Medical Staff</Label>
                  <Input
                    id="medicalStaff"
                    type="number"
                    value={medicalStaff}
                    onChange={(e) => setMedicalStaff(Number(e.target.value))}
                    className="mt-2"
                    min="0"
                  />
                </div>

                <div>
                  <Label htmlFor="certifiedStaff">Certified Staff</Label>
                  <Input
                    id="certifiedStaff"
                    type="number"
                    value={certifiedStaff}
                    onChange={(e) => setCertifiedStaff(Number(e.target.value))}
                    className="mt-2"
                    min="0"
                  />
                </div>

                <div>
                  <Label htmlFor="staffToResidentRatio">Staff to Resident Ratio</Label>
                  <Input
                    id="staffToResidentRatio"
                    value={staffToResidentRatio}
                    onChange={(e) => setStaffToResidentRatio(e.target.value)}
                    className="mt-2"
                    placeholder="e.g., 1:5"
                  />
                </div>

                <div className="md:col-span-2">
                  <Label htmlFor="administrator">Administrator Name</Label>
                  <Input
                    id="administrator"
                    value={administrator}
                    onChange={(e) => setAdministrator(e.target.value)}
                    className="mt-2"
                    placeholder="Name of facility administrator"
                  />
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Certifications Tab */}
        <TabsContent value="certifications" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <ClipboardCheck className="h-5 w-5 text-[#3F5CEA]" />
                Additional Certifications & Inspections
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-6">
              {/* Certifications */}
              <div className="space-y-2">
                <div className="flex items-center justify-between">
                  <h3 className="text-lg font-semibold text-gray-900">Certifications</h3>
                  <Button onClick={addCertification} variant="outline" size="sm">
                    <Plus className="h-4 w-4 mr-2" />
                    Add Certification
                  </Button>
                </div>

                {certifications.length > 0 ? (
                  <div className="space-y-4">
                    {certifications.map((cert, index) => (
                      <Card key={index} className="p-4">
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                          <div>
                            <Label>Certification Name</Label>
                            <Input
                              value={cert.name}
                              onChange={(e) => updateCertification(index, 'name', e.target.value)}
                              className="mt-2"
                              placeholder="Certificate name"
                            />
                          </div>
                          <div>
                            <Label>Issued By</Label>
                            <Input
                              value={cert.issuedBy}
                              onChange={(e) => updateCertification(index, 'issuedBy', e.target.value)}
                              className="mt-2"
                              placeholder="Issuing organization"
                            />
                          </div>
                          <div>
                            <Label>Issue Date</Label>
                            <Input
                              type="date"
                              value={cert.issuedDate}
                              onChange={(e) => updateCertification(index, 'issuedDate', e.target.value)}
                              className="mt-2"
                            />
                          </div>
                          <div>
                            <Label>Expiry Date</Label>
                            <Input
                              type="date"
                              value={cert.expiryDate}
                              onChange={(e) => updateCertification(index, 'expiryDate', e.target.value)}
                              className="mt-2"
                            />
                          </div>
                          <div className="md:col-span-2 flex justify-end">
                            <Button
                              variant="destructive"
                              size="sm"
                              onClick={() => removeCertification(index)}
                            >
                              <X className="h-4 w-4 mr-2" />
                              Remove
                            </Button>
                          </div>
                        </div>
                      </Card>
                    ))}
                  </div>
                ) : (
                  <p className="text-sm text-gray-500 text-center py-8">
                    No certifications added yet
                  </p>
                )}
              </div>

              {/* Inspection Scores */}
              <div className="space-y-2 pt-4 border-t">
                <div className="flex items-center justify-between">
                  <h3 className="text-lg font-semibold text-gray-900">Inspection Scores</h3>
                  <Button onClick={addInspectionScore} variant="outline" size="sm">
                    <Plus className="h-4 w-4 mr-2" />
                    Add Inspection
                  </Button>
                </div>

                {inspectionScores.length > 0 ? (
                  <div className="space-y-4">
                    {inspectionScores.map((score, index) => (
                      <Card key={index} className="p-4">
                        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                          <div>
                            <Label>Inspection Type</Label>
                            <Input
                              value={score.type}
                              onChange={(e) => updateInspectionScore(index, 'type', e.target.value)}
                              className="mt-2"
                              placeholder="e.g., Health & Safety"
                            />
                          </div>
                          <div>
                            <Label>Score</Label>
                            <Input
                              type="number"
                              value={score.score}
                              onChange={(e) => updateInspectionScore(index, 'score', Number(e.target.value))}
                              className="mt-2"
                              min="0"
                            />
                          </div>
                          <div>
                            <Label>Max Score</Label>
                            <Input
                              type="number"
                              value={score.maxScore}
                              onChange={(e) => updateInspectionScore(index, 'maxScore', Number(e.target.value))}
                              className="mt-2"
                              min="0"
                            />
                          </div>
                          <div>
                            <Label>Inspection Date</Label>
                            <Input
                              type="date"
                              value={score.date}
                              onChange={(e) => updateInspectionScore(index, 'date', e.target.value)}
                              className="mt-2"
                            />
                          </div>
                          <div>
                            <Label>Inspector</Label>
                            <Input
                              value={score.inspector}
                              onChange={(e) => updateInspectionScore(index, 'inspector', e.target.value)}
                              className="mt-2"
                              placeholder="Inspector name/org"
                            />
                          </div>
                          <div className="flex items-end">
                            <Button
                              variant="destructive"
                              size="sm"
                              onClick={() => removeInspectionScore(index)}
                              className="w-full"
                            >
                              <X className="h-4 w-4 mr-2" />
                              Remove
                            </Button>
                          </div>
                        </div>
                      </Card>
                    ))}
                  </div>
                ) : (
                  <p className="text-sm text-gray-500 text-center py-8">
                    No inspection scores added yet
                  </p>
                )}
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>

      {/* Bottom Save Button */}
      <div className="flex justify-end pt-6 border-t">
        <Button
          onClick={handleSave}
          disabled={saving}
          className="bg-[#3F5CEA] hover:bg-[#3F5CEA]/90 h-11 px-8"
        >
          {saving ? (
            <>
              <Loader2 className="h-4 w-4 mr-2 animate-spin" />
              Saving Changes...
            </>
          ) : (
            <>
              <Save className="h-4 w-4 mr-2" />
              Save All Changes
            </>
          )}
        </Button>
      </div>

      {/* Subscription Prompt */}
      <SubscriptionPrompt
        open={showSubscriptionPrompt}
        onOpenChange={setShowSubscriptionPrompt}
        feature="edit"
        facilityName={name}
      />

      {/* Success Confirmation Dialog */}
      <Dialog open={showSuccessDialog} onOpenChange={setShowSuccessDialog}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2 text-green-600">
              <CheckCircle className="h-5 w-5" />
              Facility Updated Successfully
            </DialogTitle>
            <DialogDescription className="space-y-3 pt-4">
              <p>Your facility information has been updated and is now live on the platform.</p>
              
              {updatedSections.length > 0 && (
                <div className="bg-green-50 border border-green-200 rounded-lg p-3">
                  <p className="font-semibold text-sm text-green-900 mb-2">Updated Sections:</p>
                  <ul className="space-y-1">
                    {updatedSections.map((section, index) => (
                      <li key={index} className="text-sm text-green-800 flex items-center gap-2">
                        <CheckCircle className="h-3 w-3" />
                        {section}
                      </li>
                    ))}
                  </ul>
                </div>
              )}

              <div className="bg-blue-50 border border-blue-200 rounded-lg p-3">
                <p className="text-sm text-blue-900">
                  <strong>Note:</strong> Changes are visible to the public immediately. Users searching for facilities will see your updated information.
                </p>
              </div>
            </DialogDescription>
          </DialogHeader>
          <DialogFooter className="flex gap-2 sm:gap-2">
            <Button
              variant="outline"
              onClick={() => {
                setShowSuccessDialog(false)
                window.open(`/facility/${facilityId}`, '_blank')
              }}
            >
              Preview Facility Page
            </Button>
            <Button
              onClick={() => {
                setShowSuccessDialog(false)
                router.push('/facility-owner/dashboard')
              }}
              className="bg-green-600 hover:bg-green-700"
            >
              Go to Dashboard
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
