"use client";

import {
  AlertTriangle,
  ArrowDownRight,
  ArrowUpRight,
  CheckCircle2,
  ChevronLeft,
  ChevronRight,
  DollarSign,
  Plus,
  RefreshCw,
  Search,
  Wallet,
} from "lucide-react";
import { useEffect, useState } from "react";
import { useSearchParams } from "next/navigation";
import { FinancialEntryModal } from "@/components/finance/financial-entry-modal";
import { ClearEntryModal } from "@/components/finance/clear-entry-modal";
import { FinanceStatsCards } from "@/components/finance/finance-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 { useFinance } from "@/hooks/use-finance";
import { rebuildAllFinancials } from "@/services/rental-service";
import { currency, formatDate } from "@/lib/utils";
import { FinancialStatus } from "@/types/finance";

export default function FinanceiroPage() {
  const {
    receivables,
    payables,
    cashFlow,
    customers,
    stats,
    activeTab,
    filters,
    isLoading,
    isSaving,
    totalItems,
    totalPages,
    currentPage,
    itemsPerPage,
    setActiveTab,
    setSearch,
    setStatusFilter,
    setPage,
    setLimit,
    loadData,
    createEntry,
    payReceivable,
    payPayable,
  } = useFinance();

  const searchParams = useSearchParams();
  const [isEntryModalOpen, setIsEntryModalOpen] = useState(false);
  const [isClearModalOpen, setIsClearModalOpen] = useState(false);
  const [selectedClearEntry, setSelectedClearEntry] = useState<{ id: string; description: string; amount: number } | null>(null);
  const [clearEntryType, setClearEntryType] = useState<"RECEIVABLE" | "PAYABLE">("RECEIVABLE");
  const [isSyncing, setIsSyncing] = useState(false);

  // Sync tab & search filters from URL parameters if present
  useEffect(() => {
    const tabParam = searchParams.get("tab");
    const searchParam = searchParams.get("search");

    if (tabParam === "PAYABLES" || tabParam === "PAYABLE") {
      if (activeTab !== "PAYABLES") setActiveTab("PAYABLES");
    } else if (tabParam === "RECEIVABLES" || tabParam === "RECEIVABLE") {
      if (activeTab !== "RECEIVABLES") setActiveTab("RECEIVABLES");
    } else if (tabParam === "CASH_FLOW") {
      if (activeTab !== "CASH_FLOW") setActiveTab("CASH_FLOW");
    }

    if (searchParam !== null && filters.search !== searchParam) {
      setSearch(searchParam);
    }
  }, [searchParams, activeTab, filters.search, setActiveTab, setSearch]);

  // Auto-sync financial entries on mount to fix any wrong amounts in DB
  useEffect(() => {
    const syncOnMount = async () => {
      try {
        await rebuildAllFinancials();
      } catch {
        // ignore
      }
    };
    syncOnMount();
  }, []);

  const handleSyncFinancials = async () => {
    setIsSyncing(true);
    try {
      await rebuildAllFinancials();
      await loadData();
    } finally {
      setIsSyncing(false);
    }
  };

  const handleOpenClearReceivable = (rec: any) => {
    setSelectedClearEntry({ id: rec.id, description: rec.description, amount: Number(rec.amount) });
    setClearEntryType("RECEIVABLE");
    setIsClearModalOpen(true);
  };

  const handleOpenClearPayable = (pay: any) => {
    setSelectedClearEntry({ id: pay.id, description: pay.description, amount: Number(pay.amount) });
    setClearEntryType("PAYABLE");
    setIsClearModalOpen(true);
  };

  const handleConfirmClear = async (amountPaid: number, paidAt: string, newDueDate?: string) => {
    if (!selectedClearEntry) return;
    if (clearEntryType === "RECEIVABLE") {
      await payReceivable(selectedClearEntry.id, { amountPaid, paidAt, newDueDate });
    } else {
      await payPayable(selectedClearEntry.id, { amountPaid, paidAt, newDueDate });
    }
  };

  const renderStatusBadge = (status: FinancialStatus) => {
    switch (status) {
      case "PAID":
        return <Badge tone="green">Pago / Quitado</Badge>;
      case "OPEN":
        return <Badge tone="blue">Aberto</Badge>;
      case "OVERDUE":
        return <Badge tone="red">Vencido / Atrasado</Badge>;
      case "CANCELED":
        return <Badge tone="red">Cancelado</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 / Gestão Financeira</p>
          <h1 className="mt-1 text-2xl font-bold tracking-tight text-foreground sm:text-3xl">
            Módulo Financeiro & Fluxo de Caixa
          </h1>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="secondary" onClick={handleSyncFinancials} disabled={isSyncing} title="Sincronizar lançamentos com locações">
            <RefreshCw className={`mr-1.5 h-4 w-4 ${isSyncing ? "animate-spin" : ""}`} />
            {isSyncing ? "Sincronizando..." : "Sincronizar"}
          </Button>
          <Button onClick={() => setIsEntryModalOpen(true)} className="shadow-xs">
            <Plus className="mr-1.5 h-4 w-4" /> Novo Lançamento
          </Button>
        </div>
      </div>

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

      {/* Navegação por Abas (Contas a Receber, Contas a Pagar, Fluxo de Caixa) */}
      <Card className="overflow-hidden shadow-xs border">
        <div className="flex flex-col gap-4 border-b bg-card p-4 sm:flex-row sm:items-center sm:justify-between">
          <div className="flex rounded-lg border bg-muted/50 p-1">
            <button
              onClick={() => setActiveTab("RECEIVABLES")}
              className={`flex items-center gap-2 rounded-md px-4 py-2 text-xs font-semibold transition ${
                activeTab === "RECEIVABLES"
                  ? "bg-background text-emerald-600 shadow-xs dark:text-emerald-400"
                  : "text-muted-foreground hover:text-foreground"
              }`}
            >
              <ArrowUpRight className="h-4 w-4" /> Contas a Receber ({receivables.length})
            </button>
            <button
              onClick={() => setActiveTab("PAYABLES")}
              className={`flex items-center gap-2 rounded-md px-4 py-2 text-xs font-semibold transition ${
                activeTab === "PAYABLES"
                  ? "bg-background text-rose-600 shadow-xs dark:text-rose-400"
                  : "text-muted-foreground hover:text-foreground"
              }`}
            >
              <ArrowDownRight className="h-4 w-4" /> Contas a Pagar ({payables.length})
            </button>
            <button
              onClick={() => setActiveTab("CASH_FLOW")}
              className={`flex items-center gap-2 rounded-md px-4 py-2 text-xs font-semibold transition ${
                activeTab === "CASH_FLOW"
                  ? "bg-background text-blue-600 shadow-xs dark:text-blue-400"
                  : "text-muted-foreground hover:text-foreground"
              }`}
            >
              <Wallet className="h-4 w-4" /> Extrato / Fluxo de Caixa
            </button>
          </div>

          {/* Busca e Filtros */}
          <div className="flex items-center gap-3">
            <div className="relative max-w-xs">
              <Search className="pointer-events-none absolute left-3 top-2.5 h-4 w-4 text-muted-foreground" />
              <Input
                value={filters.search || ""}
                onChange={(e) => setSearch(e.target.value)}
                className="pl-9 text-xs h-9"
                placeholder={activeTab === "CASH_FLOW" ? "Buscar extrato..." : "Buscar por descrição..."}
              />
            </div>

            {activeTab !== "CASH_FLOW" && (
              <select
                value={filters.status || "ALL"}
                onChange={(e) => setStatusFilter(e.target.value as any)}
                className="h-9 rounded-md border border-input bg-background px-3 text-xs font-medium shadow-xs focus:outline-hidden focus:ring-1 focus:ring-ring font-semibold"
              >
                <option value="ALL">Todos os Status</option>
                <option value="OPEN">Aberto</option>
                <option value="PAID">Quitados</option>
                <option value="OVERDUE">Vencidos</option>
              </select>
            )}
          </div>
        </div>

        {/* Tabela de Contas a Receber */}
        {activeTab === "RECEIVABLES" && (
          <div className="overflow-x-auto">
            <table className="w-full min-w-[750px] 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">Descrição / Título</th>
                  <th className="px-4 py-3.5 font-medium">Cliente</th>
                  <th className="px-4 py-3.5 font-medium">Vencimento</th>
                  <th className="px-4 py-3.5 font-medium">Data Baixa</th>
                  <th className="px-4 py-3.5 font-medium">Valor (R$)</th>
                  <th className="px-4 py-3.5 font-medium">Situação</th>
                  <th className="w-24 px-4 py-3.5 text-right font-medium">Ação</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 contas a receber...</p>
                    </td>
                  </tr>
                ) : receivables.length === 0 ? (
                  <tr>
                    <td colSpan={7} className="p-12 text-center text-muted-foreground">
                      Nenhum título a receber encontrado.
                    </td>
                  </tr>
                ) : (
                  receivables.map((rec) => (
                    <tr key={rec.id} className="group hover:bg-muted/40 transition-colors">
                      <td className="px-4 py-3.5 font-medium text-foreground">
                        {rec.description}
                      </td>
                      <td className="px-4 py-3.5 text-xs text-muted-foreground">
                        <p className="font-semibold text-foreground">
                          {rec.customer?.name || "Cliente Padrão"}
                        </p>
                        {rec.customer?.document && <p className="font-mono">{rec.customer.document}</p>}
                      </td>
                      <td className="px-4 py-3.5 text-xs font-medium">
                        {formatDate(rec.dueDate)}
                      </td>
                      <td className="px-4 py-3.5 text-xs font-semibold text-muted-foreground">
                        {rec.paidAt ? formatDate(rec.paidAt) : "-"}
                      </td>
                      <td className="px-4 py-3.5 font-bold text-emerald-600 dark:text-emerald-400">
                        {currency(rec.amount)}
                      </td>
                      <td className="px-4 py-3.5">{renderStatusBadge(rec.status)}</td>
                      <td className="px-4 py-3.5 text-right">
                        {rec.status !== "PAID" && (
                          <Button
                            variant="secondary"
                            size="sm"
                            onClick={() => handleOpenClearReceivable(rec)}
                            className="text-xs"
                          >
                            <CheckCircle2 className="mr-1 h-3.5 w-3.5 text-emerald-500" /> Dar Baixa
                          </Button>
                        )}
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        )}

        {/* Tabela de Contas a Pagar */}
        {activeTab === "PAYABLES" && (
          <div className="overflow-x-auto">
            <table className="w-full min-w-[750px] 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">Descrição da Despesa</th>
                  <th className="px-4 py-3.5 font-medium">Fornecedor</th>
                  <th className="px-4 py-3.5 font-medium">Vencimento</th>
                  <th className="px-4 py-3.5 font-medium">Data Baixa</th>
                  <th className="px-4 py-3.5 font-medium">Valor (R$)</th>
                  <th className="px-4 py-3.5 font-medium">Situação</th>
                  <th className="w-24 px-4 py-3.5 text-right font-medium">Ação</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 contas a pagar...</p>
                    </td>
                  </tr>
                ) : payables.length === 0 ? (
                  <tr>
                    <td colSpan={7} className="p-12 text-center text-muted-foreground">
                      Nenhuma conta a pagar encontrada.
                    </td>
                  </tr>
                ) : (
                  payables.map((pay) => (
                    <tr key={pay.id} className="group hover:bg-muted/40 transition-colors">
                      <td className="px-4 py-3.5 font-medium text-foreground">
                        {pay.description}
                      </td>
                      <td className="px-4 py-3.5 text-xs text-muted-foreground font-semibold">
                        {pay.supplier?.name || "Fornecedor Cadastrado"}
                      </td>
                      <td className="px-4 py-3.5 text-xs font-medium">
                        {formatDate(pay.dueDate)}
                      </td>
                      <td className="px-4 py-3.5 text-xs font-semibold text-muted-foreground">
                        {pay.paidAt ? formatDate(pay.paidAt) : "-"}
                      </td>
                      <td className="px-4 py-3.5 font-bold text-rose-600 dark:text-rose-400">
                        {currency(pay.amount)}
                      </td>
                      <td className="px-4 py-3.5">{renderStatusBadge(pay.status)}</td>
                      <td className="px-4 py-3.5 text-right">
                        {pay.status !== "PAID" && (
                          <Button
                            variant="secondary"
                            size="sm"
                            onClick={() => handleOpenClearPayable(pay)}
                            className="text-xs"
                          >
                            <CheckCircle2 className="mr-1 h-3.5 w-3.5 text-emerald-500" /> Pagar
                          </Button>
                        )}
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        )}

        {/* Extrato / Fluxo de Caixa */}
        {activeTab === "CASH_FLOW" && (
          <div className="overflow-x-auto">
            <table className="w-full min-w-[700px] 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">Data / Hora</th>
                  <th className="px-4 py-3.5 font-medium">Descrição da Movimentação</th>
                  <th className="px-4 py-3.5 font-medium">Categoria</th>
                  <th className="px-4 py-3.5 font-medium">Tipo</th>
                  <th className="px-4 py-3.5 text-right font-medium">Valor (R$)</th>
                </tr>
              </thead>
              <tbody className="divide-y">
                {cashFlow.map((cm) => (
                  <tr key={cm.id} className="hover:bg-muted/40 transition-colors">
                    <td className="px-4 py-3.5 text-xs font-mono text-muted-foreground">
                      {new Date(cm.occurredAt).toLocaleString("pt-BR")}
                    </td>
                    <td className="px-4 py-3.5 font-medium text-foreground">
                      {cm.description}
                    </td>
                    <td className="px-4 py-3.5 text-xs text-muted-foreground">
                      {cm.category || "Geral"}
                    </td>
                    <td className="px-4 py-3.5">
                      {cm.type === "INCOME" ? (
                        <Badge tone="green">Entrada</Badge>
                      ) : (
                        <Badge tone="red">Saída</Badge>
                      )}
                    </td>
                    <td
                      className={`px-4 py-3.5 font-bold text-right ${
                        cm.type === "INCOME"
                          ? "text-emerald-600 dark:text-emerald-400"
                          : "text-rose-600 dark:text-rose-400"
                      }`}
                    >
                      {cm.type === "INCOME" ? `+ ${currency(cm.amount)}` : `- ${currency(cm.amount)}`}
                    </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 bg-muted/20">
          <div className="flex flex-wrap items-center gap-2">
            <span>
              Exibindo {
                activeTab === "RECEIVABLES"
                  ? receivables.length
                  : activeTab === "PAYABLES"
                  ? payables.length
                  : cashFlow.length
              } lançamentos de {totalItems} no total
            </span>
            <span className="hidden sm:inline text-muted-foreground">•</span>
            <div className="flex items-center gap-1.5">
              <span>Itens por página:</span>
              <select
                value={itemsPerPage}
                onChange={(e) => setLimit(Number(e.target.value))}
                className="rounded-md border border-input bg-background px-2 py-1 text-[11px] font-medium shadow-xs focus:ring-1 focus:ring-ring focus:outline-hidden"
              >
                <option value={10}>10</option>
                <option value={20}>20</option>
                <option value={50}>50</option>
                <option value={100}>100</option>
              </select>
            </div>
          </div>

          <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 Novo Lançamento Financeiro */}
      <FinancialEntryModal
        isOpen={isEntryModalOpen}
        onClose={() => setIsEntryModalOpen(false)}
        onSubmit={createEntry}
        customers={customers}
        isSaving={isSaving}
      />

      {/* Modal de Confirmação e Baixa de Título */}
      <ClearEntryModal
        isOpen={isClearModalOpen}
        onClose={() => setIsClearModalOpen(false)}
        onConfirm={handleConfirmClear}
        entry={selectedClearEntry}
        type={clearEntryType}
        isSaving={isSaving}
      />
    </div>
  );
}
