"use client"

import { useEffect, useState } from "react"
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 { Header } from "@/components/ui/header"
import { Footer } from "@/components/ui/footer"
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 { Slider } from "@/components/ui/slider"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import {
  User,
  Mail,
  Phone,
  MapPin,
  Bell,
  Shield,
  Eye,
  EyeOff,
  Camera,
  Save,
  Trash2,
  Settings,
  Heart,
  Search,
  AlertCircle,
  CheckCircle,
  Upload,
  X
} from "lucide-react"
import Image from "next/image"
import Link from "next/link"
import { motion } from "framer-motion"
import { useAuth } from "@/hooks/use-auth"
import { DataAPI } from "@/lib/data-api"
import { PageLoader } from "@/components/ui/loader"
import SmartAddressInput, { AddressResult } from "@/components/ui/smart-address-input"
import { validatePhoneNumber } from "@/lib/validation/facility-validator"

export default function UserProfilePage() {
  const { user, isAuthenticated, refreshAuth } = useAuth()
  const [activeTab, setActiveTab] = useState("personal")
  const [isLoading, setIsLoading] = useState(false)
  const [showCurrentPassword, setShowCurrentPassword] = useState(false)
  const [showNewPassword, setShowNewPassword] = useState(false)
  const [showConfirmPassword, setShowConfirmPassword] = useState(false)
  const [unsavedChanges, setUnsavedChanges] = useState(false)
  const [formData, setFormData] = useState<any | null>(null)
  const [phoneError, setPhoneError] = useState("")

  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"
  ]

  // Load profile from API when user is available
  useEffect(() => {
    const load = async () => {
      if (!user?.id) return
      try {
        setIsLoading(true)
        const profileRes = await DataAPI.profile.getProfile(user.id)
        const profile = profileRes.success ? profileRes.data : {}
        const notif = profile?.notificationPreferences || {}
        const ui = {
          id: user.id,
          firstName: user.firstName,
          lastName: user.lastName,
          email: user.email,
          phone: profile?.phone || "",
          avatar: user.profilePicture || profile?.profilePicture || "/placeholder-user.jpg",
          location: {
            address: profile?.mailingAddress?.street || "",
            city: profile?.mailingAddress?.city || "",
            state: profile?.mailingAddress?.state || "",
            zipCode: profile?.mailingAddress?.zipCode || "",
          },
          preferences: {
            careTypes: profile?.carePreferences?.careTypes || [],
            budget: {
              min: profile?.carePreferences?.budgetRange?.min || 1000,
              max: profile?.carePreferences?.budgetRange?.max || 5000,
            },
            radius: profile?.carePreferences?.preferredLocation?.radius || 25,
            moveInTimeframe: profile?.carePreferences?.moveInTimeframe || "",
          },
          notifications: {
            emailAlerts: notif?.email?.general ?? (profile?.preferences?.emailUpdates ?? true),
            facilityUpdates: notif?.email?.facilityUpdates ?? true,
            reviewResponses: notif?.email?.reviewResponses ?? true,
            newFacilities: notif?.email?.newFacilities ?? true,
            smsAlerts: notif?.sms?.alerts ?? (profile?.preferences?.smsUpdates ?? false),
            priceChanges: notif?.sms?.priceChanges ?? false,
          },
          privacy: {
            profileVisibility: "private",
            shareReviews: true,
            allowContact: false,
          },
          currentPassword: "",
          newPassword: "",
          confirmPassword: "",
        }
        setFormData(ui)
      } finally {
        setIsLoading(false)
      }
    }
    load()
  }, [user?.id])

  const handleAddressAutoChange = (result: AddressResult) => {
    setFormData((prev: any) => ({
      ...prev,
      location: {
        ...prev.location,
        address: result.address || prev.location.address,
        city: result.city || prev.location.city,
        state: result.state || prev.location.state,
        zipCode: result.zipCode || prev.location.zipCode,
      },
    }))
    setUnsavedChanges(true)
  }

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

  const handlePhoneChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value
    const validation = validatePhoneNumber(value)

    if (validation.isValid) {
      handleInputChange("phone", validation.formatted || value)
      setPhoneError('')
    } else if (value.length > 0) {
      handleInputChange("phone", value)
      setPhoneError(validation.message || 'Invalid phone number')
    } else {
      handleInputChange("phone", value)
      setPhoneError('')
    }
  }

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

  const handleSave = async () => {
    setIsLoading(true)
    try {
      if (!user?.id || !formData) return
      // Build update payload mapping UI -> UserProfile
      const update = {
        phone: formData.phone?.replace(/\D/g, ""),
        mailingAddress: {
          street: formData.location.address,
          city: formData.location.city,
          state: formData.location.state,
          zipCode: formData.location.zipCode,
        },
        preferences: {
          notifications: formData.notifications.emailAlerts ?? true,
          emailUpdates: formData.notifications.emailAlerts ?? true,
          smsUpdates: formData.notifications.smsAlerts ?? false,
          preferredContactMethod: 'email',
        },
        notificationPreferences: {
          email: {
            general: !!formData.notifications.emailAlerts,
            facilityUpdates: !!formData.notifications.facilityUpdates,
            reviewResponses: !!formData.notifications.reviewResponses,
            newFacilities: !!formData.notifications.newFacilities,
          },
          sms: {
            alerts: !!formData.notifications.smsAlerts,
            priceChanges: !!formData.notifications.priceChanges,
          }
        },
        carePreferences: {
          careTypes: formData.preferences.careTypes,
          budgetRange: { min: formData.preferences.budget.min, max: formData.preferences.budget.max },
          preferredLocation: { radius: formData.preferences.radius },
          moveInTimeframe: formData.preferences.moveInTimeframe,
        },
        firstName: formData.firstName,
        lastName: formData.lastName,
        profilePicture: formData.avatar,
      }
      await DataAPI.profile.updateProfile(user.id, update)
      await refreshAuth()
      setUnsavedChanges(false)
    } finally {
      setIsLoading(false)
    }
  }

  const handleDeleteAccount = () => {
    // Show confirmation modal
    console.log("Delete account requested")
  }

  if (!formData) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-blue-50/30">
        <Header />
        <PageLoader />
        <Footer />
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-blue-50/30">
      <Header />

      <div className="container mx-auto px-4 py-8">
        <div className="max-w-6xl mx-auto">
          {/* Header */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6 }}
            className="mb-8"
          >
            <div className="flex flex-col md:flex-row items-start md:items-center justify-between gap-6">
              <div>
                <h1 className="font-primary text-3xl md:text-4xl font-bold text-gray-900 mb-2">
                  Profile Settings
                </h1>
                <p className="font-body text-lg text-gray-600">
                  Manage your account information and preferences
                </p>
              </div>

              <div className="flex gap-3">
                <Link href="/dashboard">
                  <Button variant="outline" className="border-gray-300 text-gray-700 hover:bg-gray-50 hover:text-gray-900">
                    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>

            {unsavedChanges && (
              <motion.div
                initial={{ opacity: 0, y: -10 }}
                animate={{ opacity: 1, y: 0 }}
                className="mt-4 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>
            )}
          </motion.div>

          <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
            <TabsList className="grid w-full grid-cols-3 h-16 bg-white border border-blue-200/50 rounded-xl shadow-sm">
              <TabsTrigger value="personal" className="text-lg font-body data-[state=active]:bg-[#3F5CEA] data-[state=active]:text-white">
                <User className="h-4 w-4 mr-2" />
                Personal
              </TabsTrigger>
              <TabsTrigger value="preferences" className="text-lg font-body data-[state=active]:bg-[#3F5CEA] data-[state=active]:text-white">
                <Heart className="h-4 w-4 mr-2" />
                Preferences
              </TabsTrigger>
              <TabsTrigger value="notifications" className="text-lg font-body data-[state=active]:bg-[#3F5CEA] data-[state=active]:text-white">
                <Bell className="h-4 w-4 mr-2" />
                Notifications
              </TabsTrigger>
            </TabsList>

            {/* Personal Information Tab */}
            <TabsContent value="personal" className="mt-8">
              <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
                {/* Profile Photo */}
                <AnimatedCard>
                  <CardHeader>
                    <CardTitle className="font-primary text-xl text-gray-900">Profile Photo</CardTitle>
                  </CardHeader>
                  <CardContent className="text-center">
                    <div className="relative w-32 h-32 mx-auto mb-4">
                      <Image
                        src={formData.avatar}
                        alt="Profile"
                        fill
                        className="object-cover rounded-full border-4 border-white shadow-lg"
                      />
                      <label htmlFor="avatarUpload" className="absolute bottom-2 right-2 w-8 h-8 bg-[#3F5CEA] text-white rounded-full flex items-center justify-center hover:bg-[#09183D] transition-colors cursor-pointer">
                        <Camera className="h-4 w-4" />
                      </label>
                      <input
                        id="avatarUpload"
                        type="file"
                        accept="image/*"
                        className="hidden"
                        onChange={async (e) => {
                          const file = e.target.files?.[0]
                          if (!file) return
                          setIsLoading(true)
                          try {
                            const res: any = await (DataAPI as any).profile.uploadAvatar(file)
                            const url = res?.data?.url || res?.url
                            if (url) {
                              setFormData((prev: any) => ({ ...prev, avatar: url }))
                              setUnsavedChanges(true)
                            }
                          } finally {
                            setIsLoading(false)
                          }
                        }}
                      />
                    </div>
                    <div className="space-y-2">
                      <label htmlFor="avatarUpload" className="w-full inline-flex items-center justify-center rounded-md border border-[#3F5CEA] text-[#3F5CEA] hover:bg-[#3F5CEA] hover:text-white h-10 cursor-pointer">
                        <Upload className="h-4 w-4 mr-2" /> Upload New Photo
                      </label>
                      <Button variant="outline" className="w-full border-gray-300 text-gray-700 hover:bg-gray-50" onClick={() => { setFormData((prev: any) => ({ ...prev, avatar: "/placeholder-user.jpg" })); setUnsavedChanges(true) }}>
                        Remove Photo
                      </Button>
                    </div>
                  </CardContent>
                </AnimatedCard>

                {/* Personal Details */}
                <div className="lg:col-span-2">
                  <AnimatedCard>
                    <CardHeader>
                      <CardTitle className="font-primary text-xl text-gray-900">Personal Information</CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-6">
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div className="space-y-2">
                          <Label htmlFor="firstName" className="font-body">First Name</Label>
                          <Input
                            id="firstName"
                            value={formData.firstName}
                            onChange={(e) => handleInputChange("firstName", e.target.value)}
                            className="h-12"
                          />
                        </div>
                        <div className="space-y-2">
                          <Label htmlFor="lastName" className="font-body">Last Name</Label>
                          <Input
                            id="lastName"
                            value={formData.lastName}
                            onChange={(e) => handleInputChange("lastName", e.target.value)}
                            className="h-12"
                          />
                        </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.email}
                            onChange={(e) => handleInputChange("email", e.target.value)}
                            className="pl-10 h-12"
                          />
                        </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"
                            type="tel"
                            value={formData.phone}
                            onChange={handlePhoneChange}
                            className={`pl-10 h-12 ${phoneError ? 'border-red-500' : ''}`}
                            placeholder="(555) 555-5555"
                          />
                        </div>
                        {phoneError && (
                          <p className="text-sm text-red-600 flex items-center gap-1">
                            <AlertCircle className="h-3 w-3" />
                            {phoneError}
                          </p>
                        )}
                      </div>

                      <div className="space-y-4">
                        <Label className="font-body">Address</Label>
                        <div className="space-y-3">
                          <SmartAddressInput
                            value={formData.location.address}
                            onAddressChange={(address) => handleNestedChange("location", "address", address)}
                            onChange={handleAddressAutoChange}
                            placeholder="123 Main Street, City, State"
                            className="h-12"
                          />
                          <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
                            <Input
                              placeholder="City"
                              value={formData.location.city}
                              onChange={(e) => handleNestedChange("location", "city", e.target.value)}
                              className="h-12"
                            />
                            <Select
                              value={formData.location.state}
                              onValueChange={(value) => handleNestedChange("location", "state", value)}
                            >
                              <SelectTrigger className="h-12">
                                <SelectValue placeholder="State" />
                              </SelectTrigger>
                              <SelectContent>
                                {US_STATES.map((st) => (
                                  <SelectItem key={st} value={st}>{st}</SelectItem>
                                ))}
                              </SelectContent>
                            </Select>
                            <Input
                              placeholder="ZIP Code"
                              value={formData.location.zipCode}
                              onChange={(e) => handleNestedChange("location", "zipCode", e.target.value)}
                              className="h-12"
                            />
                          </div>
                        </div>
                      </div>
                    </CardContent>
                  </AnimatedCard>
                </div>
              </div>
            </TabsContent>

            {/* Search Preferences Tab */}
            <TabsContent value="preferences" 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 Preferences</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-6">
                    <div className="space-y-3">
                      <Label className="font-body">Preferred Care Types</Label>
                      <div className="space-y-2">
                        {["Independent Living", "Assisted Living", "Memory Care", "Skilled Nursing"].map((type) => (
                          <div key={type} className="flex items-center space-x-2">
                            <input
                              type="checkbox"
                              id={type}
                              checked={formData.preferences.careTypes.includes(type)}
                              onChange={(e) => {
                                const newTypes = e.target.checked
                                  ? [...formData.preferences.careTypes, type]
                                  : formData.preferences.careTypes.filter((t: string) => t !== type)
                                handleNestedChange("preferences", "careTypes", newTypes)
                              }}
                              className="w-4 h-4 text-[#3F5CEA] border-gray-300 rounded focus:ring-[#3F5CEA]"
                            />
                            <Label htmlFor={type} className="font-body text-gray-700">{type}</Label>
                          </div>
                        ))}
                      </div>
                    </div>

                    <div className="space-y-3">
                      <Label className="font-body">Move-in Timeframe</Label>
                      <Select
                        value={formData.preferences.moveInTimeframe}
                        onValueChange={(value) => handleNestedChange("preferences", "moveInTimeframe", value)}
                      >
                        <SelectTrigger className="h-12">
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="immediate">Immediately</SelectItem>
                          <SelectItem value="1-3 months">1-3 months</SelectItem>
                          <SelectItem value="3-6 months">3-6 months</SelectItem>
                          <SelectItem value="6-12 months">6-12 months</SelectItem>
                          <SelectItem value="1+ years">1+ years</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                  </CardContent>
                </AnimatedCard>

                <AnimatedCard>
                  <CardHeader>
                    <CardTitle className="font-primary text-xl text-gray-900">Budget & Location</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-6">
                    <div className="space-y-4">
                      <Label className="font-body">Monthly Budget Range</Label>
                      <div className="px-3">
                        <Slider
                          value={[formData.preferences.budget.min, formData.preferences.budget.max]}
                          onValueChange={([min, max]) => {
                            handleNestedChange("preferences", "budget", { min, max })
                          }}
                          max={10000}
                          min={1000}
                          step={100}
                          className="w-full"
                        />
                        <div className="flex justify-between text-sm text-gray-600 mt-2">
                          <span>${formData.preferences.budget.min.toLocaleString()}</span>
                          <span>${formData.preferences.budget.max.toLocaleString()}</span>
                        </div>
                      </div>
                    </div>

                    <div className="space-y-4">
                      <Label className="font-body">Search Radius</Label>
                      <div className="px-3">
                        <Slider
                          value={[formData.preferences.radius]}
                          onValueChange={([radius]) => handleNestedChange("preferences", "radius", radius)}
                          max={100}
                          min={5}
                          step={5}
                          className="w-full"
                        />
                        <div className="text-center text-sm text-gray-600 mt-2">
                          {formData.preferences.radius} miles
                        </div>
                      </div>
                    </div>
                  </CardContent>
                </AnimatedCard>
              </div>
            </TabsContent>

            {/* Notifications Tab */}
            <TabsContent value="notifications" className="mt-8">
              <AnimatedCard>
                <CardHeader>
                  <CardTitle className="font-primary text-xl text-gray-900">Notification Preferences</CardTitle>
                  <p className="font-body text-gray-600">Choose how you'd like to be notified about updates</p>
                </CardHeader>
                <CardContent className="space-y-6">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                    <div className="space-y-6">
                      <h3 className="font-body font-semibold text-gray-900">Email Notifications</h3>

                      {[
                        { key: "emailAlerts", label: "General Email Alerts", description: "Important account updates and announcements" },
                        { key: "facilityUpdates", label: "Facility Updates", description: "Changes to saved facilities (pricing, availability)" },
                        { key: "reviewResponses", label: "Review Responses", description: "When facilities respond to your reviews" },
                        { key: "newFacilities", label: "New Facilities", description: "New facilities matching your preferences" }
                      ].map((item) => (
                        <div key={item.key} className="flex items-start justify-between">
                          <div className="flex-1">
                            <Label className="font-body font-medium text-gray-900">{item.label}</Label>
                            <p className="font-body text-sm text-gray-600 mt-1">{item.description}</p>
                          </div>
                          <Switch
                            checked={formData.notifications[item.key as keyof typeof formData.notifications]}
                            onCheckedChange={(checked) => handleNestedChange("notifications", item.key, checked)}
                          />
                        </div>
                      ))}
                    </div>

                    <div className="space-y-6">
                      <h3 className="font-body font-semibold text-gray-900">SMS Notifications</h3>

                      {[
                        { key: "smsAlerts", label: "SMS Alerts", description: "Urgent notifications via text message" },
                        { key: "priceChanges", label: "Price Changes", description: "Immediate alerts for price drops" }
                      ].map((item) => (
                        <div key={item.key} className="flex items-start justify-between">
                          <div className="flex-1">
                            <Label className="font-body font-medium text-gray-900">{item.label}</Label>
                            <p className="font-body text-sm text-gray-600 mt-1">{item.description}</p>
                          </div>
                          <Switch
                            checked={formData.notifications[item.key as keyof typeof formData.notifications]}
                            onCheckedChange={(checked) => handleNestedChange("notifications", item.key, checked)}
                          />
                        </div>
                      ))}
                    </div>
                  </div>
                </CardContent>
              </AnimatedCard>
            </TabsContent>

            {/* Security Tab */}
            <TabsContent value="security" 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">Change Password</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    <div className="space-y-2">
                      <Label htmlFor="currentPassword" className="font-body">Current Password</Label>
                      <div className="relative">
                        <Input
                          id="currentPassword"
                          type={showCurrentPassword ? "text" : "password"}
                          value={formData.currentPassword}
                          onChange={(e) => handleInputChange("currentPassword", e.target.value)}
                          className="pr-10 h-12"
                        />
                        <button
                          type="button"
                          onClick={() => setShowCurrentPassword(!showCurrentPassword)}
                          className="absolute right-3 top-3 text-gray-400 hover:text-gray-600"
                        >
                          {showCurrentPassword ? <EyeOff className="h-5 w-5" /> : <Eye className="h-5 w-5" />}
                        </button>
                      </div>
                    </div>

                    <div className="space-y-2">
                      <Label htmlFor="newPassword" className="font-body">New Password</Label>
                      <div className="relative">
                        <Input
                          id="newPassword"
                          type={showNewPassword ? "text" : "password"}
                          value={formData.newPassword}
                          onChange={(e) => handleInputChange("newPassword", e.target.value)}
                          className="pr-10 h-12"
                        />
                        <button
                          type="button"
                          onClick={() => setShowNewPassword(!showNewPassword)}
                          className="absolute right-3 top-3 text-gray-400 hover:text-gray-600"
                        >
                          {showNewPassword ? <EyeOff className="h-5 w-5" /> : <Eye className="h-5 w-5" />}
                        </button>
                      </div>
                    </div>

                    <div className="space-y-2">
                      <Label htmlFor="confirmPassword" className="font-body">Confirm New Password</Label>
                      <div className="relative">
                        <Input
                          id="confirmPassword"
                          type={showConfirmPassword ? "text" : "password"}
                          value={formData.confirmPassword}
                          onChange={(e) => handleInputChange("confirmPassword", e.target.value)}
                          className="pr-10 h-12"
                        />
                        <button
                          type="button"
                          onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                          className="absolute right-3 top-3 text-gray-400 hover:text-gray-600"
                        >
                          {showConfirmPassword ? <EyeOff className="h-5 w-5" /> : <Eye className="h-5 w-5" />}
                        </button>
                      </div>
                    </div>

                    <Button className="w-full bg-[#3F5CEA] hover:bg-[#09183D] h-12">
                      Update Password
                    </Button>
                  </CardContent>
                </AnimatedCard>

                <AnimatedCard>
                  <CardHeader>
                    <CardTitle className="font-primary text-xl text-gray-900">Account Security</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-6">
                    <div className="p-4 bg-green-50 border border-green-200 rounded-lg">
                      <div className="flex items-center gap-2 mb-2">
                        <CheckCircle className="h-5 w-5 text-green-600" />
                        <span className="font-body font-medium text-green-900">Account Verified</span>
                      </div>
                      <p className="font-body text-sm text-green-700">
                        Your email address has been verified
                      </p>
                    </div>

                    <div className="space-y-3">
                      <h4 className="font-body font-medium text-gray-900">Two-Factor Authentication</h4>
                      <p className="font-body text-sm text-gray-600">
                        Add an extra layer of security to your account
                      </p>
                      <Button variant="outline" className="border-[#3F5CEA] text-[#3F5CEA] hover:bg-[#3F5CEA] hover:text-white">
                        Enable 2FA
                      </Button>
                    </div>

                    <div className="pt-6 border-t border-gray-200">
                      <h4 className="font-body font-medium text-red-900 mb-2">Danger Zone</h4>
                      <p className="font-body text-sm text-gray-600 mb-4">
                        Once you delete your account, there is no going back. Please be certain.
                      </p>
                      <Button
                        variant="outline"
                        onClick={handleDeleteAccount}
                        className="border-red-300 text-red-700 hover:bg-red-50"
                      >
                        <Trash2 className="h-4 w-4 mr-2" />
                        Delete Account
                      </Button>
                    </div>
                  </CardContent>
                </AnimatedCard>
              </div>
            </TabsContent>

            {/* Privacy Tab */}
            <TabsContent value="privacy" className="mt-8">
              <AnimatedCard>
                <CardHeader>
                  <CardTitle className="font-primary text-xl text-gray-900">Privacy Settings</CardTitle>
                  <p className="font-body text-gray-600">Control how your information is shared and used</p>
                </CardHeader>
                <CardContent className="space-y-8">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                    <div className="space-y-6">
                      <div>
                        <Label className="font-body font-medium text-gray-900">Profile Visibility</Label>
                        <p className="font-body text-sm text-gray-600 mb-3">Who can see your profile information</p>
                        <Select
                          value={formData.privacy.profileVisibility}
                          onValueChange={(value) => handleNestedChange("privacy", "profileVisibility", value)}
                        >
                          <SelectTrigger className="h-12">
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="private">Private (Only me)</SelectItem>
                            <SelectItem value="facilities">Facilities only</SelectItem>
                            <SelectItem value="public">Public</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>

                      <div className="flex items-start justify-between">
                        <div className="flex-1">
                          <Label className="font-body font-medium text-gray-900">Share Reviews Publicly</Label>
                          <p className="font-body text-sm text-gray-600 mt-1">
                            Allow your reviews to be visible to other families
                          </p>
                        </div>
                        <Switch
                          checked={formData.privacy.shareReviews}
                          onCheckedChange={(checked) => handleNestedChange("privacy", "shareReviews", checked)}
                        />
                      </div>

                      <div className="flex items-start justify-between">
                        <div className="flex-1">
                          <Label className="font-body font-medium text-gray-900">Allow Facility Contact</Label>
                          <p className="font-body text-sm text-gray-600 mt-1">
                            Let facilities contact you directly about their services
                          </p>
                        </div>
                        <Switch
                          checked={formData.privacy.allowContact}
                          onCheckedChange={(checked) => handleNestedChange("privacy", "allowContact", checked)}
                        />
                      </div>
                    </div>

                    <div className="space-y-6">
                      <div className="p-4 bg-blue-50 border border-blue-200 rounded-lg">
                        <h4 className="font-body font-medium text-blue-900 mb-2">Data Protection</h4>
                        <ul className="font-body text-sm text-blue-700 space-y-1">
                          <li>✓ We never sell your personal information</li>
                          <li>✓ Your data is encrypted and secure</li>
                          <li>✓ HIPAA compliant platform</li>
                          <li>✓ You control your data sharing</li>
                        </ul>
                      </div>

                      <div className="space-y-3">
                        <h4 className="font-body font-medium text-gray-900">Data Download</h4>
                        <p className="font-body text-sm text-gray-600">
                          Download a copy of all your data
                        </p>
                        <Button variant="outline" className="border-gray-300">
                          Request Data Download
                        </Button>
                      </div>
                    </div>
                  </div>
                </CardContent>
              </AnimatedCard>
            </TabsContent>
          </Tabs>
        </div>
      </div>

      <Footer />
    </div>
  )
}
