"use client"

import { useEffect, useMemo, useState } from "react"
import { Heart } from "lucide-react"
import { Button } from "@/components/ui/button"
import { useAuth } from "@/hooks/use-auth"
import { DataAPI } from "@/lib/data-api"
import { useToast } from "@/hooks/use-toast"

type Props = {
  facilityId: string
  initial?: boolean
  count?: number
  compact?: boolean
  onChange?: (isFavorite: boolean, count?: number) => void
}

export function FavoriteButton({ facilityId, initial, count, compact, onChange }: Props) {
  const { isAuthenticated } = useAuth()
  const { toast } = useToast()
  const [isFav, setIsFav] = useState(!!initial)
  const [pending, setPending] = useState(false)
  const [favCount, setFavCount] = useState<number | undefined>(count)

  useEffect(() => {
    if (typeof initial === 'boolean') setIsFav(initial)
  }, [initial])

  // Drop status fetch; rely on server-provided initial and count

  const variant = useMemo(() => (isFav ? "default" : "outline" as const), [isFav])

  const handleClick = async () => {
    if (!isAuthenticated) {
      toast({ title: "Sign in required", description: "Please sign in to save favorites." })
      window.location.href = `/login?next=${encodeURIComponent(window.location.pathname + window.location.search)}`
      return
    }
    try {
      setPending(true)
      if (isFav) {
        setIsFav(false)
        const res = await DataAPI.favorites.remove(facilityId)
        setFavCount((res as any)?.data?.count ?? (res as any)?.count)
        toast({ title: "Removed from favorites" })
        onChange?.(false, (res as any)?.data?.count ?? (res as any)?.count)
      } else {
        setIsFav(true)
        const res = await DataAPI.favorites.add(facilityId)
        setFavCount((res as any)?.data?.count ?? (res as any)?.count)
        toast({ title: "Added to favorites" })
        onChange?.(true, (res as any)?.data?.count ?? (res as any)?.count)
      }
    } catch (e: any) {
      setIsFav((prev) => !prev) // revert
      toast({ title: "Action failed", description: e?.message || "Please try again.", variant: "destructive" })
    } finally {
      setPending(false)
    }
  }

  return (
    <div className="inline-flex items-center gap-2">
      <Button size={compact ? "sm" : "default"} variant={variant} onClick={handleClick} disabled={pending} aria-pressed={isFav} className="rounded-full">
        <Heart className={`h-4 w-4 ${isFav ? 'fill-white' : ''}`} />
      </Button>
      {typeof favCount === 'number' && <span className="text-sm text-muted-foreground">{favCount}</span>}
    </div>
  )
}


