"use client"

import { useState, useEffect } from "react"
import { useAuth } from "@/hooks/use-auth"
import { DataAPI } from "@/lib/data-api"
import { useToast } from "@/components/ui/toast"
import { Button } from "@/components/ui/button"
import { AnimatedButton } from "@/components/ui/animated-button"
import { Input } from "@/components/ui/input"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { AnimatedCard } from "@/components/ui/animated-card"
import { Badge } from "@/components/ui/badge"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Switch } from "@/components/ui/switch"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Checkbox } from "@/components/ui/checkbox"
import { 
  Building,
  MapPin, 
  Phone,
  Mail,
  Globe,
  Calendar,
  Users,
  Bed,
  Camera,
  Upload,
  Save,
  Eye,
  EyeOff,
  Plus,
  X,
  FileText,
  Award,
  Clock,
  DollarSign,
  Star,
  Trash2,
  Edit,
  CheckCircle,
  AlertCircle,
  Image as ImageIcon,
  Video,
  Shield
} from "lucide-react"
import Image from "next/image"
import Link from "next/link"
import { motion } from "framer-motion"

// Mock facility data
const mockFacilityData = {
  id: "fac_123",
  basicInfo: {
    name: "Sunrise Senior Living",
    description: "A premier assisted living community dedicated to providing exceptional care and comfortable living for seniors. Our experienced staff and beautiful facilities create a warm, home-like environment where residents can thrive.",
    type: "Assisted Living",
    address: "123 Oak Street",
    city: "Springfield",
    state: "IL",
    zipCode: "62701",
    phone: "(555) 123-4567",
    email: "info@sunrisesenior.com",
    website: "www.sunrisesenior.com",
    establishedYear: "1998",
    licenseNumber: "IL-AL-2023-001"
  },
  capacity: {
    totalBeds: 120,
    availableBeds: 8,
    privateRooms: 80,
    sharedRooms: 40,
    memoryCareBeds: 24
  },
  careTypes: ["Assisted Living", "Memory Care", "Respite Care"],
  amenities: [
    "24/7 Nursing Care", "Medication Management", "Physical Therapy", 
    "Occupational Therapy", "Memory Care", "Transportation Services",
    "Housekeeping", "Laundry Services", "Meals Included", "Activities Program",
    "Beauty Salon", "Library", "Garden Areas", "Pet-Friendly"
  ],
  pricing: {
    baseRate: 3500,
    memoryRate: 4200,
    privateRoomSupplement: 800,
    additionalServices: [
      { name: "Medication Management", price: 150 },
      { name: "Physical Therapy", price: 200 },
      { name: "Transportation", price: 100 }
    ]
  },
  operatingHours: {
    officeHours: "8:00 AM - 6:00 PM",
    visitingHours: "8:00 AM - 8:00 PM",
    emergencyContact: "24/7 Available"
  },
  staff: [
    {
      id: 1,
      name: "Dr. Sarah Johnson",
      role: "Medical Director",
      credentials: "MD, Geriatrics",
      experience: "15 years",
      photo: "/placeholder-user.jpg"
    },
    {
      id: 2,
      name: "Maria Rodriguez",
      role: "Director of Nursing",
      credentials: "RN, BSN",
      experience: "12 years",
      photo: "/placeholder-user.jpg"
    }
  ],
  certifications: [
    { name: "State Licensed", issuer: "Illinois Department of Health", expiry: "2025-12-31" },
    { name: "Medicare Certified", issuer: "CMS", expiry: "2024-06-30" },
    { name: "CARF Accredited", issuer: "CARF International", expiry: "2025-03-15" }
  ],
  photos: [
    { id: 1, url: "/senior-living-facility-exterior.jpg", caption: "Main Building Exterior", type: "exterior" },
    { id: 2, url: "/placeholder.jpg", caption: "Dining Room", type: "interior" },
    { id: 3, url: "/placeholder.jpg", caption: "Garden Area", type: "amenity" }
  ],
  policies: {
    petPolicy: "Small pets allowed with approval",
    visitorPolicy: "Open visiting hours with health screening",
    smokingPolicy: "Designated outdoor areas only",
    alcoholPolicy: "Permitted in private rooms with physician approval"
  }
}

