"use client"

import { useEffect, useState } from 'react'
import { Card, CardContent } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { AnimatedCard } from '@/components/ui/animated-card'
import { AnimatedButton } from '@/components/ui/animated-button'
import { Star, ArrowRight, Loader2, CheckCircle } from 'lucide-react'
import Link from 'next/link'
import { motion } from 'framer-motion'
import { formatLocationDisplay } from '@/lib/location-utils'

interface FacilityBadge {
  type: 'featured' | 'top_rated' | 'new_listing' | 'verified'
  label: string
}

interface Facility {
  id: string
  slug: string
  name: string
  description: string
  careTypes: string[]
  location: {
    city: string
    state: string
    address: string
  }
  pricing: {
    min: number
    max: number
    currency: string
    period: string
  }
  images: string[]
  rating: number
  reviewCount: number
  badge: FacilityBadge
  featured?: boolean
  featuredUntil?: string
}

// Badge color mapping
const badgeStyles = {
  featured: 'bg-gradient-to-r from-purple-600 to-purple-700 text-white border border-purple-500/20',
  top_rated: 'bg-gradient-to-r from-orange-600 to-orange-700 text-white border border-orange-500/20',
  new_listing: 'bg-gradient-to-r from-blue-600 to-blue-700 text-white border border-blue-500/20',
  verified: 'bg-gradient-to-r from-green-600 to-green-700 text-white border border-green-500/20'
}

