import { Trash2 } from "lucide-react";
import { createClient } from "@/lib/supabase/server";
import { getLookups } from "@/lib/data";
import { currentMonth, dateBR, isMonth, money, monthRange } from "@/lib/format";
import { PageHeader } from "@/components/PageHeader";
import { MonthNav } from "@/components/MonthNav";
import { Progress } from "@/components/Progress";
import { ConfirmButton } from "@/components/ConfirmButton";
import { contributeGoal, deleteGoal, saveBudget, saveGoal } from "../actions";

type Goal = { id: string; name: string; target_amount: number; current_amount: number; deadline: string | null };

export default async function Orcamento({ params, searchParams }: { params: Promise<{ ws: string }>; searchParams: Promise<{ mes?: string }> }) {
  const { ws } = await params;
  const { mes } = await searchParams;
  const month = isMonth(mes) ? mes : currentMonth();
  const { start, end } = monthRange(month);

  const supabase = await createClient();
  const [lookups, budRes, txRes, goalRes] = await Promise.all([
    getLookups(ws),
    supabase.from("budgets").select("category_id,amount").eq("workspace_id", ws),
    supabase.from("transactions").select("category_id,amount").eq("workspace_id", ws).eq("type", "despesa").gte("date", start).lte("date", end),
    supabase.from("goals").select("*").eq("workspace_id", ws).order("created_at"),
  ]);

  const limits = new Map((budRes.data ?? []).map((b) => [b.category_id as string, Number(b.amount)]));
  const spent = new Map<string, number>();
  (txRes.data ?? []).forEach((t) => spent.set(t.category_id ?? "", (spent.get(t.category_id ?? "") ?? 0) + Number(t.amount)));
  const cats = lookups.categories.filter((c) => c.type === "despesa");
  const totalLimit = [...limits.values()].reduce((a, b) => a + b, 0);
  const totalSpentBudgeted = cats.filter((c) => limits.has(c.id)).reduce((s, c) => s + (spent.get(c.id) ?? 0), 0);
  const goals = (goalRes.data ?? []) as Goal[];

  return (
    <>
      <PageHeader title="Orçamento e metas" subtitle="Limites mensais por categoria e objetivos de economia">
        <MonthNav month={month} basePath={`/w/${ws}/orcamento`} />
      </PageHeader>

      <div className="mb-8 grid gap-4 lg:grid-cols-3">
        <div className="card lg:col-span-2 p-0">
          <div className="flex items-center justify-between border-b border-stone-200 px-5 py-4">
            <span className="font-semibold">Orçamento mensal</span>
            {totalLimit > 0 && (
              <span className="text-sm text-stone-500">
                <span className="font-medium text-stone-800 tabular">{money(totalSpentBudgeted)}</span> de {money(totalLimit)}
              </span>
            )}
          </div>
          <table className="table">
            <thead><tr><th>Categoria</th><th className="w-2/5">Gasto no mês</th><th className="w-44">Limite mensal</th></tr></thead>
            <tbody>
              {cats.map((c) => {
                const lim = limits.get(c.id);
                const s = spent.get(c.id) ?? 0;
                return (
                  <tr key={c.id}>
                    <td><span className="inline-flex items-center gap-2"><span className="h-2 w-2 rounded-full" style={{ background: c.color }} />{c.name}</span></td>
                    <td>
                      <div className="mb-1 flex justify-between text-xs">
                        <span className={`tabular ${lim && s > lim ? "font-medium text-red-600" : "text-stone-600"}`}>{money(s)}</span>
                        {lim ? <span className="text-stone-400 tabular">{Math.round((s / lim) * 100)}%</span> : null}
                      </div>
                      {lim ? <Progress value={s} max={lim} /> : <div className="h-2" />}
                    </td>
                    <td>
                      <form action={saveBudget} className="flex gap-1">
                        <input type="hidden" name="ws" value={ws} />
                        <input type="hidden" name="category_id" value={c.id} />
                        <input className="input py-1 tabular" name="amount" inputMode="decimal" defaultValue={lim ?? ""} placeholder="sem limite" />
                        <button className="btn btn-sm">OK</button>
                      </form>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
          <p className="px-5 py-3 text-xs text-stone-500">Deixe em branco para remover o limite. Considera despesas pagas e pendentes do mês.</p>
        </div>

        <form action={saveGoal} className="card h-fit space-y-3">
          <input type="hidden" name="ws" value={ws} />
          <div className="font-semibold">Nova meta</div>
          <div><label className="label">Nome</label><input className="input" name="name" required placeholder="Reserva de emergência" /></div>
          <div className="grid grid-cols-2 gap-2">
            <div><label className="label">Valor alvo</label><input className="input" name="target_amount" inputMode="decimal" required /></div>
            <div><label className="label">Já guardado</label><input className="input" name="current_amount" inputMode="decimal" defaultValue="0" /></div>
          </div>
          <div><label className="label">Prazo</label><input className="input" type="date" name="deadline" /></div>
          <button className="btn-primary w-full">Criar meta</button>
        </form>
      </div>

      <h2 className="mb-3 font-semibold">Metas</h2>
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
        {goals.map((g) => {
          const pct = Math.round((Number(g.current_amount) / Number(g.target_amount)) * 100);
          return (
            <div key={g.id} className="card space-y-3">
              <div className="flex items-start justify-between">
                <div>
                  <div className="font-medium">{g.name}</div>
                  {g.deadline && <div className="text-xs text-stone-500">até {dateBR(g.deadline)}</div>}
                </div>
                <form action={deleteGoal}>
                  <input type="hidden" name="ws" value={ws} /><input type="hidden" name="id" value={g.id} />
                  <ConfirmButton message="Excluir esta meta?" className="btn-ghost hover:text-red-600"><Trash2 size={14} /></ConfirmButton>
                </form>
              </div>
              <div>
                <div className="mb-1 flex justify-between text-sm">
                  <span className="font-semibold tabular">{money(g.current_amount)}</span>
                  <span className="text-stone-500 tabular">{pct}% de {money(g.target_amount)}</span>
                </div>
                <Progress value={Number(g.current_amount)} max={Number(g.target_amount)} danger={false} />
              </div>
              <form action={contributeGoal} className="flex gap-2">
                <input type="hidden" name="ws" value={ws} /><input type="hidden" name="id" value={g.id} />
                <input className="input py-1" name="value" inputMode="decimal" placeholder="Aportar (ou -valor)" required />
                <button className="btn btn-sm">Somar</button>
              </form>
            </div>
          );
        })}
        {!goals.length && <p className="text-sm text-stone-500">Nenhuma meta ainda.</p>}
      </div>
    </>
  );
}
