'use client';
import Link from 'next/link';
import { useAuth } from '@/hooks/useAuth';
import { useApi } from '@/hooks/useApi';
import { customersService } from '@/services/customers.service';
import { Card } from '@/components/ui/Card';
import { PageHeader } from '@/components/layout/PageHeader';
import { LoadingState, EmptyState } from '@/components/ui/States';
import { formatDate } from '@/utils/formatDate';

export default function ClientesPage() {
  const { storeId } = useAuth();
  const { data, loading } = useApi(
    () => (storeId ? customersService.list(storeId) : Promise.resolve([])),
    [storeId],
  );

  return (
    <>
      <PageHeader title="Clientes" subtitle="Quem compra na sua loja" />
      <Card>
        {loading ? <LoadingState /> : (data ?? []).length === 0 ? (
          <EmptyState title="Nenhum cliente ainda" />
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-ink-100 text-left text-xs uppercase tracking-wide text-ink-400">
                  <th className="px-4 py-3 font-medium">Cliente</th>
                  <th className="px-4 py-3 font-medium">Contato</th>
                  <th className="px-4 py-3 font-medium">Pedidos</th>
                  <th className="px-4 py-3 font-medium">Último pedido</th>
                </tr>
              </thead>
              <tbody>
                {(data ?? []).map((c) => (
                  <tr key={c.id} className="border-b border-ink-50 last:border-0 hover:bg-ink-50/50">
                    <td className="px-4 py-3">
                      <Link href={`/clientes/${c.id}`} className="font-medium text-ink-900 hover:text-brand-600">{c.name}</Link>
                      <p className="text-xs text-ink-400">{c.document}</p>
                    </td>
                    <td className="px-4 py-3 text-ink-600">
                      <p>{c.email}</p>
                      <p className="text-xs text-ink-400">{c.phone}</p>
                    </td>
                    <td className="px-4 py-3 text-ink-700">{c.totalOrders}</td>
                    <td className="px-4 py-3 text-ink-500">{c.lastOrderDate ? formatDate(c.lastOrderDate) : '—'}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </Card>
    </>
  );
}
