"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { toast } from "sonner"
import { Button } from "@/components/ui/button"
import { Spinner } from "@/components/ui/spinner"

interface DashboardCheckInButtonProps {
  reservationId: string
  className?: string
}

export function DashboardCheckInButton({
  reservationId,
  className,
}: DashboardCheckInButtonProps) {
  const router = useRouter()
  const [loading, setLoading] = useState(false)

  const handleCheckIn = async () => {
    setLoading(true)
    const response = await fetch("/api/checkins", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ reservationId }),
    })

    const payload = (await response.json().catch(() => null)) as { error?: string } | null

    if (!response.ok) {
      toast.error(payload?.error ?? "No se pudo hacer check-in")
      setLoading(false)
      return
    }

    toast.success("Check-in realizado")
    setLoading(false)
    router.refresh()
  }

  return (
    <Button
      size="sm"
      variant="outline"
      className={className}
      disabled={loading}
      onClick={handleCheckIn}
    >
      {loading ? (
        <>
          <Spinner className="mr-1 h-4 w-4" />
          Check-in
        </>
      ) : (
        "Check-in"
      )}
    </Button>
  )
}
