"use client";

import {
  AlertTriangle,
  Building2,
  CheckCircle2,
  ChevronLeft,
  ChevronRight,
  Eye,
  Filter,
  MoreVertical,
  Pencil,
  Plus,
  RefreshCw,
  Search,
  Trash2,
  User,
  Users,
} from "lucide-react";
import { useState } from "react";
import { CustomerDetailModal } from "@/components/customers/customer-detail-modal";
import { CustomerFormModal } from "@/components/customers/customer-form-modal";
import { CustomerStatsCards } from "@/components/customers/customer-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 { useCustomers } from "@/hooks/use-customers";
import { currency } from "@/lib/utils";
import { Customer, CustomerStatus, CustomerType } from "@/types/customer";

export default function ClientesPage() {
  const {
    customers,
    stats,
    totalItems,
    totalPages,
    currentPage,
    filters,
    isLoading,
    isSaving,
    selectedCustomer,
    setSelectedCustomer,
    setSearch,
    setStatusFilter,
    setTypeFilter,
    setPage,
    loadData,
    loadCustomerDetails,
    createCustomer,
    updateCustomer,
    deleteCustomer,
    toggleStatus,
  } = useCustomers();

  const [isFormModalOpen, setIsFormModalOpen] = useState(false);
  const [customerToEdit, setCustomerToEdit] = useState<Customer | null>(null);
  const [isDetailModalOpen, setIsDetailModalOpen] = useState(false);
  const [actionDropdownOpen, setActionDropdownOpen] = useState<string | null>(null);

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

  const handleOpenEditModal = (customer: Customer) => {
    setCustomerToEdit(customer);
    setIsFormModalOpen(true);
    setActionDropdownOpen(null);
  };

  const handleOpenDetailModal = async (customer: Customer) => {
    setIsDetailModalOpen(true);
    await loadCustomerDetails(customer.id);
    setActionDropdownOpen(null);
  };

  const handleFormSubmit = async (data: any) => {
    if (customerToEdit) {
      await updateCustomer(customerToEdit.id, data);
    } else {
      await createCustomer(data);
    }
  };

  const renderStatusBadge = (status: CustomerStatus) => {
    switch (status) {
      case "ACTIVE":
        return <Badge tone="green">Ativo</Badge>;
      case "DELINQUENT":
        return <Badge tone="red">Inadimplente</Badge>;
      case "INACTIVE":
        return <Badge tone="blue">Inativo</Badge>;
      default:
        return <Badge tone="blue">{status}</Badge>;
    }
  };

  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 / Cadastros</p>
          <h1 className="mt-1 text-2xl font-bold tracking-tight text-foreground sm:text-3xl">
            Gestão de Clientes
          </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 Cliente
          </Button>
        </div>
      </div>

      {/* Cartões de Estatísticas / KPIs */}
      <CustomerStatsCards
        stats={stats}
        activeFilter={filters.status || "ALL"}
        onFilterClick={(statusKey) => setStatusFilter(statusKey as any)}
      />

      {/* Painel Principal com Tabela e Filtros */}
      <Card className="overflow-hidden shadow-xs border">
        {/* Barra de Busca e Filtros Avançados */}
        <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 nome, CPF/CNPJ, e-mail ou cidade..."
            />
          </div>

          <div className="flex flex-wrap items-center gap-3">
            {/* Filtro Tipo de Pessoa */}
            <div className="flex rounded-lg border bg-muted/50 p-1">
              <button
                onClick={() => setTypeFilter("ALL")}
                className={`rounded-md px-3 py-1 text-xs font-medium transition ${
                  filters.type === "ALL"
                    ? "bg-background text-foreground shadow-xs"
                    : "text-muted-foreground hover:text-foreground"
                }`}
              >
                Todos
              </button>
              <button
                onClick={() => setTypeFilter("COMPANY")}
                className={`flex items-center gap-1 rounded-md px-3 py-1 text-xs font-medium transition ${
                  filters.type === "COMPANY"
                    ? "bg-background text-foreground shadow-xs"
                    : "text-muted-foreground hover:text-foreground"
                }`}
              >
                <Building2 className="h-3 w-3" /> PJ
              </button>
              <button
                onClick={() => setTypeFilter("INDIVIDUAL")}
                className={`flex items-center gap-1 rounded-md px-3 py-1 text-xs font-medium transition ${
                  filters.type === "INDIVIDUAL"
                    ? "bg-background text-foreground shadow-xs"
                    : "text-muted-foreground hover:text-foreground"
                }`}
              >
                <User className="h-3 w-3" /> PF
              </button>
            </div>

            {/* Filtro por Status */}
            <select
              value={filters.status || "ALL"}
              onChange={(e) => setStatusFilter(e.target.value as any)}
              className="rounded-md border border-input bg-background px-3 py-1.5 text-xs font-medium shadow-xs focus:outline-hidden focus:ring-1 focus:ring-ring"
            >
              <option value="ALL">Todos os Status</option>
              <option value="ACTIVE">Ativos</option>
              <option value="INACTIVE">Inativos</option>
              <option value="DELINQUENT">Inadimplentes</option>
            </select>
          </div>
        </div>

        {/* Tabela de Clientes */}
        <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">Cliente</th>
                <th className="px-4 py-3.5 font-medium">CPF / CNPJ</th>
                <th className="px-4 py-3.5 font-medium">Contato</th>
                <th className="px-4 py-3.5 font-medium">Cidade/UF</th>
                <th className="px-4 py-3.5 font-medium">Limite de Crédito</th>
                <th className="px-4 py-3.5 font-medium">Status</th>
                <th className="w-16 px-4 py-3.5 text-right font-medium">Ações</th>
              </tr>
            </thead>
            <tbody className="divide-y">
              {isLoading ? (
                <tr>
                  <td colSpan={7} 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 clientes...</p>
                  </td>
                </tr>
              ) : customers.length === 0 ? (
                <tr>
                  <td colSpan={7} className="p-12 text-center">
                    <Users className="mx-auto h-10 w-10 text-muted-foreground/40" />
                    <h3 className="mt-3 text-base font-semibold">Nenhum cliente encontrado</h3>
                    <p className="mt-1 text-sm text-muted-foreground">
                      Tente ajustar os filtros ou cadastre um novo cliente.
                    </p>
                    <Button onClick={handleOpenCreateModal} variant="secondary" className="mt-4">
                      <Plus className="mr-1.5 h-4 w-4" /> Cadastrar Cliente
                    </Button>
                  </td>
                </tr>
              ) : (
                customers.map((customer) => (
                  <tr
                    key={customer.id}
                    className="group transition-colors hover:bg-muted/40"
                  >
                    {/* Nome & Tipo */}
                    <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">
                          {customer.type === "COMPANY" ? (
                            <Building2 className="h-4 w-4 text-primary" />
                          ) : (
                            <User className="h-4 w-4 text-primary" />
                          )}
                        </div>
                        <div>
                          <p
                            onClick={() => handleOpenDetailModal(customer)}
                            className="font-medium text-foreground hover:text-primary hover:underline cursor-pointer"
                          >
                            {customer.name}
                          </p>
                          {customer.email && (
                            <p className="text-xs text-muted-foreground truncate max-w-[200px]">
                              {customer.email}
                            </p>
                          )}
                        </div>
                      </div>
                    </td>

                    {/* Documento */}
                    <td className="px-4 py-3.5 font-mono text-xs text-foreground">
                      {customer.document}
                    </td>

                    {/* Contato */}
                    <td className="px-4 py-3.5 text-xs text-muted-foreground">
                      {customer.contactName && (
                        <p className="font-medium text-foreground">{customer.contactName}</p>
                      )}
                      <p>{customer.phone || customer.mobile || "Sem telefone"}</p>
                    </td>

                    {/* Cidade/UF */}
                    <td className="px-4 py-3.5 text-xs text-muted-foreground">
                      {customer.city ? (
                        <span>
                          {customer.city}
                          {customer.state ? ` - ${customer.state}` : ""}
                        </span>
                      ) : (
                        <span className="italic text-muted-foreground/60">Não informado</span>
                      )}
                    </td>

                    {/* Limite de Crédito */}
                    <td className="px-4 py-3.5 font-medium text-foreground">
                      {currency(customer.creditLimit)}
                    </td>

                    {/* Status */}
                    <td className="px-4 py-3.5">{renderStatusBadge(customer.status)}</td>

                    {/* Ações */}
                    <td className="px-4 py-3.5 text-right relative">
                      <div className="flex items-center justify-end gap-1">
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => handleOpenDetailModal(customer)}
                          title="Ver Detalhes"
                        >
                          <Eye className="h-4 w-4 text-muted-foreground hover:text-foreground" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => handleOpenEditModal(customer)}
                          title="Editar"
                        >
                          <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 cliente ${customer.name}?`
                              )
                            ) {
                              deleteCustomer(customer.id);
                            }
                          }}
                          title="Excluir"
                          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>

        {/* Rodapé da Tabela com 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 {customers.length} de {totalItems} clientes cadastrados
          </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) */}
      <CustomerFormModal
        isOpen={isFormModalOpen}
        onClose={() => setIsFormModalOpen(false)}
        onSubmit={handleFormSubmit}
        customerToEdit={customerToEdit}
        isSaving={isSaving}
      />

      {/* Modal de Detalhes do Cliente */}
      <CustomerDetailModal
        isOpen={isDetailModalOpen}
        onClose={() => setIsDetailModalOpen(false)}
        customer={selectedCustomer}
        onEdit={(cust) => {
          setIsDetailModalOpen(false);
          handleOpenEditModal(cust);
        }}
        onDelete={(id) => deleteCustomer(id)}
        onToggleStatus={(id, st) => toggleStatus(id, st)}
      />
    </div>
  );
}
