'use client';

import { useEffect, useState } from 'react';
import Header from '@/components/header';
import api from '@/lib/api';

interface KanbanCard {
  id: string;
  title: string;
  subtitle?: string;
  amount?: number;
}

interface DashStats {
  activeContracts: number;
  expectedThisMonth: number;
  receivedThisMonth: number;
  overdue: number;
  nfseCount: number;
  issExpected: number;
}

const COLUMNS: { key: string; title: string; dot: string }[] = [
  { key: 'contato',    title: 'Contato recebido',      dot: 'bg-blue-500'   },
  { key: 'proposta',   title: 'Proposta',               dot: 'bg-yellow-500' },
  { key: 'contrato',   title: 'Contrato',               dot: 'bg-orange-500' },
  { key: 'aguardando', title: 'Aguardando assinatura',  dot: 'bg-purple-500' },
  { key: 'ativo',      title: 'Contratos ativos',       dot: 'bg-green-500'  },
];

const PROPOSAL_STATUS_PT: Record<string, string> = {
  draft: 'Rascunho', sent: 'Enviada', viewed: 'Visualizada',
  accepted: 'Aceita', rejected: 'Rejeitada',
};

function fmtMoney(n: number) {
  return n.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });
}

function StatCard({
  icon, label, value, money, color,
}: {
  icon: string; label: string; value: number; money?: boolean;
  color: 'green' | 'blue' | 'red' | 'yellow' | 'accent';
}) {
  const bg: Record<string, string> = {
    green:  'bg-green-50 text-green-700',
    blue:   'bg-blue-50 text-blue-700',
    red:    'bg-red-50 text-red-700',
    yellow: 'bg-yellow-50 text-yellow-700',
    accent: 'bg-[#EAE4D9] text-[#B7895A]',
  };
  return (
    <div className="bg-white rounded-xl border border-[#EAE4D9] p-5">
      <div className={`w-9 h-9 rounded-lg flex items-center justify-center text-base mb-3 ${bg[color]}`}>
        {icon}
      </div>
      <p className="text-xl font-bold text-[#0E0F12] truncate">
        {money ? fmtMoney(value) : value}
      </p>
      <p className="text-xs text-[#0E0F12]/50 mt-1">{label}</p>
    </div>
  );
}

