import { createFileRoute } from "@tanstack/react-router";
import { useMemo, useState } from "react";
import { AppShell } from "@/components/layout/AppShell";
import { EscopoToggle, useEscopo } from "@/components/layout/EscopoToggle";
import { useResumoMensal } from "@/features/lancamentos/hooks/useLancamentos";
import { tir, vpl, payback } from "@/features/analise/finance";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { formatBRL, formatPct } from "@/lib/format";

export const Route = createFileRoute("/analise")({
  component: Analise,
});

function Analise() {
  const { escopo } = useEscopo();
  const resumo = useResumoMensal(escopo);
  const [investimento, setInvestimento] = useState("10000");
  const [tmaPct, setTmaPct] = useState("1.0"); // % ao mês

  const result = useMemo(() => {
    if (resumo.length === 0) return null;
    const inv = -Math.abs(parseFloat(investimento) || 0);
    const tma = (parseFloat(tmaPct) || 0) / 100;
    const fluxos = [inv, ...resumo.map((r) => r.saldo)];
    return {
      fluxos,
      vplValor: vpl(tma, fluxos),
      tirValor: tir(fluxos),
      pay: payback(fluxos, tma),
      tma,
    };
  }, [resumo, investimento, tmaPct]);

  return (
    <AppShell
      title="Análise de Investimento"
      subtitle={escopo === "pj" ? "Empresa" : "Pessoal"}
      right={<EscopoToggle />}
    >
      <div className="space-y-4">
        <div className="grid grid-cols-2 gap-3">
          <div className="space-y-1.5">
            <Label htmlFor="inv">Investimento inicial (R$)</Label>
            <Input
              id="inv"
              type="number"
              value={investimento}
              onChange={(e) => setInvestimento(e.target.value)}
            />
          </div>
          <div className="space-y-1.5">
            <Label htmlFor="tma">TMA (% ao mês)</Label>
            <Input
              id="tma"
              type="number"
              step="0.1"
              value={tmaPct}
              onChange={(e) => setTmaPct(e.target.value)}
            />
          </div>
        </div>

        {result == null ? (
          <p className="rounded-2xl border border-dashed border-border bg-card/50 p-6 text-center text-sm text-muted-foreground">
            Cadastre lançamentos mensais para calcular VPL, TIR e Payback.
          </p>
        ) : (
          <>
            <Card label="VPL (Valor Presente Líquido)" value={formatBRL(result.vplValor)}
              hint={result.vplValor >= 0 ? "Projeto viável a essa TMA" : "Projeto inviável a essa TMA"} />
            <Card
              label="TIR (Taxa Interna de Retorno)"
              value={Number.isFinite(result.tirValor) ? formatPct(result.tirValor) : "—"}
              hint={
                Number.isFinite(result.tirValor)
                  ? result.tirValor > result.tma
                    ? "TIR > TMA: investimento atrativo"
                    : "TIR < TMA: rende menos que a TMA"
                  : "Sem mudança de sinal nos fluxos"
              }
            />
            <Card
              label="Payback simples"
              value={
                Number.isFinite(result.pay.periodoSimples)
                  ? `${result.pay.periodoSimples} meses`
                  : "Não recupera"
              }
            />
            <Card
              label="Payback descontado"
              value={
                Number.isFinite(result.pay.periodoDescontado)
                  ? `${result.pay.periodoDescontado} meses`
                  : "Não recupera"
              }
            />

            <details className="rounded-2xl border border-border bg-card p-3">
              <summary className="cursor-pointer text-sm font-medium text-foreground">
                Fluxos de caixa usados ({result.fluxos.length})
              </summary>
              <ol className="mt-2 space-y-1 text-xs text-muted-foreground">
                {result.fluxos.map((f, i) => (
                  <li key={i} className="flex justify-between">
                    <span>{i === 0 ? "Inicial" : `Mês ${i}`}</span>
                    <span
                      className={
                        f >= 0 ? "font-medium text-success" : "font-medium text-destructive"
                      }
                    >
                      {formatBRL(f)}
                    </span>
                  </li>
                ))}
              </ol>
            </details>
          </>
        )}
      </div>
    </AppShell>
  );
}

interface CardProps {
  label: string;
  value: string;
  hint?: string;
}

function Card({ label, value, hint }: CardProps) {
  return (
    <div className="rounded-2xl border border-border bg-card p-4">
      <p className="text-xs font-medium text-muted-foreground">{label}</p>
      <p className="mt-1 text-2xl font-bold text-foreground">{value}</p>
      {hint && <p className="mt-1 text-xs text-muted-foreground">{hint}</p>}
    </div>
  );
}
