"use client"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import { AnimatedButton } from "@/components/ui/animated-button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { AnimatedCard } from "@/components/ui/animated-card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Checkbox } from "@/components/ui/checkbox"
import { Slider } from "@/components/ui/slider"
import { Header } from "@/components/ui/header"
import { Footer } from "@/components/ui/footer"
import { Badge } from "@/components/ui/badge"
import {
  Search,
  MapPin,
  DollarSign,
  Calendar,
  Users,
  Heart,
  Filter,
  X,
  RotateCcw,
  Map,
  List,
  Grid,
  SlidersHorizontal,
  Star,
  Building,
  Car,
  Utensils,
  Activity,
  Shield,
  Award,
  Stethoscope,
  Clock
} from "lucide-react"
import Image from "next/image"
import Link from "next/link"
import { motion } from "framer-motion"

// Mock data for facilities
const mockFacilities = [
  {
    id: "fac_001",
    name: "Sunrise Senior Living",
    type: "Assisted Living",
    location: "Springfield, IL",
    address: "123 Oak Street",
    distance: 2.4,
    rating: 4.8,
    reviews: 156,
    pricing: { min: 3500, max: 4200 },
    image: "/senior-living-facility-exterior.jpg",
    amenities: ["24/7 Care", "Memory Care", "Physical Therapy", "Transportation"],
    specialties: ["Alzheimer's Care", "Diabetes Management"],
    availability: "Available",
    certifications: ["Medicare", "CARF"],
    established: 1998
  },
  {
    id: "fac_002",
    name: "Golden Years Care Center",
    type: "Memory Care",
    location: "Springfield, IL",
    address: "456 Maple Avenue",
    distance: 3.1,
    rating: 4.6,
    reviews: 203,
    pricing: { min: 3200, max: 3900 },
    image: "/placeholder.jpg",
    amenities: ["24/7 Care", "Memory Care", "Activities", "Garden"],
    specialties: ["Memory Care", "Physical Rehabilitation"],
    availability: "Limited",
    certifications: ["Medicare"],
    established: 2003
  },
  {
    id: "fac_003",
    name: "Peaceful Pines Assisted Living",
    type: "Skilled Nursing",
    location: "Springfield, IL",
    address: "789 Pine Street",
    distance: 4.7,
    rating: 4.7,
    reviews: 89,
    pricing: { min: 3800, max: 4500 },
    image: "/placeholder.jpg",
    amenities: ["Skilled Nursing", "Rehabilitation", "Chapel", "Pet-Friendly"],
    specialties: ["Skilled Nursing", "Rehabilitation", "Hospice Care"],
    availability: "Available",
    certifications: ["Medicare", "CARF", "Joint Commission"],
    established: 1995
  }
]

const careTypes = [
  "Independent Living",
  "Assisted Living",
  "Memory Care",
  "Skilled Nursing",
  "Continuing Care Retirement Community (CCRC)",
  "Adult Day Care",
  "Respite Care"
]

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

const specialtyServices = [
  "Alzheimer's Care",
  "Dementia Care",
  "Diabetes Management",
  "Heart Disease Management",
  "Stroke Recovery",
  "Physical Rehabilitation",
  "Occupational Rehabilitation",
  "Speech Rehabilitation",
  "Hospice Care",
  "Palliative Care",
  "Wound Care",
  "IV Therapy",
  "Dialysis",
  "Mental Health Services"
]

