'use client';

import { useEffect, useMemo, useState } from 'react';
import AdminGuard from '@/components/admin-guard';
import { claimsApi, type AdminClaim } from '@/lib/api';

export default function AdminClaimsPage() {
  return (
    <AdminGuard>
      <ClaimsView />
    </AdminGuard>
  );
}

function ClaimsView() {
  const [claims, setClaims] = useState<AdminClaim[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    claimsApi.list().then((c) => setClaims(c)).finally(() => setLoading(false));
  }, []);

  const totals = useMemo(() => {
    const byItem: Record<string, { reserved: number; total: number }> = {};
    for (const c of claims) {
      const k = c.itemId;
      if (!byItem[k]) byItem[k] = { reserved: 0, total: c.itemQuantity };
      byItem[k].reserved += c.quantity;
    }
    return byItem;
  }, [claims]);

  if (loading) {
    return <div className="min-h-screen flex items-center justify-center text-gray-500">Carregando…</div>;
  }

  return (
    <div className="max-w-5xl mx-auto p-6 space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold">Reservas</h1>
        <div className="text-sm text-gray-500">{claims.length} no total</div>
      </div>

      {claims.length === 0 ? (
        <div className="border rounded p-6 text-center text-gray-500">Nenhuma reserva ainda.</div>
      ) : (
        <div className="overflow-x-auto border rounded">
          <table className="w-full text-sm">
            <thead className="bg-gray-50 dark:bg-gray-800">
              <tr className="text-left">
                <th className="p-3">Item</th>
                <th className="p-3">Qtd</th>
                <th className="p-3">Convidado</th>
                <th className="p-3">Nota</th>
                <th className="p-3">Quando</th>
              </tr>
            </thead>
            <tbody>
              {claims.map((c) => {
                const t = totals[c.itemId];
                return (
                  <tr key={c.claimId} className="border-t">
                    <td className="p-3">
                      <div className="font-medium">{c.itemName}</div>
                      <div className="text-xs text-gray-500">
                        {c.wishlistName} · {t.reserved}/{t.total} reservados
                      </div>
                    </td>
                    <td className="p-3">{c.quantity}</td>
                    <td className="p-3">{c.guestName}</td>
                    <td className="p-3 italic text-gray-600 dark:text-gray-400">{c.note ?? '—'}</td>
                    <td className="p-3 text-gray-500">{new Date(c.claimedAt).toLocaleString('pt-BR')}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
