"use client";
// components/flow/TicketLookup.tsx
// "Consulta tus boletos" — DNI-only lookup. Posts to /api/tickets/lookup (rate
// limited, no-PII) and renders the ticket numbers grouped by raffle, plus a
// "participa de nuevo" CTA. Client-side DNI validation mirrors the register form
// (validation.ts); the server re-validates.

import * as React from "react";
import Link from "next/link";
import { Button, Card, Input } from "@/components/ui";
import type { TicketLookupResponse } from "@/lib/types";
import { isValidDni } from "./validation";

export function TicketLookup() {
  const [dni, setDni] = React.useState("");
  const [touched, setTouched] = React.useState(false);
  const [loading, setLoading] = React.useState(false);
  const [result, setResult] = React.useState<TicketLookupResponse | null>(null);
  const [error, setError] = React.useState<string | null>(null);

  const dniError =
    touched && dni.length > 0 && !isValidDni(dni) ? "El DNI tiene 8 dígitos." : undefined;

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    setTouched(true);
    if (!isValidDni(dni)) return;
    setLoading(true);
    setError(null);
    setResult(null);
    try {
      const res = await fetch("/api/tickets/lookup", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ dni: dni.trim() }),
      });
      const payload = await res.json().catch(() => null);
      if (!res.ok) {
        setError(
          payload?.error?.message ??
            "No pudimos consultar tus boletos. Intenta de nuevo.",
        );
        return;
      }
      setResult(payload as TicketLookupResponse);
    } catch {
      setError(
        "No pudimos consultar tus boletos. Revisa tu conexión e intenta de nuevo.",
      );
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="mx-auto flex w-full max-w-[480px] flex-col gap-lg px-5 py-10">
      <Card elevation="tight">
        <h1 className="font-display text-heading-lg text-ink-strong">
          Consulta tus boletos
        </h1>
        <p className="mt-2 font-body text-body-md text-muted">
          Ingresa tu DNI para ver los números de tus boletos en la Rifa Solidaria
          Teletón.
        </p>

        <form onSubmit={onSubmit} className="mt-4 flex flex-col gap-4" noValidate>
          <Input
            label="DNI"
            name="dni"
            type="text"
            inputMode="numeric"
            autoComplete="off"
            enterKeyHint="search"
            maxLength={8}
            placeholder="12345678"
            required
            hint="8 dígitos."
            value={dni}
            error={dniError}
            onChange={(e) =>
              setDni(e.target.value.replace(/\D/g, "").slice(0, 8))
            }
            onBlur={() => setTouched(true)}
          />
          <Button type="submit" size="lg" block disabled={loading}>
            {loading ? "Buscando..." : "Buscar mis boletos"}
          </Button>
        </form>

        {error ? (
          <p className="mt-3 font-body text-body-sm text-primary" role="alert">
            {error}
          </p>
        ) : null}
      </Card>

      {result ? (
        result.found ? (
          <Card elevation="tight">
            <div className="flex flex-col gap-3">
              {result.raffles.map((r) => (
                <div
                  key={r.raffleName}
                  className="border-t border-hairline pt-3 first:border-t-0 first:pt-0"
                >
                  <p className="font-body text-caption uppercase tracking-wide text-muted-label">
                    {r.raffleName}
                  </p>
                  <p className="mt-1 font-body text-body-md text-ink-strong">
                    {r.count} {r.count === 1 ? "boleto" : "boletos"}
                  </p>
                  <p className="mt-1 font-body text-body-md font-semibold text-ink-strong tabular-nums">
                    {r.ticketNumbers.join(", ")}
                  </p>
                </div>
              ))}
            </div>
          </Card>
        ) : (
          <Card elevation="tight">
            <p className="font-body text-body-md text-ink-strong">
              No encontramos boletos con ese DNI.
            </p>
            <p className="mt-1 font-body text-body-sm text-muted">
              Verifica el número, o participa para conseguir tus boletos.
            </p>
          </Card>
        )
      ) : null}

      {/* Buy-more CTA (product requirement): always offered on this screen. */}
      <div className="rounded-md border border-hairline p-4">
        <p className="font-body text-body-md font-semibold text-ink-strong">
          ¿Quieres más boletos?
        </p>
        <p className="mt-1 font-body text-body-sm text-muted">
          Cada S/5 es un boleto más y más posibilidades de ganar.
        </p>
        <Link href="/participar" className="mt-3 block">
          <Button type="button" size="lg" block>
            Participa de nuevo
          </Button>
        </Link>
      </div>
    </div>
  );
}