export default function AdvancedSearchPage() {
  const [searchFilters, setSearchFilters] = useState({
    location: "",
    radius: [25],
    careTypes: [] as string[],
    priceRange: [1000, 8000],
    rating: [0],
    amenities: [] as string[],
    specialties: [] as string[],
    availability: "any",
    certifications: [] as string[],
    establishedBefore: "",
    bedrooms: "any",
    moveInDate: ""
  })

  const [viewMode, setViewMode] = useState<"list" | "grid" | "map">("grid")
  const [sortBy, setSortBy] = useState("relevance")
  const [filteredFacilities, setFilteredFacilities] = useState(mockFacilities)
  const [showFilters, setShowFilters] = useState(true)

  const handleFilterChange = (key: string, value: any) => {
    setSearchFilters(prev => ({
      ...prev,
      [key]: value
    }))
  }

  const handleArrayFilterChange = (key: string, item: string, checked: boolean) => {
    setSearchFilters(prev => ({
      ...prev,
      [key]: checked
        ? [...prev[key as keyof typeof prev] as string[], item]
        : (prev[key as keyof typeof prev] as string[]).filter(i => i !== item)
    }))
  }

  const resetFilters = () => {
    setSearchFilters({
      location: "",
      radius: [25],
      careTypes: [],
      priceRange: [1000, 8000],
      rating: [0],
      amenities: [],
      specialties: [],
      availability: "any",
      certifications: [],
      establishedBefore: "",
      bedrooms: "any",
      moveInDate: ""
    })
  }

  const applyFilters = () => {
    // In a real app, this would filter the results based on searchFilters
    console.log("Applying filters:", searchFilters)
  }

  const renderStars = (rating: number) => {
    return Array.from({ length: 5 }, (_, i) => (
      <Star
        key={i}
        className={`h-4 w-4 ${i < Math.floor(rating) ? "text-yellow-400 fill-yellow-400" : "text-gray-300"
          }`}
      />
    ))
  }

  const getAvailabilityColor = (availability: string) => {
    switch (availability) {
      case "Available": return "text-green-700 bg-green-100"
      case "Limited": return "text-yellow-700 bg-yellow-100"
      case "Waitlist": return "text-red-700 bg-red-100"
      default: return "text-gray-700 bg-gray-100"
    }
  }

  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-7xl 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 items-center justify-between mb-6">
              <div>
                <h1 className="font-primary text-3xl md:text-4xl font-bold text-gray-900 mb-2">
                  Advanced Search
                </h1>
                <p className="font-body text-lg text-gray-600">
                  Find the perfect senior living facility with detailed filters
                </p>
              </div>
              <Link href="/search">
                <Button variant="outline" className="border-gray-300 text-gray-700 hover:bg-gray-50">
                  Back to Simple Search
                </Button>
              </Link>
            </div>

            {/* Quick Search Bar */}
            <AnimatedCard>
              <CardContent className="p-6">
                <div className="flex gap-4">
                  <div className="flex-1 relative">
                    <MapPin className="absolute left-3 top-3 h-5 w-5 text-gray-400" />
                    <Input
                      placeholder="Enter city, state, or ZIP code"
                      value={searchFilters.location}
                      onChange={(e) => handleFilterChange("location", e.target.value)}
                      className="pl-10 h-12"
                    />
                  </div>
                  <AnimatedButton
                    onClick={applyFilters}
                    className="bg-gradient-to-r from-[#3F5CEA] to-[#5B73F0] hover:from-[#09183D] hover:to-[#3F5CEA] text-white h-12 px-8"
                  >
                    <Search className="h-4 w-4 mr-2" />
                    Search
                  </AnimatedButton>
                </div>
              </CardContent>
            </AnimatedCard>
          </motion.div>

          <div className="grid grid-cols-1 lg:grid-cols-4 gap-8">
            {/* Filters Sidebar */}
            <div className={`lg:col-span-1 space-y-6 ${showFilters ? 'block' : 'hidden lg:block'}`}>
              <AnimatedCard>
                <CardHeader>
                  <div className="flex items-center justify-between">
                    <CardTitle className="font-primary text-xl text-gray-900">Filters</CardTitle>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={resetFilters}
                      className="text-gray-600 hover:text-gray-900"
                    >
                      <RotateCcw className="h-4 w-4 mr-1" />
                      Reset
                    </Button>
                  </div>
                </CardHeader>
                <CardContent className="space-y-6">
                  {/* Location & Distance */}
                  <div className="space-y-3">
                    <Label className="font-body font-medium text-gray-900">Search Radius</Label>
                    <div className="px-3">
                      <Slider
                        value={searchFilters.radius}
                        onValueChange={(value) => handleFilterChange("radius", value)}
                        max={100}
                        min={5}
                        step={5}
                        className="w-full"
                      />
                      <div className="flex justify-between text-sm text-gray-600 mt-2">
                        <span>5 miles</span>
                        <span>{searchFilters.radius[0]} miles</span>
                        <span>100 miles</span>
                      </div>
                    </div>
                  </div>

                  {/* Care Types */}
                  <div className="space-y-3">
                    <Label className="font-body font-medium text-gray-900">Care Types</Label>
                    <div className="space-y-2 max-h-48 overflow-y-auto">
                      {careTypes.map((type) => (
                        <div key={type} className="flex items-center space-x-2">
                          <Checkbox
                            id={type}
                            checked={searchFilters.careTypes.includes(type)}
                            onCheckedChange={(checked) =>
                              handleArrayFilterChange("careTypes", type, checked as boolean)
                            }
                          />
                          <Label htmlFor={type} className="font-body text-sm text-gray-700">{type}</Label>
                        </div>
                      ))}
                    </div>
                  </div>

                  {/* Price Range */}
                  <div className="space-y-3">
                    <Label className="font-body font-medium text-gray-900">Monthly Budget</Label>
                    <div className="px-3">
                      <Slider
                        value={searchFilters.priceRange}
                        onValueChange={(value) => handleFilterChange("priceRange", value)}
                        max={15000}
                        min={1000}
                        step={100}
                        className="w-full"
                      />
                      <div className="flex justify-between text-sm text-gray-600 mt-2">
                        <span>${searchFilters.priceRange[0].toLocaleString()}</span>
                        <span>${searchFilters.priceRange[1].toLocaleString()}</span>
                      </div>
                    </div>
                  </div>

                  {/* Minimum Rating */}
                  <div className="space-y-3">
                    <Label className="font-body font-medium text-gray-900">Minimum Rating</Label>
                    <div className="px-3">
                      <Slider
                        value={searchFilters.rating}
                        onValueChange={(value) => handleFilterChange("rating", value)}
                        max={5}
                        min={0}
                        step={0.5}
                        className="w-full"
                      />
                      <div className="flex justify-between items-center text-sm text-gray-600 mt-2">
                        <span>Any Rating</span>
                        <div className="flex items-center gap-1">
                          <span>{searchFilters.rating[0]}+</span>
                          <Star className="h-3 w-3 text-yellow-400 fill-yellow-400" />
                        </div>
                      </div>
                    </div>
                  </div>

                  {/* Availability */}
                  <div className="space-y-3">
                    <Label className="font-body font-medium text-gray-900">Availability</Label>
                    <Select value={searchFilters.availability} onValueChange={(value) => handleFilterChange("availability", value)}>
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="any">Any</SelectItem>
                        <SelectItem value="available">Available Now</SelectItem>
                        <SelectItem value="limited">Limited Availability</SelectItem>
                        <SelectItem value="waitlist">Accepting Waitlist</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  {/* Move-in Date */}
                  <div className="space-y-3">
                    <Label className="font-body font-medium text-gray-900">Desired Move-in Date</Label>
                    <Input
                      type="date"
                      value={searchFilters.moveInDate}
                      onChange={(e) => handleFilterChange("moveInDate", e.target.value)}
                    />
                  </div>

                  {/* Amenities */}
                  <div className="space-y-3">
                    <Label className="font-body font-medium text-gray-900">Required Amenities</Label>
                    <div className="space-y-2 max-h-48 overflow-y-auto">
                      {amenityOptions.map((amenity) => (
                        <div key={amenity} className="flex items-center space-x-2">
                          <Checkbox
                            id={amenity}
                            checked={searchFilters.amenities.includes(amenity)}
                            onCheckedChange={(checked) =>
                              handleArrayFilterChange("amenities", amenity, checked as boolean)
                            }
                          />
                          <Label htmlFor={amenity} className="font-body text-sm text-gray-700">{amenity}</Label>
                        </div>
                      ))}
                    </div>
                  </div>

                  {/* Specialty Services */}
                  <div className="space-y-3">
                    <Label className="font-body font-medium text-gray-900">Specialty Services</Label>
                    <div className="space-y-2 max-h-48 overflow-y-auto">
                      {specialtyServices.map((specialty) => (
                        <div key={specialty} className="flex items-center space-x-2">
                          <Checkbox
                            id={specialty}
                            checked={searchFilters.specialties.includes(specialty)}
                            onCheckedChange={(checked) =>
                              handleArrayFilterChange("specialties", specialty, checked as boolean)
                            }
                          />
                          <Label htmlFor={specialty} className="font-body text-sm text-gray-700">{specialty}</Label>
                        </div>
                      ))}
                    </div>
                  </div>

                  {/* Certifications */}
                  <div className="space-y-3">
                    <Label className="font-body font-medium text-gray-900">Certifications</Label>
                    <div className="space-y-2">
                      {["Medicare Certified", "CARF Accredited", "Joint Commission", "State Licensed"].map((cert) => (
                        <div key={cert} className="flex items-center space-x-2">
                          <Checkbox
                            id={cert}
                            checked={searchFilters.certifications.includes(cert)}
                            onCheckedChange={(checked) =>
                              handleArrayFilterChange("certifications", cert, checked as boolean)
                            }
                          />
                          <Label htmlFor={cert} className="font-body text-sm text-gray-700">{cert}</Label>
                        </div>
                      ))}
                    </div>
                  </div>

                  <AnimatedButton
                    onClick={applyFilters}
                    className="w-full bg-gradient-to-r from-[#3F5CEA] to-[#5B73F0] hover:from-[#09183D] hover:to-[#3F5CEA] text-white"
                  >
                    Apply Filters
                  </AnimatedButton>
                </CardContent>
              </AnimatedCard>
            </div>

            {/* Results */}
            <div className="lg:col-span-3 space-y-6">
              {/* Results Header */}
              <AnimatedCard>
                <CardContent className="p-6">
                  <div className="flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
                    <div className="flex items-center gap-4">
                      <span className="font-body text-gray-900">
                        <span className="font-semibold">{filteredFacilities.length}</span> facilities found
                      </span>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => setShowFilters(!showFilters)}
                        className="lg:hidden"
                      >
                        <SlidersHorizontal className="h-4 w-4 mr-2" />
                        Filters
                      </Button>
                    </div>

                    <div className="flex items-center gap-4">
                      <Select value={sortBy} onValueChange={setSortBy}>
                        <SelectTrigger className="w-40">
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="relevance">Relevance</SelectItem>
                          <SelectItem value="rating">Highest Rated</SelectItem>
                          <SelectItem value="price_low">Price: Low to High</SelectItem>
                          <SelectItem value="price_high">Price: High to Low</SelectItem>
                          <SelectItem value="distance">Distance</SelectItem>
                          <SelectItem value="newest">Newest</SelectItem>
                        </SelectContent>
                      </Select>

                      <div className="flex border border-gray-300 rounded-lg">
                        <button
                          onClick={() => setViewMode("grid")}
                          className={`p-2 ${viewMode === "grid" ? "bg-[#3F5CEA] text-white" : "text-gray-600 hover:bg-gray-50"}`}
                        >
                          <Grid className="h-4 w-4" />
                        </button>
                        <button
                          onClick={() => setViewMode("list")}
                          className={`p-2 ${viewMode === "list" ? "bg-[#3F5CEA] text-white" : "text-gray-600 hover:bg-gray-50"}`}
                        >
                          <List className="h-4 w-4" />
                        </button>
                        <button
                          onClick={() => setViewMode("map")}
                          className={`p-2 ${viewMode === "map" ? "bg-[#3F5CEA] text-white" : "text-gray-600 hover:bg-gray-50"}`}
                        >
                          <Map className="h-4 w-4" />
                        </button>
                      </div>
                    </div>
                  </div>

                  {/* Active Filters */}
                  {(searchFilters.careTypes.length > 0 || searchFilters.amenities.length > 0 || searchFilters.specialties.length > 0) && (
                    <div className="mt-4 pt-4 border-t border-gray-200">
                      <div className="flex flex-wrap gap-2">
                        {searchFilters.careTypes.map((type) => (
                          <Badge key={type} variant="secondary" className="bg-blue-100 text-blue-800">
                            {type}
                            <button
                              onClick={() => handleArrayFilterChange("careTypes", type, false)}
                              className="ml-1 hover:text-blue-900"
                            >
                              <X className="h-3 w-3" />
                            </button>
                          </Badge>
                        ))}
                        {searchFilters.amenities.slice(0, 3).map((amenity) => (
                          <Badge key={amenity} variant="secondary" className="bg-green-100 text-green-800">
                            {amenity}
                            <button
                              onClick={() => handleArrayFilterChange("amenities", amenity, false)}
                              className="ml-1 hover:text-green-900"
                            >
                              <X className="h-3 w-3" />
                            </button>
                          </Badge>
                        ))}
                        {searchFilters.amenities.length > 3 && (
                          <Badge variant="secondary" className="bg-gray-100 text-gray-800">
                            +{searchFilters.amenities.length - 3} more amenities
                          </Badge>
                        )}
                      </div>
                    </div>
                  )}
                </CardContent>
              </AnimatedCard>

              {/* Results Grid/List */}
              <div className={viewMode === "grid" ? "grid grid-cols-1 md:grid-cols-2 gap-6" : "space-y-6"}>
                {filteredFacilities.map((facility) => (
                  <AnimatedCard key={facility.id} className="group hover:shadow-lg transition-all duration-300">
                    <CardContent className="p-0">
                      <div className={viewMode === "list" ? "flex gap-6" : ""}>
                        {/* Image */}
                        <div className={`relative overflow-hidden ${viewMode === "list" ? "w-64 h-48" : "aspect-video"} rounded-t-lg`}>
                          <Image
                            src={facility.image}
                            alt={facility.name}
                            fill
                            className="object-cover group-hover:scale-105 transition-transform duration-300"
                          />
                          <div className="absolute top-3 left-3">
                            <Badge className={getAvailabilityColor(facility.availability)}>
                              {facility.availability}
                            </Badge>
                          </div>
                          <button className="absolute top-3 right-3 w-8 h-8 bg-white/90 hover:bg-white rounded-full flex items-center justify-center transition-colors">
                            <Heart className="h-4 w-4 text-gray-600 hover:text-red-500" />
                          </button>
                        </div>

                        {/* Content */}
                        <div className="p-6 flex-1">
                          <div className="flex items-start justify-between mb-3">
                            <div>
                              <h3 className="font-body font-semibold text-lg text-gray-900 mb-1 group-hover:text-[#3F5CEA] transition-colors">
                                {facility.name}
                              </h3>
                              <div className="flex items-center gap-2 mb-2">
                                <div className="flex items-center gap-1">
                                  {renderStars(facility.rating)}
                                </div>
                                <span className="font-body text-sm text-gray-600">
                                  {facility.rating} ({facility.reviews} reviews)
                                </span>
                              </div>
                              <div className="flex items-center gap-2 text-gray-600">
                                <MapPin className="h-4 w-4" />
                                <span className="font-body text-sm">{facility.address} • {facility.distance} miles</span>
                              </div>
                            </div>
                            <Badge variant="secondary" className="bg-blue-100 text-blue-800">
                              {facility.type}
                            </Badge>
                          </div>

                          <div className="space-y-3">
                            <div className="flex items-center justify-between">
                              <span className="font-body text-sm text-gray-600">Starting at</span>
                              <span className="font-body font-semibold text-lg text-gray-900">
                                ${facility.pricing.min.toLocaleString()}/month
                              </span>
                            </div>

                            <div className="flex flex-wrap gap-1">
                              {facility.amenities.slice(0, 4).map((amenity) => (
                                <Badge key={amenity} variant="secondary" className="text-xs">
                                  {amenity}
                                </Badge>
                              ))}
                              {facility.amenities.length > 4 && (
                                <Badge variant="secondary" className="text-xs">
                                  +{facility.amenities.length - 4} more
                                </Badge>
                              )}
                            </div>

                            <div className="flex gap-2 pt-3">
                              <Link href={`/facility/${facility.id}`} className="flex-1">
                                <Button className="w-full bg-gradient-to-r from-[#3F5CEA] to-[#5B73F0] hover:from-[#09183D] hover:to-[#3F5CEA] text-white">
                                  View Details
                                </Button>
                              </Link>
                              <Button variant="outline" className="border-[#3F5CEA] text-[#3F5CEA] hover:bg-[#3F5CEA] hover:text-white">
                                <Calendar className="h-4 w-4" />
                              </Button>
                            </div>
                          </div>
                        </div>
                      </div>
                    </CardContent>
                  </AnimatedCard>
                ))}
              </div>

              {/* Map View */}
              {viewMode === "map" && (
                <AnimatedCard>
                  <CardContent className="p-0">
                    <div className="h-96 bg-gray-100 rounded-lg flex items-center justify-center">
                      <div className="text-center">
                        <Map className="h-12 w-12 text-gray-400 mx-auto mb-3" />
                        <p className="font-body text-gray-600">Interactive map view coming soon</p>
                      </div>
                    </div>
                  </CardContent>
                </AnimatedCard>
              )}

              {/* Load More */}
              <div className="text-center pt-6">
                <Button variant="outline" className="border-[#3F5CEA] text-[#3F5CEA] hover:bg-[#3F5CEA] hover:text-white">
                  Load More Results
                </Button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <Footer />
    </div>
  )
}
