"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { GatoMascota } from "@/components/child/gato-mascota"
import { speak } from "@/lib/speech"

const CHILD_ID_KEY = "edueasy_child_id"

export default function ChildPairingPage() {
  const [code, setCode] = useState("")
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState("")
  const [paired, setPaired] = useState(false)
  const router = useRouter()

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

    const deviceFingerprint = `child-${navigator.userAgent.slice(0, 64)}`
    const res = await fetch("/api/pairing", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        pairingCode: code.toUpperCase(),
        deviceFingerprint,
      }),
    })
    const data = await res.json()

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

    localStorage.setItem(CHILD_ID_KEY, data.childId)
    setPaired(true)
    speak("¡Emparejado! Ahora podemos aprender juntos")
  }

  if (paired) {
    return (
      <div className="flex-1 flex flex-col items-center justify-center p-8 gap-6">
        <GatoMascota mood="celebrate" message="iPad emparejado" size="lg" />
        <button
          onClick={() => router.push("/child")}
          className="bg-primary text-primary-foreground touch-target-lg rounded-2xl px-8 py-4 text-xl font-display font-bold"
        >
          Ir a jugar
        </button>
      </div>
    )
  }

  return (
    <div className="flex-1 flex flex-col items-center justify-center p-6 gap-6">
      <GatoMascota mood="coach" message="Poné el código que te dió mamá" size="md" />

      <form onSubmit={handlePair} className="flex flex-col items-center gap-4 w-full max-w-sm">
        <input
          type="text"
          value={code}
          onChange={(e) => setCode(e.target.value.toUpperCase())}
          placeholder="Código"
          maxLength={8}
          className="w-full rounded-2xl border-2 border-primary bg-white px-6 py-4 text-center text-3xl tracking-[0.5em] uppercase font-display font-bold focus:outline-none focus:ring-4 focus:ring-primary/30"
          autoFocus
        />
        {error && <p className="text-destructive text-sm">{error}</p>}
        <button
          type="submit"
          disabled={loading || code.length < 8}
          className="bg-primary text-primary-foreground touch-target-lg rounded-2xl px-8 py-4 text-xl font-display font-bold disabled:opacity-50"
        >
          {loading ? "Emparejando..." : "¡Listo!"}
        </button>
        <button
          type="button"
          onClick={() => router.push("/child")}
          className="text-muted-foreground underline text-sm"
        >
          Volver
        </button>
      </form>
    </div>
  )
}
