"use client";

import {
  Bar, CartesianGrid, Cell, Legend, Pie, PieChart, ResponsiveContainer, Tooltip, XAxis, YAxis, Line, ComposedChart,
} from "recharts";

const brl = (v: number) => v.toLocaleString("pt-BR", { style: "currency", currency: "BRL", maximumFractionDigits: 0 });
const compact = (v: number) => v.toLocaleString("pt-BR", { notation: "compact", maximumFractionDigits: 1 });

export function MonthlyChart({ data }: { data: { label: string; receitas: number; despesas: number; resultado: number }[] }) {
  return (
    <ResponsiveContainer width="100%" height={260}>
      <ComposedChart data={data} margin={{ top: 8, right: 8, left: 0, bottom: 0 }}>
        <CartesianGrid vertical={false} stroke="#e7e5e4" />
        <XAxis dataKey="label" tickLine={false} axisLine={false} fontSize={12} />
        <YAxis tickFormatter={compact} tickLine={false} axisLine={false} fontSize={12} width={48} />
        <Tooltip formatter={(v) => brl(Number(v))} contentStyle={{ borderRadius: 8, fontSize: 12 }} />
        <Legend iconType="circle" wrapperStyle={{ fontSize: 12 }} />
        <Bar dataKey="receitas" name="Receitas" fill="#15803d" radius={[4, 4, 0, 0]} maxBarSize={28} />
        <Bar dataKey="despesas" name="Despesas" fill="#c2410c" radius={[4, 4, 0, 0]} maxBarSize={28} />
        <Line dataKey="resultado" name="Resultado" stroke="#1c1917" strokeWidth={2} dot={{ r: 3 }} />
      </ComposedChart>
    </ResponsiveContainer>
  );
}

export function CategoryChart({ data }: { data: { name: string; value: number; color: string }[] }) {
  if (!data.length) return <p className="py-16 text-center text-sm text-stone-500">Sem despesas no mês.</p>;
  const total = data.reduce((s, d) => s + d.value, 0);
  return (
    <div className="flex flex-col items-center gap-4">
      <div className="h-48 w-48 shrink-0">
        <ResponsiveContainer>
          <PieChart>
            <Pie data={data} dataKey="value" nameKey="name" innerRadius={52} outerRadius={88} paddingAngle={1} stroke="#fff">
              {data.map((d) => <Cell key={d.name} fill={d.color} />)}
            </Pie>
            <Tooltip formatter={(v) => brl(Number(v))} contentStyle={{ borderRadius: 8, fontSize: 12 }} />
          </PieChart>
        </ResponsiveContainer>
      </div>
      <ul className="w-full space-y-1.5 text-sm">
        {data.slice(0, 8).map((d) => (
          <li key={d.name} className="flex items-center gap-2">
            <span className="h-2.5 w-2.5 shrink-0 rounded-full" style={{ background: d.color }} />
            <span className="flex-1 truncate">{d.name}</span>
            <span className="text-stone-500 tabular">{Math.round((d.value / total) * 100)}%</span>
            <span className="text-right font-medium tabular">{brl(d.value)}</span>
          </li>
        ))}
      </ul>
    </div>
  );
}