export default function DashboardPage() {
  const [kanban, setKanban] = useState<Record<string, KanbanCard[]>>({
    contato: [], proposta: [], contrato: [], aguardando: [], ativo: [],
  });
  const [stats, setStats] = useState<DashStats>({
    activeContracts: 0, expectedThisMonth: 0,
    receivedThisMonth: 0, overdue: 0, nfseCount: 0, issExpected: 0,
  });
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function load() {
      const now = new Date();
      const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);
      const monthEnd   = new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59);

      const [cliRes, propRes, conRes, chgRes, invRes] = await Promise.allSettled([
        api.get('/clients?limit=100'),
        api.get('/proposals?limit=100'),
        api.get('/contracts?limit=200'),
        api.get('/charges?limit=500'),
        api.get('/invoices?limit=500'),
      ]);

      const clients  = cliRes.status  === 'fulfilled' ? (cliRes.value.data.data  ?? cliRes.value.data)  : [];
      const proposals= propRes.status === 'fulfilled' ? (propRes.value.data.data ?? propRes.value.data) : [];
      const contracts= conRes.status  === 'fulfilled' ? (conRes.value.data.data  ?? conRes.value.data)  : [];
      const charges  = chgRes.status  === 'fulfilled' ? (chgRes.value.data.data  ?? chgRes.value.data)  : [];
      const invoices = invRes.status  === 'fulfilled' ? (invRes.value.data.data  ?? invRes.value.data)  : [];

      const activeContracts = contracts.filter((c: { status: string }) => c.status === 'active');

      // Each client occupies exactly one column — the most advanced stage they've reached.
      // Priority: ativo (4) > aguardando (3) > contrato (2) > proposta (1) > contato (0)
      type StageEntry = { stage: string; order: number; subtitle?: string; amount?: number };
      const clientStage = new Map<string, StageEntry>();

      for (const c of clients as { id: string; document?: string; createdAt: string }[]) {
        clientStage.set(c.id, {
          stage: 'contato',
          order: 0,
          subtitle: c.document ?? new Date(c.createdAt).toLocaleDateString('pt-BR'),
        });
      }

      for (const p of proposals as { id: string; clientId: string; number: string; total: number; status: string }[]) {
        if (!['draft', 'sent', 'viewed', 'accepted'].includes(p.status)) continue;
        const cur = clientStage.get(p.clientId);
        if (!cur || cur.order < 1) {
          clientStage.set(p.clientId, {
            stage: 'proposta',
            order: 1,
            subtitle: `Proposta #${p.number} — ${PROPOSAL_STATUS_PT[p.status] ?? p.status}`,
            amount: Number(p.total),
          });
        }
      }

      const contractStageMap: Record<string, { stage: string; order: number }> = {
        draft:             { stage: 'contrato',   order: 2 },
        pending_signature: { stage: 'aguardando', order: 3 },
        active:            { stage: 'ativo',      order: 4 },
      };

      for (const c of contracts as { id: string; clientId: string; number: string; total: number; status: string }[]) {
        const mapped = contractStageMap[c.status];
        if (!mapped) continue;
        const cur = clientStage.get(c.clientId);
        if (!cur || cur.order < mapped.order) {
          clientStage.set(c.clientId, {
            stage: mapped.stage,
            order: mapped.order,
            subtitle: `Contrato #${c.number}`,
            amount: Number(c.total),
          });
        }
      }

      const kanbanData: Record<string, KanbanCard[]> = {
        contato: [], proposta: [], contrato: [], aguardando: [], ativo: [],
      };

      for (const [clientId, info] of clientStage) {
        const client = (clients as { id: string; name: string }[]).find((c) => c.id === clientId);
        if (!client) continue;
        kanbanData[info.stage]?.push({
          id: clientId,
          title: client.name,
          subtitle: info.subtitle,
          amount: info.amount,
        });
      }

      setKanban(kanbanData);

      const expectedThisMonth = (charges as { status: string; amount: number; dueDate: string }[])
        .filter((c) => {
          if (c.status !== 'pending') return false;
          const due = new Date(c.dueDate + 'T00:00:00');
          return due >= monthStart && due <= monthEnd;
        })
        .reduce((s, c) => s + Number(c.amount), 0);

      const receivedThisMonth = (charges as { status: string; amount: number; paidAt?: string }[])
        .filter((c) => {
          if (c.status !== 'paid' || !c.paidAt) return false;
          const d = new Date(c.paidAt);
          return d >= monthStart && d <= monthEnd;
        })
        .reduce((s, c) => s + Number(c.amount), 0);

      const overdue = (charges as { status: string; amount: number }[])
        .filter((c) => c.status === 'overdue')
        .reduce((s, c) => s + Number(c.amount), 0);

      const monthInvoices = (invoices as {
        createdAt: string; status: string;
        serviceAmount: number; issAliquota?: number; issRetained?: boolean;
      }[]).filter((inv) => {
        const d = new Date(inv.createdAt);
        return d >= monthStart && d <= monthEnd && inv.status !== 'cancelled';
      });

      const nfseCount = monthInvoices.length;

      // ISS esperado = soma de serviceAmount * issAliquota / 100 das NFs não retidas no mês
      const issExpected = monthInvoices
        .filter((inv) => !inv.issRetained && inv.issAliquota)
        .reduce((s, inv) => s + Number(inv.serviceAmount) * Number(inv.issAliquota) / 100, 0);

      setStats({ activeContracts: activeContracts.length, expectedThisMonth, receivedThisMonth, overdue, nfseCount, issExpected });
    }

    load().finally(() => setLoading(false));
  }, []);

  if (loading) {
    return (
      <>
        <Header title="Dashboard" subtitle="Visão geral e pipeline" />
        <p className="text-sm text-[#0E0F12]/50">Carregando...</p>
      </>
    );
  }

  return (
    <>
      <Header title="Dashboard" subtitle="Visão geral e pipeline" />

      {/* Kanban */}
      <div className="overflow-x-auto -mx-1 px-1">
        <div className="flex gap-3 min-w-max pb-2">
          {COLUMNS.map((col) => {
            const cards = kanban[col.key] ?? [];
            return (
              <div key={col.key} className="w-52 shrink-0 flex flex-col">
                <div className="flex items-center gap-2 mb-2">
                  <span className={`w-2 h-2 rounded-full shrink-0 ${col.dot}`} />
                  <h3 className="text-xs font-semibold text-[#0E0F12] uppercase tracking-wide leading-none flex-1 min-w-0 truncate">
                    {col.title}
                  </h3>
                  <span className="text-xs font-medium text-[#0E0F12]/40 bg-[#EAE4D9] px-1.5 py-0.5 rounded-full shrink-0">
                    {cards.length}
                  </span>
                </div>

                <div
                  className="flex flex-col gap-2 overflow-y-auto rounded-xl"
                  style={{ maxHeight: 'calc(100vh - 340px)', minHeight: '120px' }}
                >
                  {cards.length === 0 ? (
                    <div className="border-2 border-dashed border-[#EAE4D9] rounded-xl p-4 text-center flex-1">
                      <p className="text-xs text-[#0E0F12]/40">Nenhum item</p>
                    </div>
                  ) : (
                    cards.map((card) => (
                      <div
                        key={card.id}
                        className="bg-white rounded-xl border border-[#EAE4D9] p-3 shadow-sm hover:shadow transition-shadow"
                      >
                        <p className="text-sm font-medium text-[#0E0F12] truncate">{card.title}</p>
                        {card.subtitle && (
                          <p className="text-xs text-[#0E0F12]/50 mt-0.5 truncate">{card.subtitle}</p>
                        )}
                        {card.amount !== undefined && (
                          <p className="text-xs font-semibold text-[#B7895A] mt-1">{fmtMoney(card.amount)}</p>
                        )}
                      </div>
                    ))
                  )}
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-2 sm:grid-cols-3 xl:grid-cols-6 gap-4 mt-6">
        <StatCard icon="📄" label="Contratos ativos"         value={stats.activeContracts}    color="green"  />
        <StatCard icon="📅" label="Expectativa do mês"       value={stats.expectedThisMonth}  color="blue"   money />
        <StatCard icon="✅" label="Recebido no mês"          value={stats.receivedThisMonth}  color="green"  money />
        <StatCard icon="⚠️" label="Recebimento vencido"     value={stats.overdue}            color="red"    money />
        <StatCard icon="🧾" label="NFS-e emitidas no mês"   value={stats.nfseCount}          color="accent" />
        <StatCard icon="🏛️" label="ISS estimado no mês"    value={stats.issExpected}        color="yellow" money />
      </div>
    </>
  );
}
