'use client';
import { useState } from 'react';
import Link from 'next/link';
import { Plus, Search, Pencil, Star } from 'lucide-react';
import { useAuth } from '@/hooks/useAuth';
import { useApi } from '@/hooks/useApi';
import { productsService } from '@/services/products.service';
import { Card } from '@/components/ui/Card';
import { Badge } from '@/components/ui/Badge';
import { Input } from '@/components/ui/Input';
import { PageHeader } from '@/components/layout/PageHeader';
import { LoadingState, EmptyState } from '@/components/ui/States';
import { formatCurrency } from '@/utils/formatCurrency';

export default function ProdutosPage() {
  const { storeId } = useAuth();
  const [q, setQ] = useState('');
  const { data, loading } = useApi(
    () => (storeId ? productsService.list(storeId) : Promise.resolve([])),
    [storeId],
  );

  const products = (data ?? []).filter((p) =>
    p.name.toLowerCase().includes(q.toLowerCase()) || p.sku.toLowerCase().includes(q.toLowerCase()),
  );

  return (
    <>
      <PageHeader
        title="Produtos"
        subtitle="Cadastre e gerencie seu catálogo"
        action={
          <Link href="/produtos/novo" className="inline-flex items-center gap-2 rounded-lg bg-brand-600 px-4 py-2 text-sm font-medium text-white hover:bg-brand-700">
            <Plus className="h-4 w-4" /> Novo produto
          </Link>
        }
      />

      <div className="mb-4 max-w-xs">
        <div className="relative">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-ink-400" />
          <Input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Buscar por nome ou SKU" className="pl-9" />
        </div>
      </div>

      <Card>
        {loading ? (
          <LoadingState />
        ) : products.length === 0 ? (
          <EmptyState title="Nenhum produto encontrado" description="Cadastre seu primeiro produto para começar a vender." />
        ) : (
          <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">Produto</th>
                  <th className="px-4 py-3 font-medium">SKU</th>
                  <th className="px-4 py-3 font-medium">Preço</th>
                  <th className="px-4 py-3 font-medium">Estoque</th>
                  <th className="px-4 py-3 font-medium">Status</th>
                  <th className="px-4 py-3" />
                </tr>
              </thead>
              <tbody>
                {products.map((p) => (
                  <tr key={p.id} className="border-b border-ink-50 last:border-0 hover:bg-ink-50/50">
                    <td className="px-4 py-3">
                      <div className="flex items-center gap-3">
                        {/* eslint-disable-next-line @next/next/no-img-element */}
                        <img src={p.images[0]} alt={p.name} className="h-10 w-10 rounded-lg object-cover" />
                        <div>
                          <p className="flex items-center gap-1 font-medium text-ink-900">
                            {p.name}
                            {p.featured && <Star className="h-3.5 w-3.5 fill-amber-400 text-amber-400" />}
                          </p>
                          {p.variations.length > 0 && (
                            <p className="text-xs text-ink-400">{p.variations.length} variações</p>
                          )}
                        </div>
                      </div>
                    </td>
                    <td className="px-4 py-3 text-ink-500">{p.sku}</td>
                    <td className="px-4 py-3">
                      {p.promoPrice ? (
                        <span>
                          <span className="font-medium text-ink-900">{formatCurrency(p.promoPrice)}</span>
                          <span className="ml-1 text-xs text-ink-400 line-through">{formatCurrency(p.price)}</span>
                        </span>
                      ) : (
                        <span className="font-medium text-ink-900">{formatCurrency(p.price)}</span>
                      )}
                    </td>
                    <td className="px-4 py-3">
                      {p.stock === 0 ? (
                        <Badge tone="red">Esgotado</Badge>
                      ) : p.stock <= p.minStock ? (
                        <Badge tone="amber">{p.stock} un.</Badge>
                      ) : (
                        <span className="text-ink-700">{p.stock} un.</span>
                      )}
                    </td>
                    <td className="px-4 py-3">
                      <Badge tone={p.status === 'ativo' ? 'green' : 'gray'}>
                        {p.status === 'ativo' ? 'Ativo' : 'Inativo'}
                      </Badge>
                    </td>
                    <td className="px-4 py-3 text-right">
                      <Link href={`/produtos/${p.id}`} className="inline-flex items-center gap-1 text-sm text-brand-600 hover:underline">
                        <Pencil className="h-3.5 w-3.5" /> Editar
                      </Link>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </Card>
    </>
  );
}
