"use client";

import {
  BriefcaseBusiness,
  ChevronLeft,
  ChevronRight,
  Eye,
  Mail,
  Pencil,
  Phone,
  Plus,
  RefreshCw,
  Search,
  Trash2,
  User,
} from "lucide-react";
import { useState } from "react";
import { SupplierDetailModal } from "@/components/suppliers/supplier-detail-modal";
import { SupplierFormModal } from "@/components/suppliers/supplier-form-modal";
import { SupplierStatsCards } from "@/components/suppliers/supplier-stats-cards";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { useSuppliers } from "@/hooks/use-suppliers";
import { currency } from "@/lib/utils";
import { Supplier } from "@/types/supplier";

export default function FornecedoresPage() {
  const {
    suppliers,
    stats,
    totalItems,
    totalPages,
    currentPage,
    filters,
    isLoading,
    isSaving,
    selectedSupplier,
    setSelectedSupplier,
    setSearch,
    setPage,
    loadData,
    loadSupplierDetails,
    createSupplier,
    updateSupplier,
    deleteSupplier,
  } = useSuppliers();

  const [isFormModalOpen, setIsFormModalOpen] = useState(false);
  const [supplierToEdit, setSupplierToEdit] = useState<Supplier | null>(null);
  const [isDetailModalOpen, setIsDetailModalOpen] = useState(false);

  const handleOpenCreateModal = () => {
    setSupplierToEdit(null);
    setIsFormModalOpen(true);
  };

  const handleOpenEditModal = (sup: Supplier) => {
    setSupplierToEdit(sup);
    setIsFormModalOpen(true);
  };

  const handleOpenDetailModal = async (sup: Supplier) => {
    setIsDetailModalOpen(true);
    await loadSupplierDetails(sup.id);
  };

  const handleFormSubmit = async (data: any) => {
    if (supplierToEdit) {
      await updateSupplier(supplierToEdit.id, data);
    } else {
      await createSupplier(data);
    }
  };

  return (
    <div className="space-y-6">
      {/* Header com Título e Ação */}
      <div className="flex flex-wrap items-center justify-between gap-4">
        <div>
          <p className="text-sm font-medium text-muted-foreground">Dashboard / Compras & Serviços</p>
          <h1 className="mt-1 text-2xl font-bold tracking-tight text-foreground sm:text-3xl">
            Gestão de Fornecedores
          </h1>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="secondary" size="icon" onClick={() => loadData()} title="Atualizar dados">
            <RefreshCw className={`h-4 w-4 ${isLoading ? "animate-spin" : ""}`} />
          </Button>
          <Button onClick={handleOpenCreateModal} className="shadow-xs">
            <Plus className="mr-1.5 h-4 w-4" /> Novo Fornecedor
          </Button>
        </div>
      </div>

      {/* Cartões de Estatísticas / KPIs */}
      <SupplierStatsCards stats={stats} />

      {/* Painel Principal com Tabela e Filtros */}
      <Card className="overflow-hidden shadow-xs border">
        {/* Barra de Busca */}
        <div className="flex flex-col gap-4 border-b bg-card p-4 lg:flex-row lg:items-center lg:justify-between">
          <div className="relative flex-1 max-w-md">
            <Search className="pointer-events-none absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
            <Input
              value={filters.search || ""}
              onChange={(e) => setSearch(e.target.value)}
              className="pl-9"
              placeholder="Buscar por razão social, CNPJ, e-mail ou contato..."
            />
          </div>
        </div>

        {/* Tabela de Fornecedores */}
        <div className="overflow-x-auto">
          <table className="w-full min-w-[800px] text-left text-sm">
            <thead className="bg-muted/50 text-xs uppercase text-muted-foreground">
              <tr>
                <th className="px-4 py-3.5 font-medium">Razão Social / Nome</th>
                <th className="px-4 py-3.5 font-medium">CNPJ / CPF</th>
                <th className="px-4 py-3.5 font-medium">Contato</th>
                <th className="px-4 py-3.5 font-medium">Telefone</th>
                <th className="px-4 py-3.5 font-medium">Contas em Aberto</th>
                <th className="w-24 px-4 py-3.5 text-right font-medium">Ações</th>
              </tr>
            </thead>
            <tbody className="divide-y">
              {isLoading ? (
                <tr>
                  <td colSpan={6} className="p-8 text-center text-muted-foreground">
                    <RefreshCw className="mx-auto h-6 w-6 animate-spin text-primary" />
                    <p className="mt-2 text-xs">Carregando fornecedores...</p>
                  </td>
                </tr>
              ) : suppliers.length === 0 ? (
                <tr>
                  <td colSpan={6} className="p-12 text-center">
                    <BriefcaseBusiness className="mx-auto h-10 w-10 text-muted-foreground/40" />
                    <h3 className="mt-3 text-base font-semibold">Nenhum fornecedor encontrado</h3>
                    <p className="mt-1 text-sm text-muted-foreground">
                      Tente ajustar os filtros ou cadastre um novo fornecedor.
                    </p>
                    <Button onClick={handleOpenCreateModal} variant="secondary" className="mt-4">
                      <Plus className="mr-1.5 h-4 w-4" /> Cadastrar Fornecedor
                    </Button>
                  </td>
                </tr>
              ) : (
                suppliers.map((sup) => (
                  <tr key={sup.id} className="group transition-colors hover:bg-muted/40">
                    {/* Nome */}
                    <td className="px-4 py-3.5">
                      <div className="flex items-center gap-3">
                        <div className="rounded-lg border bg-background p-2 group-hover:border-primary/40 transition-colors">
                          <BriefcaseBusiness className="h-4 w-4 text-primary" />
                        </div>
                        <div>
                          <p
                            onClick={() => handleOpenDetailModal(sup)}
                            className="font-bold text-foreground hover:text-primary hover:underline cursor-pointer"
                          >
                            {sup.name}
                          </p>
                          {sup.email && (
                            <p className="text-xs text-muted-foreground">{sup.email}</p>
                          )}
                        </div>
                      </div>
                    </td>

                    {/* CNPJ / CPF */}
                    <td className="px-4 py-3.5 font-mono text-xs">
                      {sup.document || "—"}
                    </td>

                    {/* Contato */}
                    <td className="px-4 py-3.5 text-xs text-muted-foreground">
                      {sup.contactName || "—"}
                    </td>

                    {/* Telefone */}
                    <td className="px-4 py-3.5 font-mono text-xs">
                      {sup.phone || "—"}
                    </td>

                    {/* Contas em Aberto */}
                    <td className="px-4 py-3.5">
                      {sup.openPayablesCount && sup.openPayablesCount > 0 ? (
                        <div>
                          <Badge tone="blue">
                            {sup.openPayablesCount} fatura(s)
                          </Badge>
                          <p className="text-xs font-bold text-purple-600 dark:text-purple-400 mt-0.5">
                            {currency(sup.totalOpenAmount || 0)}
                          </p>
                        </div>
                      ) : (
                        <span className="text-xs text-muted-foreground">Sem pendências</span>
                      )}
                    </td>

                    {/* Ações */}
                    <td className="px-4 py-3.5 text-right">
                      <div className="flex items-center justify-end gap-1">
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => handleOpenDetailModal(sup)}
                          title="Ver Detalhes"
                        >
                          <Eye className="h-4 w-4 text-muted-foreground hover:text-foreground" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => handleOpenEditModal(sup)}
                          title="Editar Fornecedor"
                        >
                          <Pencil className="h-4 w-4 text-muted-foreground hover:text-foreground" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => {
                            if (confirm(`Tem certeza que deseja excluir o fornecedor ${sup.name}?`)) {
                              deleteSupplier(sup.id);
                            }
                          }}
                          title="Excluir Fornecedor"
                          className="text-rose-500 hover:bg-rose-500/10 hover:text-rose-600"
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>

        {/* Paginação */}
        <div className="flex flex-col gap-3 border-t px-4 py-3.5 sm:flex-row sm:items-center sm:justify-between text-xs text-muted-foreground">
          <span>
            Exibindo {suppliers.length} de {totalItems} fornecedores
          </span>

          <div className="flex items-center gap-2">
            <span className="mr-2">
              Página {currentPage} de {totalPages}
            </span>
            <Button
              variant="secondary"
              size="sm"
              disabled={currentPage <= 1 || isLoading}
              onClick={() => setPage(currentPage - 1)}
            >
              <ChevronLeft className="h-4 w-4 mr-1" /> Anterior
            </Button>
            <Button
              variant="secondary"
              size="sm"
              disabled={currentPage >= totalPages || isLoading}
              onClick={() => setPage(currentPage + 1)}
            >
              Próxima <ChevronRight className="h-4 w-4 ml-1" />
            </Button>
          </div>
        </div>
      </Card>

      {/* Modal de Formulário (Novo / Editar Fornecedor) */}
      <SupplierFormModal
        isOpen={isFormModalOpen}
        onClose={() => setIsFormModalOpen(false)}
        onSubmit={handleFormSubmit}
        supplierToEdit={supplierToEdit}
        isSaving={isSaving}
      />

      {/* Modal de Detalhes do Fornecedor */}
      <SupplierDetailModal
        isOpen={isDetailModalOpen}
        onClose={() => setIsDetailModalOpen(false)}
        supplier={selectedSupplier}
        onEdit={(sup) => {
          setIsDetailModalOpen(false);
          handleOpenEditModal(sup);
        }}
        onDelete={(id) => deleteSupplier(id)}
      />
    </div>
  );
}