export default function FacilityProfileEditPage() {
  const { user } = useAuth()
  const toast = useToast()
  const [activeTab, setActiveTab] = useState("basic")
  const [isLoading, setIsLoading] = useState(false)
  const [isLoadingData, setIsLoadingData] = useState(true)
  const [unsavedChanges, setUnsavedChanges] = useState(false)
  const [previewMode, setPreviewMode] = useState(false)
  
  const [formData, setFormData] = useState(mockFacilityData)
  const [facilities, setFacilities] = useState<any[]>([])

  // Load facility data on component mount
  useEffect(() => {
    loadFacilityData()
  }, [])

  const loadFacilityData = async () => {
    try {
      setIsLoadingData(true)
      
      // Get user's facilities
      const facilitiesResponse = await DataAPI.facilities.getMyFacilities()
      
      if (facilitiesResponse.success && facilitiesResponse.data?.facilities && facilitiesResponse.data.facilities.length > 0) {
        const facility = facilitiesResponse.data.facilities[0] as any // Get first facility
        setFacilities(facilitiesResponse.data.facilities)
        
        // Transform facility data to match form structure with safe null checks
        const facilityData = {
          id: (facility as any)?._id || (facility as any)?.id || "",
          basicInfo: {
            name: facility?.name || "",
            description: facility?.description || "",
            type: (facility?.careTypes && Array.isArray(facility.careTypes) && facility.careTypes[0]) || "",
            address: facility?.location?.address || "",
            city: facility?.location?.city || "",
            state: facility?.location?.state || "",
            zipCode: facility?.location?.zipCode || "",
            phone: facility?.contact?.phone || "",
            email: facility?.contact?.email || "",
            website: facility?.contact?.website || "",
            establishedYear: "",
            licenseNumber: facility?.licensing?.licenseNumber || ""
          },
          capacity: {
            totalBeds: facility?.capacity?.totalLicensed || 6,
            availableBeds: facility?.capacity?.available || 0,
            privateRooms: facility?.capacity?.licensedOnlyBeds || 0,
            sharedRooms: 0,
            memoryCareBeds: facility?.capacity?.alzheimerCapacity || 0
          },
          careTypes: (facility?.careTypes && Array.isArray(facility.careTypes)) ? facility.careTypes : [],
          amenities: (facility?.amenities && Array.isArray(facility.amenities)) ? facility.amenities : [],
          pricing: {
            baseRate: facility?.pricing?.min || 0,
            memoryRate: facility?.pricing?.max || 0,
            privateRoomSupplement: 0,
            additionalServices: []
          },
          operatingHours: {
            officeHours: "8:00 AM - 6:00 PM",
            visitingHours: "8:00 AM - 8:00 PM",
            emergencyContact: "24/7 Available"
          },
          staff: (facility?.staffing?.administrator) ? [{
            id: 1,
            name: facility.staffing.administrator,
            role: "Administrator",
            credentials: "",
            experience: "",
            photo: "/placeholder-user.jpg"
          }] : [],
          certifications: (facility?.certifications && Array.isArray(facility.certifications)) ? facility.certifications : [],
          photos: (facility?.images && Array.isArray(facility.images)) ? facility.images.map((img: string, idx: number) => ({
            id: idx + 1,
            url: img,
            caption: "",
            type: idx === 0 ? "exterior" : "interior"
          })) : [],
          policies: {
            petPolicy: "",
            visitorPolicy: "",
            smokingPolicy: "",
            alcoholPolicy: ""
          }
        }
        
        setFormData(facilityData)
      } else {
        // No facilities found, keep mockFacilityData
        console.log('No facilities found, using default data')
      }
    } catch (error: any) {
      console.error('Error loading facility data:', error)
      toast.error("Failed to load facility data. Using default values.", { title: "Error Loading Data" })
    } finally {
      setIsLoadingData(false)
    }
  }

  const handleInputChange = (section: string, field: string, value: any) => {
    setFormData(prev => ({
      ...prev,
      [section]: {
        ...((prev[section as keyof typeof prev] as any) || {}),
        [field]: value
      }
    }))
    setUnsavedChanges(true)
  }

  const handleArrayChange = (field: string, value: string[]) => {
    setFormData(prev => ({ ...prev, [field]: value }))
    setUnsavedChanges(true)
  }

  const handleSave = async () => {
    try {
      setIsLoading(true)
      
      if (facilities.length === 0) {
        toast.error("Please create a facility first before editing the profile.", { title: "No Facility Found" })
        return
      }

      // Transform form data back to API format
      const facilityId = facilities[0].id
      const updateData = {
        name: formData.basicInfo.name,
        description: formData.basicInfo.description,
        location: {
          address: formData.basicInfo.address,
          city: formData.basicInfo.city,
          state: formData.basicInfo.state,
          zipCode: formData.basicInfo.zipCode
        },
        contact: {
          phone: formData.basicInfo.phone,
          email: formData.basicInfo.email,
          website: formData.basicInfo.website
        },
        licensing: {
          licenseNumber: formData.basicInfo.licenseNumber
        },
        capacity: {
          total: (formData as any).capacity?.totalBeds || 0,
          available: (formData as any).capacity?.availableBeds || 0
        },
        careTypes: formData.careTypes,
        amenities: formData.amenities,
        pricing: {
          baseRate: formData.pricing.baseRate,
          additionalServices: formData.pricing.additionalServices
        },
        staff: formData.staff,
        photos: formData.photos,
        policies: formData.policies
      }

      const response = await DataAPI.facilities.updateFacility(facilityId, updateData)
      
      if (response.success) {
        setUnsavedChanges(false)
        toast.success("Your facility profile has been successfully updated.", { title: "Profile Updated" })
      } else {
        throw new Error(response.message || "Failed to update profile")
      }
    } catch (error: any) {
      console.error('Error saving facility data:', error)
      toast.error(error.message || "Failed to save changes. Please try again.", { title: "Save Failed" })
    } finally {
      setIsLoading(false)
    }
  }

  const addStaffMember = () => {
    const newStaff = {
      id: Date.now(),
      name: "",
      role: "",
      credentials: "",
      experience: "",
      photo: "/placeholder-user.jpg"
    }
    setFormData(prev => ({
      ...prev,
      staff: [...prev.staff, newStaff]
    }))
    setUnsavedChanges(true)
  }

  const removeStaffMember = (id: number) => {
    setFormData(prev => ({
      ...prev,
      staff: prev.staff.filter(s => s.id !== id)
    }))
    setUnsavedChanges(true)
  }

  const handleFileUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const files = event.target.files
    if (!files || files.length === 0) return

    try {
      setIsLoading(true)
      
      // Create FormData for file upload
      const formDataUpload = new FormData()
      Array.from(files).forEach((file, index) => {
        formDataUpload.append(`photos`, file)
      })

      // Upload files (you'll need to implement this API endpoint)
      // const uploadResponse = await DataAPI.facilities.uploadMedia(formDataUpload)
      
      // For now, create local URLs for preview
      const newPhotos = Array.from(files).map((file, index) => ({
        id: Date.now() + index,
        url: URL.createObjectURL(file),
        caption: "",
        isPrimary: formData.photos.length === 0 && index === 0
      }))

      setFormData((prev: any) => ({
        ...(prev || {}),
        photos: [...prev.photos, ...newPhotos]
      }))
      
      setUnsavedChanges(true)
      
      toast.success(`${files.length} photo(s) added successfully.`, { title: "Photos Added" })
    } catch (error: any) {
      console.error('Error uploading files:', error)
      toast.error("Failed to upload photos. Please try again.", { title: "Upload Failed" })
    } finally {
      setIsLoading(false)
    }
  }

  const careTypeOptions = [
    "Independent Living", "Assisted Living", "Memory Care", 
    "Skilled Nursing", "Respite Care", "Adult Day Care"
  ]

  const amenityOptions = [
    "24/7 Nursing Care", "Medication Management", "Physical Therapy",
    "Occupational Therapy", "Speech Therapy", "Memory Care",
    "Transportation Services", "Housekeeping", "Laundry Services",
    "Meals Included", "Activities Program", "Beauty Salon",
    "Library", "Chapel", "Garden Areas", "Pet-Friendly",
    "WiFi", "Cable TV", "Emergency Response", "Security System"
  ]

  // Show loading state while fetching data
  if (isLoadingData) {
    return (
      <div className="min-h-screen bg-gradient-to-b from-white to-muted/30 p-6">
        <div className="max-w-6xl mx-auto">
          <div className="flex items-center justify-center min-h-[400px]">
            <div className="text-center">
              <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
              <p className="text-gray-600">Loading facility data...</p>
            </div>
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-start justify-between">
        <div>
          <h1 className="font-primary text-3xl md:text-4xl font-bold text-gray-900 mb-2">
            Facility Profile
          </h1>
          <p className="font-body text-lg text-gray-600">
            Manage your facility information and showcase your services
          </p>
        </div>
        
        <div className="flex gap-3">
          <Button 
            variant="outline" 
            onClick={() => setPreviewMode(!previewMode)}
            className="border-gray-300 text-gray-700 hover:bg-gray-50"
          >
            {previewMode ? <Edit className="h-4 w-4 mr-2" /> : <Eye className="h-4 w-4 mr-2" />}
            {previewMode ? "Edit Mode" : "Preview"}
          </Button>
          
          <Link href="/facility-owner/dashboard">
            <Button variant="outline" className="border-gray-300 text-gray-700 hover:bg-gray-50">
              Back to Dashboard
            </Button>
          </Link>
          
          <AnimatedButton 
            onClick={handleSave}
            disabled={!unsavedChanges || isLoading}
            loading={isLoading}
            loadingText="Saving..."
            className="bg-gradient-to-r from-[#3F5CEA] to-[#5B73F0] hover:from-[#09183D] hover:to-[#3F5CEA] text-white"
          >
            <Save className="h-4 w-4 mr-2" />
            Save Changes
          </AnimatedButton>
        </div>
      </div>

      {/* Unsaved Changes Alert */}
      {unsavedChanges && (
        <motion.div
          initial={{ opacity: 0, y: -10 }}
          animate={{ opacity: 1, y: 0 }}
          className="p-3 bg-yellow-50 border border-yellow-200 rounded-lg flex items-center gap-2"
        >
          <AlertCircle className="h-4 w-4 text-yellow-600" />
          <span className="font-body text-sm text-yellow-800">You have unsaved changes</span>
        </motion.div>
      )}

      {/* Profile Completeness */}
      <AnimatedCard className="bg-gradient-to-r from-blue-50 to-indigo-50 border-blue-200">
        <CardContent className="p-6">
          <div className="flex items-center justify-between mb-4">
            <div>
              <h3 className="font-body font-semibold text-blue-900">Profile Completeness</h3>
              <p className="font-body text-sm text-blue-700">Complete your profile to attract more families</p>
            </div>
            <div className="text-right">
              <span className="font-primary text-2xl font-bold text-blue-900">85%</span>
              <p className="font-body text-sm text-blue-700">Complete</p>
            </div>
          </div>
          <div className="w-full bg-blue-200 rounded-full h-2">
            <div className="bg-blue-600 h-2 rounded-full w-[85%]"></div>
          </div>
          <div className="flex flex-wrap gap-2 mt-3">
            <Badge className="bg-green-100 text-green-800">
              <CheckCircle className="h-3 w-3 mr-1" />
              Basic Info
            </Badge>
            <Badge className="bg-green-100 text-green-800">
              <CheckCircle className="h-3 w-3 mr-1" />
              Photos
            </Badge>
            <Badge className="bg-yellow-100 text-yellow-800">
              <AlertCircle className="h-3 w-3 mr-1" />
              Staff Info
            </Badge>
          </div>
        </CardContent>
      </AnimatedCard>

      <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
        <TabsList className="grid w-full grid-cols-6 h-16 bg-white border border-blue-200/50 rounded-xl shadow-sm">
          <TabsTrigger value="basic" className="font-body data-[state=active]:bg-[#3F5CEA] data-[state=active]:text-white">
            <Building className="h-4 w-4 mr-2" />
            Basic Info
          </TabsTrigger>
          <TabsTrigger value="services" className="font-body data-[state=active]:bg-[#3F5CEA] data-[state=active]:text-white">
            <Users className="h-4 w-4 mr-2" />
            Services
          </TabsTrigger>
          <TabsTrigger value="pricing" className="font-body data-[state=active]:bg-[#3F5CEA] data-[state=active]:text-white">
            <DollarSign className="h-4 w-4 mr-2" />
            Pricing
          </TabsTrigger>
          <TabsTrigger value="staff" className="font-body data-[state=active]:bg-[#3F5CEA] data-[state=active]:text-white">
            <Award className="h-4 w-4 mr-2" />
            Staff
          </TabsTrigger>
          <TabsTrigger value="media" className="font-body data-[state=active]:bg-[#3F5CEA] data-[state=active]:text-white">
            <Camera className="h-4 w-4 mr-2" />
            Media
          </TabsTrigger>
          <TabsTrigger value="policies" className="font-body data-[state=active]:bg-[#3F5CEA] data-[state=active]:text-white">
            <FileText className="h-4 w-4 mr-2" />
            Policies
          </TabsTrigger>
        </TabsList>

        {/* Basic Information Tab */}
        <TabsContent value="basic" className="mt-8">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
            <AnimatedCard>
              <CardHeader>
                <CardTitle className="font-primary text-xl text-gray-900">Basic Information</CardTitle>
              </CardHeader>
              <CardContent className="space-y-6">
                <div className="space-y-2">
                  <Label htmlFor="facilityName" className="font-body">Facility Name *</Label>
                  <Input
                    id="facilityName"
                    value={formData.basicInfo.name}
                    onChange={(e) => handleInputChange("basicInfo", "name", e.target.value)}
                    className="h-12"
                    disabled={previewMode}
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="description" className="font-body">Description *</Label>
                  <Textarea
                    id="description"
                    value={formData.basicInfo.description}
                    onChange={(e) => handleInputChange("basicInfo", "description", e.target.value)}
                    className="min-h-[120px]"
                    disabled={previewMode}
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="facilityType" className="font-body">Facility Type *</Label>
                  <Select
                    value={formData.basicInfo.type}
                    onValueChange={(value) => handleInputChange("basicInfo", "type", value)}
                    disabled={previewMode}
                  >
                    <SelectTrigger className="h-12">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      {careTypeOptions.map(type => (
                        <SelectItem key={type} value={type}>{type}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="establishedYear" className="font-body">Established Year</Label>
                    <Input
                      id="establishedYear"
                      value={formData.basicInfo.establishedYear}
                      onChange={(e) => handleInputChange("basicInfo", "establishedYear", e.target.value)}
                      className="h-12"
                      disabled={previewMode}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="licenseNumber" className="font-body">License Number *</Label>
                    <Input
                      id="licenseNumber"
                      value={formData.basicInfo.licenseNumber}
                      onChange={(e) => handleInputChange("basicInfo", "licenseNumber", e.target.value)}
                      className="h-12"
                      disabled={previewMode}
                    />
                  </div>
                </div>
              </CardContent>
            </AnimatedCard>

            <AnimatedCard>
              <CardHeader>
                <CardTitle className="font-primary text-xl text-gray-900">Contact & Location</CardTitle>
              </CardHeader>
              <CardContent className="space-y-6">
                <div className="space-y-2">
                  <Label htmlFor="address" className="font-body">Street Address *</Label>
                  <div className="relative">
                    <MapPin className="absolute left-3 top-3 h-5 w-5 text-gray-400" />
                    <Input
                      id="address"
                      value={formData.basicInfo.address}
                      onChange={(e) => handleInputChange("basicInfo", "address", e.target.value)}
                      className="pl-10 h-12"
                      disabled={previewMode}
                    />
                  </div>
                </div>

                <div className="grid grid-cols-3 gap-3">
                  <div className="space-y-2">
                    <Label htmlFor="city" className="font-body">City *</Label>
                    <Input
                      id="city"
                      value={formData.basicInfo.city}
                      onChange={(e) => handleInputChange("basicInfo", "city", e.target.value)}
                      className="h-12"
                      disabled={previewMode}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="state" className="font-body">State *</Label>
                    <Input
                      id="state"
                      value={formData.basicInfo.state}
                      onChange={(e) => handleInputChange("basicInfo", "state", e.target.value)}
                      className="h-12"
                      disabled={previewMode}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="zipCode" className="font-body">ZIP Code *</Label>
                    <Input
                      id="zipCode"
                      value={formData.basicInfo.zipCode}
                      onChange={(e) => handleInputChange("basicInfo", "zipCode", e.target.value)}
                      className="h-12"
                      disabled={previewMode}
                    />
                  </div>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="phone" className="font-body">Phone Number *</Label>
                  <div className="relative">
                    <Phone className="absolute left-3 top-3 h-5 w-5 text-gray-400" />
                    <Input
                      id="phone"
                      value={formData.basicInfo.phone}
                      onChange={(e) => handleInputChange("basicInfo", "phone", e.target.value)}
                      className="pl-10 h-12"
                      disabled={previewMode}
                    />
                  </div>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="email" className="font-body">Email Address *</Label>
                  <div className="relative">
                    <Mail className="absolute left-3 top-3 h-5 w-5 text-gray-400" />
                    <Input
                      id="email"
                      type="email"
                      value={formData.basicInfo.email}
                      onChange={(e) => handleInputChange("basicInfo", "email", e.target.value)}
                      className="pl-10 h-12"
                      disabled={previewMode}
                    />
                  </div>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="website" className="font-body">Website</Label>
                  <div className="relative">
                    <Globe className="absolute left-3 top-3 h-5 w-5 text-gray-400" />
                    <Input
                      id="website"
                      value={formData.basicInfo.website}
                      onChange={(e) => handleInputChange("basicInfo", "website", e.target.value)}
                      className="pl-10 h-12"
                      disabled={previewMode}
                    />
                  </div>
                </div>
              </CardContent>
            </AnimatedCard>
          </div>

          {/* Capacity Information */}
          <AnimatedCard className="mt-8">
            <CardHeader>
              <CardTitle className="font-primary text-xl text-gray-900">Capacity Information</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-5 gap-6">
                <div className="space-y-2">
                  <Label htmlFor="totalBeds" className="font-body">Total Beds *</Label>
                  <div className="relative">
                    <Bed className="absolute left-3 top-3 h-5 w-5 text-gray-400" />
                    <Input
                      id="totalBeds"
                      type="number"
                      value={formData.capacity.totalBeds}
                      onChange={(e) => handleInputChange("capacity", "totalBeds", parseInt(e.target.value))}
                      className="pl-10 h-12"
                      disabled={previewMode}
                    />
                  </div>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="availableBeds" className="font-body">Available Beds</Label>
                  <Input
                    id="availableBeds"
                    type="number"
                    value={formData.capacity.availableBeds}
                    onChange={(e) => handleInputChange("capacity", "availableBeds", parseInt(e.target.value))}
                    className="h-12"
                    disabled={previewMode}
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="privateRooms" className="font-body">Private Rooms</Label>
                  <Input
                    id="privateRooms"
                    type="number"
                    value={formData.capacity.privateRooms}
                    onChange={(e) => handleInputChange("capacity", "privateRooms", parseInt(e.target.value))}
                    className="h-12"
                    disabled={previewMode}
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="sharedRooms" className="font-body">Shared Rooms</Label>
                  <Input
                    id="sharedRooms"
                    type="number"
                    value={formData.capacity.sharedRooms}
                    onChange={(e) => handleInputChange("capacity", "sharedRooms", parseInt(e.target.value))}
                    className="h-12"
                    disabled={previewMode}
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="memoryCareBeds" className="font-body">Memory Care Beds</Label>
                  <Input
                    id="memoryCareBeds"
                    type="number"
                    value={formData.capacity.memoryCareBeds}
                    onChange={(e) => handleInputChange("capacity", "memoryCareBeds", parseInt(e.target.value))}
                    className="h-12"
                    disabled={previewMode}
                  />
                </div>
              </div>
            </CardContent>
          </AnimatedCard>
        </TabsContent>

        {/* Services Tab */}
        <TabsContent value="services" className="mt-8">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
            <AnimatedCard>
              <CardHeader>
                <CardTitle className="font-primary text-xl text-gray-900">Care Types Offered</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  {careTypeOptions.map(type => (
                    <div key={type} className="flex items-center space-x-2">
                      <Checkbox
                        id={type}
                        checked={formData.careTypes.includes(type)}
                        onCheckedChange={(checked) => {
                          const newTypes = checked
                            ? [...formData.careTypes, type]
                            : formData.careTypes.filter(t => t !== type)
                          handleArrayChange("careTypes", newTypes)
                        }}
                        disabled={previewMode}
                      />
                      <Label htmlFor={type} className="font-body text-gray-700">{type}</Label>
                    </div>
                  ))}
                </div>
              </CardContent>
            </AnimatedCard>

            <AnimatedCard>
              <CardHeader>
                <CardTitle className="font-primary text-xl text-gray-900">Amenities & Services</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-1 gap-2 max-h-96 overflow-y-auto">
                  {amenityOptions.map(amenity => (
                    <div key={amenity} className="flex items-center space-x-2">
                      <Checkbox
                        id={amenity}
                        checked={formData.amenities.includes(amenity)}
                        onCheckedChange={(checked) => {
                          const newAmenities = checked
                            ? [...formData.amenities, amenity]
                            : formData.amenities.filter(a => a !== amenity)
                          handleArrayChange("amenities", newAmenities)
                        }}
                        disabled={previewMode}
                      />
                      <Label htmlFor={amenity} className="font-body text-sm text-gray-700">{amenity}</Label>
                    </div>
                  ))}
                </div>
              </CardContent>
            </AnimatedCard>
          </div>

          {/* Operating Hours */}
          <AnimatedCard className="mt-8">
            <CardHeader>
              <CardTitle className="font-primary text-xl text-gray-900">Operating Hours</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div className="space-y-2">
                  <Label htmlFor="officeHours" className="font-body">Office Hours</Label>
                  <div className="relative">
                    <Clock className="absolute left-3 top-3 h-5 w-5 text-gray-400" />
                    <Input
                      id="officeHours"
                      value={formData.operatingHours.officeHours}
                      onChange={(e) => handleInputChange("operatingHours", "officeHours", e.target.value)}
                      className="pl-10 h-12"
                      disabled={previewMode}
                    />
                  </div>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="visitingHours" className="font-body">Visiting Hours</Label>
                  <div className="relative">
                    <Clock className="absolute left-3 top-3 h-5 w-5 text-gray-400" />
                    <Input
                      id="visitingHours"
                      value={formData.operatingHours.visitingHours}
                      onChange={(e) => handleInputChange("operatingHours", "visitingHours", e.target.value)}
                      className="pl-10 h-12"
                      disabled={previewMode}
                    />
                  </div>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="emergencyContact" className="font-body">Emergency Contact</Label>
                  <Input
                    id="emergencyContact"
                    value={formData.operatingHours.emergencyContact}
                    onChange={(e) => handleInputChange("operatingHours", "emergencyContact", e.target.value)}
                    className="h-12"
                    disabled={previewMode}
                  />
                </div>
              </div>
            </CardContent>
          </AnimatedCard>
        </TabsContent>

        {/* Pricing Tab */}
        <TabsContent value="pricing" className="mt-8">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
            <AnimatedCard>
              <CardHeader>
                <CardTitle className="font-primary text-xl text-gray-900">Base Pricing</CardTitle>
              </CardHeader>
              <CardContent className="space-y-6">
                <div className="space-y-2">
                  <Label htmlFor="baseRate" className="font-body">Base Monthly Rate *</Label>
                  <div className="relative">
                    <DollarSign className="absolute left-3 top-3 h-5 w-5 text-gray-400" />
                    <Input
                      id="baseRate"
                      type="number"
                      value={formData.pricing.baseRate}
                      onChange={(e) => handleInputChange("pricing", "baseRate", parseInt(e.target.value))}
                      className="pl-10 h-12"
                      disabled={previewMode}
                    />
                  </div>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="memoryRate" className="font-body">Memory Care Rate</Label>
                  <div className="relative">
                    <DollarSign className="absolute left-3 top-3 h-5 w-5 text-gray-400" />
                    <Input
                      id="memoryRate"
                      type="number"
                      value={formData.pricing.memoryRate}
                      onChange={(e) => handleInputChange("pricing", "memoryRate", parseInt(e.target.value))}
                      className="pl-10 h-12"
                      disabled={previewMode}
                    />
                  </div>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="privateRoomSupplement" className="font-body">Private Room Supplement</Label>
                  <div className="relative">
                    <DollarSign className="absolute left-3 top-3 h-5 w-5 text-gray-400" />
                    <Input
                      id="privateRoomSupplement"
                      type="number"
                      value={formData.pricing.privateRoomSupplement}
                      onChange={(e) => handleInputChange("pricing", "privateRoomSupplement", parseInt(e.target.value))}
                      className="pl-10 h-12"
                      disabled={previewMode}
                    />
                  </div>
                </div>
              </CardContent>
            </AnimatedCard>

            <AnimatedCard>
              <CardHeader>
                <CardTitle className="font-primary text-xl text-gray-900">Additional Services</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {formData.pricing.additionalServices.map((service, index) => (
                    <div key={index} className="flex items-center gap-3 p-3 bg-gray-50 rounded-lg">
                      <div className="flex-1">
                        <Input
                          placeholder="Service name"
                          value={service.name}
                          onChange={(e) => {
                            const newServices = [...formData.pricing.additionalServices]
                            newServices[index].name = e.target.value
                            handleInputChange("pricing", "additionalServices", newServices)
                          }}
                          disabled={previewMode}
                        />
                      </div>
                      <div className="w-24">
                        <div className="relative">
                          <DollarSign className="absolute left-2 top-2 h-4 w-4 text-gray-400" />
                          <Input
                            type="number"
                            placeholder="Price"
                            value={service.price}
                            onChange={(e) => {
                              const newServices = [...formData.pricing.additionalServices]
                              newServices[index].price = parseInt(e.target.value)
                              handleInputChange("pricing", "additionalServices", newServices)
                            }}
                            className="pl-7"
                            disabled={previewMode}
                          />
                        </div>
                      </div>
                      {!previewMode && (
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => {
                            const newServices = formData.pricing.additionalServices.filter((_, i) => i !== index)
                            handleInputChange("pricing", "additionalServices", newServices)
                          }}
                          className="border-red-300 text-red-700 hover:bg-red-50"
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      )}
                    </div>
                  ))}
                  
                  {!previewMode && (
                    <Button
                      variant="outline"
                      onClick={() => {
                        const newServices = [...formData.pricing.additionalServices, { name: "", price: 0 }]
                        handleInputChange("pricing", "additionalServices", newServices)
                      }}
                      className="w-full border-[#3F5CEA] text-[#3F5CEA] hover:bg-[#3F5CEA] hover:text-white"
                    >
                      <Plus className="h-4 w-4 mr-2" />
                      Add Service
                    </Button>
                  )}
                </div>
              </CardContent>
            </AnimatedCard>
          </div>
        </TabsContent>

        {/* Staff Tab */}
        <TabsContent value="staff" className="mt-8">
          <div className="space-y-6">
            {/* Staff Members */}
            <AnimatedCard>
              <CardHeader>
                <div className="flex items-center justify-between">
                  <CardTitle className="font-primary text-xl text-gray-900">Staff Members</CardTitle>
                  {!previewMode && (
                    <Button
                      onClick={addStaffMember}
                      className="bg-gradient-to-r from-[#3F5CEA] to-[#5B73F0] hover:from-[#09183D] hover:to-[#3F5CEA] text-white"
                    >
                      <Plus className="h-4 w-4 mr-2" />
                      Add Staff Member
                    </Button>
                  )}
                </div>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  {formData.staff.map((staff, index) => (
                    <div key={staff.id} className="border border-gray-200 rounded-lg p-4">
                      <div className="flex items-start gap-4">
                        <div className="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center overflow-hidden">
                          <Image
                            src={staff.photo}
                            alt={staff.name}
                            width={64}
                            height={64}
                            className="object-cover"
                          />
                        </div>
                        <div className="flex-1 space-y-3">
                          <div className="grid grid-cols-2 gap-3">
                            <Input
                              placeholder="Full Name"
                              value={staff.name}
                              onChange={(e) => {
                                const newStaff = [...formData.staff]
                                newStaff[index].name = e.target.value
                                setFormData(prev => ({ ...prev, staff: newStaff }))
                                setUnsavedChanges(true)
                              }}
                              disabled={previewMode}
                            />
                            <Input
                              placeholder="Role/Title"
                              value={staff.role}
                              onChange={(e) => {
                                const newStaff = [...formData.staff]
                                newStaff[index].role = e.target.value
                                setFormData(prev => ({ ...prev, staff: newStaff }))
                                setUnsavedChanges(true)
                              }}
                              disabled={previewMode}
                            />
                          </div>
                          <div className="grid grid-cols-2 gap-3">
                            <Input
                              placeholder="Credentials"
                              value={staff.credentials}
                              onChange={(e) => {
                                const newStaff = [...formData.staff]
                                newStaff[index].credentials = e.target.value
                                setFormData(prev => ({ ...prev, staff: newStaff }))
                                setUnsavedChanges(true)
                              }}
                              disabled={previewMode}
                            />
                            <Input
                              placeholder="Experience"
                              value={staff.experience}
                              onChange={(e) => {
                                const newStaff = [...formData.staff]
                                newStaff[index].experience = e.target.value
                                setFormData(prev => ({ ...prev, staff: newStaff }))
                                setUnsavedChanges(true)
                              }}
                              disabled={previewMode}
                            />
                          </div>
                        </div>
                        {!previewMode && (
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => removeStaffMember(staff.id)}
                            className="border-red-300 text-red-700 hover:bg-red-50"
                          >
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              </CardContent>
            </AnimatedCard>

            {/* Certifications */}
            <AnimatedCard>
              <CardHeader>
                <CardTitle className="font-primary text-xl text-gray-900">Certifications & Licenses</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {formData.certifications.map((cert, index) => (
                    <div key={index} className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                      <div className="flex items-center gap-3">
                        <Shield className="h-5 w-5 text-green-600" />
                        <div>
                          <p className="font-body font-medium text-gray-900">{cert.name}</p>
                          <p className="font-body text-sm text-gray-600">Issued by {cert.issuer}</p>
                        </div>
                      </div>
                      <div className="text-right">
                        <p className="font-body text-sm text-gray-900">Expires: {new Date(cert.expiry).toLocaleDateString()}</p>
                        <Badge className={new Date(cert.expiry) > new Date() ? "bg-green-100 text-green-800" : "bg-red-100 text-red-800"}>
                          {new Date(cert.expiry) > new Date() ? "Valid" : "Expired"}
                        </Badge>
                      </div>
                    </div>
                  ))}
                </div>
              </CardContent>
            </AnimatedCard>
          </div>
        </TabsContent>

        {/* Media Tab */}
        <TabsContent value="media" className="mt-8">
          <AnimatedCard>
            <CardHeader>
              <CardTitle className="font-primary text-xl text-gray-900">Photo Gallery</CardTitle>
              <p className="font-body text-gray-600">Upload high-quality photos to showcase your facility</p>
            </CardHeader>
            <CardContent>
              {!previewMode && (
                <div className="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center mb-6">
                  <div className="space-y-4">
                    <div className="mx-auto w-16 h-16 bg-gradient-to-br from-[#3F5CEA] to-[#09183D] rounded-full flex items-center justify-center">
                      <Upload className="h-8 w-8 text-white" />
                    </div>
                    <div>
                      <p className="font-body text-lg font-medium text-gray-900 mb-2">
                        Upload facility photos
                      </p>
                      <p className="font-body text-gray-600 mb-4">
                        Drag & drop photos here or click to browse
                      </p>
                      <div className="relative">
                        <input
                          type="file"
                          multiple
                          accept="image/*"
                          onChange={handleFileUpload}
                          className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
                          disabled={isLoading}
                        />
                        <Button 
                          className="bg-gradient-to-r from-[#3F5CEA] to-[#5B73F0] hover:from-[#09183D] hover:to-[#3F5CEA] text-white"
                          disabled={isLoading}
                        >
                          {isLoading ? "Uploading..." : "Choose Photos"}
                        </Button>
                      </div>
                    </div>
                  </div>
                </div>
              )}

              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                {formData.photos.map((photo, index) => (
                  <div key={photo.id} className="relative group">
                    <div className="aspect-video bg-gray-100 rounded-lg overflow-hidden">
                      <Image
                        src={photo.url}
                        alt={photo.caption}
                        fill
                        className="object-cover group-hover:scale-105 transition-transform duration-300"
                      />
                    </div>
                    <div className="mt-2">
                      <Input
                        placeholder="Photo caption"
                        value={photo.caption}
                        onChange={(e) => {
                          const newPhotos = [...formData.photos]
                          newPhotos[index].caption = e.target.value
                          setFormData(prev => ({ ...prev, photos: newPhotos }))
                          setUnsavedChanges(true)
                        }}
                        className="text-sm"
                        disabled={previewMode}
                      />
                    </div>
                    {!previewMode && (
                      <Button
                        variant="outline"
                        size="sm"
                        className="absolute top-2 right-2 bg-white/90 border-red-300 text-red-700 hover:bg-red-50"
                        onClick={() => {
                          const newPhotos = formData.photos.filter(p => p.id !== photo.id)
                          setFormData(prev => ({ ...prev, photos: newPhotos }))
                          setUnsavedChanges(true)
                        }}
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    )}
                  </div>
                ))}
              </div>
            </CardContent>
          </AnimatedCard>
        </TabsContent>

        {/* Policies Tab */}
        <TabsContent value="policies" className="mt-8">
          <AnimatedCard>
            <CardHeader>
              <CardTitle className="font-primary text-xl text-gray-900">Facility Policies</CardTitle>
            </CardHeader>
            <CardContent className="space-y-6">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="space-y-2">
                  <Label htmlFor="petPolicy" className="font-body">Pet Policy</Label>
                  <Textarea
                    id="petPolicy"
                    value={formData.policies.petPolicy}
                    onChange={(e) => handleInputChange("policies", "petPolicy", e.target.value)}
                    className="min-h-[80px]"
                    disabled={previewMode}
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="visitorPolicy" className="font-body">Visitor Policy</Label>
                  <Textarea
                    id="visitorPolicy"
                    value={formData.policies.visitorPolicy}
                    onChange={(e) => handleInputChange("policies", "visitorPolicy", e.target.value)}
                    className="min-h-[80px]"
                    disabled={previewMode}
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="smokingPolicy" className="font-body">Smoking Policy</Label>
                  <Textarea
                    id="smokingPolicy"
                    value={formData.policies.smokingPolicy}
                    onChange={(e) => handleInputChange("policies", "smokingPolicy", e.target.value)}
                    className="min-h-[80px]"
                    disabled={previewMode}
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="alcoholPolicy" className="font-body">Alcohol Policy</Label>
                  <Textarea
                    id="alcoholPolicy"
                    value={formData.policies.alcoholPolicy}
                    onChange={(e) => handleInputChange("policies", "alcoholPolicy", e.target.value)}
                    className="min-h-[80px]"
                    disabled={previewMode}
                  />
                </div>
              </div>
            </CardContent>
          </AnimatedCard>
        </TabsContent>
      </Tabs>
    </div>
  )
}