import { createFileRoute } from "@tanstack/react-router";
import { useMemo } from "react";
import {
  ResponsiveContainer,
  LineChart,
  Line,
  XAxis,
  YAxis,
  Tooltip,
  CartesianGrid,
  PieChart,
  Pie,
  Cell,
  Legend,
} from "recharts";
import { AppShell } from "@/components/layout/AppShell";
import { EscopoToggle, useEscopo } from "@/components/layout/EscopoToggle";
import {
  useLancamentos,
  useResumoMensal,
} from "@/features/lancamentos/hooks/useLancamentos";
import { formatBRL, formatMes } from "@/lib/format";

export const Route = createFileRoute("/relatorios")({
  component: Relatorios,
});

const CORES = ["#1f5e6a", "#e4b956", "#5ba696", "#c46a52", "#7a8db3", "#9b6fa0", "#a89b62"];

function Relatorios() {
  const { escopo } = useEscopo();
  const resumo = useResumoMensal(escopo);
  const items = useLancamentos(escopo);

  const dadosLinha = useMemo(
    () =>
      resumo.map((r) => ({
        mes: formatMes(r.mes),
        Entradas: r.entradas,
        Saídas: r.saidas,
        Saldo: r.saldoAcumulado,
      })),
    [resumo],
  );

  const porCategoria = useMemo(() => {
    const m = new Map<string, number>();
    for (const l of items) {
      if (l.tipo !== "saida") continue;
      m.set(l.categoria, (m.get(l.categoria) ?? 0) + l.valor);
    }
    return [...m.entries()]
      .map(([name, value]) => ({ name, value }))
      .sort((a, b) => b.value - a.value)
      .slice(0, 7);
  }, [items]);

  return (
    <AppShell
      title="Relatórios"
      subtitle={escopo === "pj" ? "Empresa" : "Pessoal"}
      right={<EscopoToggle />}
    >
      {resumo.length === 0 ? (
        <p className="rounded-2xl border border-dashed border-border bg-card/50 p-6 text-center text-sm text-muted-foreground">
          Adicione lançamentos para ver os relatórios.
        </p>
      ) : (
        <div className="space-y-6">
          <section>
            <h2 className="mb-2 text-sm font-semibold text-foreground">
              Evolução do saldo
            </h2>
            <div className="h-64 rounded-2xl border border-border bg-card p-2">
              <ResponsiveContainer width="100%" height="100%">
                <LineChart data={dadosLinha} margin={{ top: 10, right: 10, left: -10, bottom: 0 }}>
                  <CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" />
                  <XAxis dataKey="mes" fontSize={11} />
                  <YAxis fontSize={11} tickFormatter={(v) => `${(v / 1000).toFixed(0)}k`} />
                  <Tooltip formatter={(v) => formatBRL(Number(v))} />
                  <Legend wrapperStyle={{ fontSize: 12 }} />
                  <Line type="monotone" dataKey="Saldo" stroke="#1f5e6a" strokeWidth={2.5} dot={false} />
                  <Line type="monotone" dataKey="Entradas" stroke="#5ba696" strokeWidth={1.5} dot={false} />
                  <Line type="monotone" dataKey="Saídas" stroke="#c46a52" strokeWidth={1.5} dot={false} />
                </LineChart>
              </ResponsiveContainer>
            </div>
          </section>

          {porCategoria.length > 0 && (
            <section>
              <h2 className="mb-2 text-sm font-semibold text-foreground">
                Saídas por categoria
              </h2>
              <div className="h-64 rounded-2xl border border-border bg-card p-2">
                <ResponsiveContainer width="100%" height="100%">
                  <PieChart>
                    <Pie
                      data={porCategoria}
                      dataKey="value"
                      nameKey="name"
                      innerRadius={45}
                      outerRadius={80}
                    >
                      {porCategoria.map((_, i) => (
                        <Cell key={i} fill={CORES[i % CORES.length]} />
                      ))}
                    </Pie>
                    <Tooltip formatter={(v) => formatBRL(Number(v))} />
                    <Legend wrapperStyle={{ fontSize: 11 }} />
                  </PieChart>
                </ResponsiveContainer>
              </div>
            </section>
          )}

          <section>
            <h2 className="mb-2 text-sm font-semibold text-foreground">Tabela mensal</h2>
            <div className="overflow-hidden rounded-2xl border border-border bg-card">
              <table className="w-full text-xs">
                <thead className="bg-secondary text-muted-foreground">
                  <tr>
                    <th className="px-2 py-2 text-left">Mês</th>
                    <th className="px-2 py-2 text-right">Entradas</th>
                    <th className="px-2 py-2 text-right">Saídas</th>
                    <th className="px-2 py-2 text-right">Saldo</th>
                  </tr>
                </thead>
                <tbody>
                  {resumo.map((r) => (
                    <tr key={r.mes} className="border-t border-border">
                      <td className="px-2 py-2 font-medium text-foreground">
                        {formatMes(r.mes)}
                      </td>
                      <td className="px-2 py-2 text-right text-success">
                        {formatBRL(r.entradas)}
                      </td>
                      <td className="px-2 py-2 text-right text-destructive">
                        {formatBRL(r.saidas)}
                      </td>
                      <td className="px-2 py-2 text-right font-semibold text-foreground">
                        {formatBRL(r.saldoAcumulado)}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </section>
        </div>
      )}
    </AppShell>
  );
}
