"use client"

import { useState, useEffect } from "react"
import { authClient } from "@/lib/auth-client"
import { useRouter } from "next/navigation"
import { GatoMascota } from "@/components/child/gato-mascota"

interface ChildSummary {
  id: string
  name: string | null
}

export default function PairingPage() {
  const [code, setCode] = useState("")
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState("")
  const [paired, setPaired] = useState(false)
  const [children, setChildren] = useState<ChildSummary[]>([])
  const [selectedChildId, setSelectedChildId] = useState("")
  const { data: session } = authClient.useSession()
  const router = useRouter()

  useEffect(() => {
    fetch("/api/children")
      .then((r) => r.json())
      .then((list) => {
        if (Array.isArray(list)) {
          setChildren(list)
          if (list.length > 0) setSelectedChildId(list[0].id)
        }
      })
      .catch(() => {})
  }, [])

  const handlePairing = async (e: React.FormEvent) => {
    e.preventDefault()
    setLoading(true)
    setError("")

    if (!selectedChildId) {
      setError("Seleccioná un niño")
      setLoading(false)
      return
    }

    try {
      const res = await fetch("/api/pairing", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          pairingCode: code.toUpperCase(),
          childId: selectedChildId,
        }),
      })
      const data = await res.json()

      if (data.error) {
        setError(data.error)
        setLoading(false)
        return
      }

      setPaired(true)
    } catch {
      setError("Error de conexión")
    }
    setLoading(false)
  }

  if (!session) {
    return (
      <div className="min-h-dvh flex flex-col items-center justify-center p-6 gap-4">
        <p className="text-muted-foreground">Iniciá sesión primero para emparejar</p>
        <button
          onClick={() => router.push("/parent/auth/login")}
          className="bg-primary text-primary-foreground touch-target rounded-xl px-6 py-3 font-display"
        >
          Ir a login
        </button>
      </div>
    )
  }

  return (
    <div className="min-h-dvh flex flex-col items-center justify-center p-6 gap-6">
      <h1 className="text-2xl font-display font-bold">Emparejar iPad</h1>

      {paired ? (
        <div className="flex flex-col items-center gap-4">
          <GatoMascota mood="celebrate" message="iPad emparejado con éxito" size="lg" />
          <button
            onClick={() => router.push("/parent")}
            className="bg-primary text-primary-foreground touch-target rounded-xl px-6 py-3 font-display"
          >
            Volver al dashboard
          </button>
        </div>
      ) : (
        <form onSubmit={handlePairing} className="flex flex-col gap-4 w-full max-w-sm">
          <p className="text-muted-foreground text-center">
            Ingresá el código de 8 caracteres que aparece en el iPad
          </p>

          {children.length > 0 && (
            <div className="flex flex-wrap gap-2 justify-center">
              {children.map((c) => (
                <button
                  key={c.id}
                  type="button"
                  onClick={() => setSelectedChildId(c.id)}
                  className={`rounded-xl px-4 py-2 font-display text-sm transition-colors ${
                    c.id === selectedChildId
                      ? "bg-secondary text-secondary-foreground"
                      : "bg-muted text-foreground"
                  }`}
                >
                  {c.name || "Sin nombre"}
                </button>
              ))}
            </div>
          )}

          <input
            type="text"
            value={code}
            onChange={(e) => setCode(e.target.value.toUpperCase())}
            placeholder="Código de 8 letras"
            maxLength={8}
            className="w-full rounded-xl border border-border bg-white px-4 py-3 text-center text-2xl tracking-widest uppercase focus:outline-none focus:ring-2 focus:ring-primary"
            autoFocus
          />
          {error && <p className="text-destructive text-sm text-center">{error}</p>}
          <button
            type="submit"
            disabled={loading || code.length < 8}
            className="bg-secondary text-secondary-foreground touch-target rounded-xl text-lg font-display font-semibold disabled:opacity-50"
          >
            {loading ? "Emparejando..." : "Emparejar"}
          </button>
        </form>
      )}
    </div>
  )
}