export default function FeaturedFacilities() {
  const [facilities, setFacilities] = useState<Facility[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    fetchFacilities()
  }, [])

  const fetchFacilities = async () => {
    try {
      setLoading(true)
      setError(null)
      
      const response = await fetch('/api/facilities/top-rated?limit=3')
      const data = await response.json()

      if (data.success) {
        setFacilities(data.data)
      } else {
        throw new Error(data.message || 'Failed to load facilities')
      }
    } catch (err: any) {
      console.error('Error fetching facilities:', err)
      setError(err.message)
    } finally {
      setLoading(false)
    }
  }

  // Render stars based on rating
  const renderStars = (rating: number, index: number) => {
    const stars = []
    const fullStars = Math.floor(rating)
    
    for (let i = 0; i < 5; i++) {
      stars.push(
        <motion.div
          key={i}
          initial={{ scale: 0, rotate: -180 }}
          animate={{ scale: 1, rotate: 0 }}
          transition={{ delay: 0.5 + i * 0.1 + index * 0.1, type: 'spring', stiffness: 300 }}
        >
          <Star
            className={`h-4 w-4 sm:h-5 sm:w-5 ${
              i < fullStars ? 'fill-yellow-400 text-yellow-400' : 'fill-gray-200 text-gray-200'
            }`}
          />
        </motion.div>
      )
    }
    return stars
  }

  // Format price
  const formatPrice = (price: number) => {
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'USD',
      minimumFractionDigits: 0,
      maximumFractionDigits: 0
    }).format(price)
  }

  // Format care types
  const formatCareTypes = (careTypes: string[]) => {
    if (careTypes.length === 0) return 'Senior Care'
    if (careTypes.length === 1) return careTypes[0]
    if (careTypes.length === 2) return careTypes.join(' • ')
    return `${careTypes[0]} • ${careTypes[1]}`
  }

  // Loading state
  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <Loader2 className="h-12 w-12 animate-spin text-[#3F5CEA]" />
      </div>
    )
  }

  // Error state
  if (error) {
    return (
      <div className="text-center py-20">
        <p className="text-red-600 mb-4">Failed to load facilities</p>
        <AnimatedButton onClick={fetchFacilities}>Try Again</AnimatedButton>
      </div>
    )
  }

  // Empty state
  if (facilities.length === 0) {
    return (
      <div className="text-center py-20">
        <p className="text-gray-600 text-lg mb-6">
          No facilities match the criteria at the moment. Please check back soon!
        </p>
        <Link href="/search">
          <AnimatedButton className="bg-[#3F5CEA] hover:bg-[#09183D] text-white">
            Browse All Facilities
          </AnimatedButton>
        </Link>
      </div>
    )
  }

  return (
    <motion.div
      className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5 sm:gap-6 lg:gap-8"
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      transition={{ duration: 0.6, delay: 0.2 }}
    >
      {facilities.map((facility, index) => (
        <motion.div
          key={facility.id}
          className="h-full"
          initial={{ opacity: 0, y: 50 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.6, delay: 0.1 * (index + 1) }}
        >
          <AnimatedCard className="bg-white border border-gray-100 shadow-md hover:shadow-xl transition-all duration-500 overflow-hidden group h-full">
            <CardContent className="p-6 sm:p-7 lg:p-8 relative flex flex-col h-full gap-0">
              {/* Featured Badge - Top Left */}
              {facility.featured && (
                <motion.div
                  className="absolute top-3 left-3 sm:top-4 sm:left-4 z-10"
                  initial={{ scale: 0, rotate: -180 }}
                  animate={{ scale: 1, rotate: 0 }}
                  transition={{ delay: 0.2 + index * 0.1, type: 'spring', stiffness: 300 }}
                >
                  <Badge className="bg-gradient-to-r from-yellow-500 via-orange-500 to-red-500 text-white shadow-lg flex items-center gap-1 px-2.5 py-1 sm:px-3 sm:py-1.5 text-[10px] sm:text-xs font-bold rounded-full animate-pulse">
                    <Star className="h-3 w-3 sm:h-3.5 sm:w-3.5 fill-white" />
                    FEATURED
                  </Badge>
                </motion.div>
              )}
              
              {/* Dynamic Badge - Top Right */}
              <motion.div
                className="absolute top-3 right-3 sm:top-4 sm:right-4 z-10"
                initial={{ scale: 0 }}
                animate={{ scale: 1 }}
                transition={{ delay: 0.3 + index * 0.1, type: 'spring', stiffness: 300 }}
              >
                <Badge
                  className={`shadow-lg flex items-center gap-1 sm:gap-1.5 px-2.5 py-1 sm:px-3 sm:py-1.5 text-[10px] sm:text-xs font-bold rounded-full ${
                    badgeStyles[facility.badge.type]
                  }`}
                >
                  {facility.badge.type === 'verified' && (
                    <CheckCircle className="h-3 w-3 sm:h-3.5 sm:w-3.5" />
                  )}
                  {facility.badge.label}
                </Badge>
              </motion.div>
              
              {/* Content wrapper */}
              <div className="flex-grow flex flex-col pt-8 sm:pt-0">
                {/* Rating - Single Star Display */}
                <div className="flex items-center gap-2 mb-4 sm:mb-5">
                  <motion.div 
                    className="flex items-center gap-1.5 bg-yellow-50 px-2.5 py-1 rounded-full border border-yellow-200 shadow-sm"
                    initial={{ opacity: 0, scale: 0.8 }}
                    animate={{ opacity: 1, scale: 1 }}
                    transition={{ delay: 0.4 + index * 0.1, type: 'spring', stiffness: 300 }}
                    whileHover={{ scale: 1.05 }}
                  >
                    <Star className="h-4 w-4 fill-yellow-400 text-yellow-400" />
                    <span className="font-sans text-sm font-bold text-gray-900">
                      {facility.rating.toFixed(1)}
                    </span>
                  </motion.div>
                  <span className="font-sans text-xs sm:text-sm text-gray-500 font-medium">
                    ({facility.reviewCount} review{facility.reviewCount !== 1 ? 's' : ''})
                  </span>
                </div>

                {/* Facility name */}
                <h3 className="font-serif text-lg sm:text-xl lg:text-2xl font-bold text-gray-900 mb-3 sm:mb-4 group-hover:text-[#3F5CEA] transition-colors duration-300 line-clamp-2 leading-tight">
                  {facility.name}
                </h3>

                {/* Care types */}
                <div className="mb-3 sm:mb-4">
                  <p className="font-sans text-sm sm:text-base text-gray-700 font-medium leading-relaxed">
                    {formatCareTypes(facility.careTypes)}
                  </p>
                </div>

                {/* Location */}
                <div className="flex items-center gap-2 mb-5 sm:mb-6">
                  <svg className="w-4 h-4 text-gray-400 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
                  </svg>
                  <p className="font-sans text-xs sm:text-sm text-gray-600 font-medium uppercase tracking-wide">
                    {formatLocationDisplay(facility)}
                  </p>
                </div>
              </div>

              {/* Divider */}
              <div className="border-t border-gray-100 mb-5 sm:mb-6"></div>

              {/* Pricing and CTA */}
              <div className="flex flex-col mt-auto gap-4">
                {/* Pricing Row */}
                <div className="font-sans">
                  {facility.pricing.min > 0 ? (
                    <div>
                      <div className="text-[10px] sm:text-xs text-gray-500 font-medium mb-1 uppercase tracking-wide">Starting at</div>
                      <div className="text-xl sm:text-2xl lg:text-3xl font-bold text-[#3F5CEA] leading-tight">
                        {formatPrice(facility.pricing.min)}
                        <span className="text-sm sm:text-base lg:text-lg font-semibold text-gray-600">/
                          {facility.pricing.period === 'monthly' ? 'mo' : 'day'}
                        </span>
                      </div>
                    </div>
                  ) : (
                    <div>
                      <div className="text-[10px] sm:text-xs text-gray-500 font-medium mb-1 uppercase tracking-wide">Pricing</div>
                      <div className="text-base sm:text-lg font-bold text-[#3F5CEA]">
                        Contact for Details
                      </div>
                    </div>
                  )}
                </div>

                {/* Button Row */}
                <Link href={`/facility/${facility.id}`} className="w-full">
                  <AnimatedButton
                    size="default"
                    variant="outline"
                    className="w-full border-2 border-[#3F5CEA] text-[#3F5CEA] hover:bg-[#3F5CEA] hover:text-white bg-white hover:shadow-lg transition-all duration-300 font-semibold text-sm sm:text-base px-6 py-2.5 sm:py-3 whitespace-nowrap"
                  >
                    View Details
                  </AnimatedButton>
                </Link>
              </div>
            </CardContent>
          </AnimatedCard>
        </motion.div>
      ))}
    </motion.div>
  )
}

