import { auth } from "@/auth";
import { redirect, notFound } from "next/navigation";
import Link from "next/link";
import type { Metadata } from "next";
import { hasPermission } from "@/lib/permissions";
import { formatCurrency, formatCompactINR } from "@/lib/utils";
import {
  getReportDataset,
  buildAccountIndex,
  costCentreRows,
  costCentreWeekly,
  topAccountsForCostCentre,
  parseGranularity,
  resolveFy,
  resolveMonth,
  fyLabel,
  FY_MONTHS,
  WEEK_LABELS,
  type Tier,
} from "@/lib/reports";
import { ReportsToolbar } from "@/components/reports/reports-toolbar";
import { TrendChart, BreakdownChart } from "@/components/reports/charts";
import { SERIES_COLORS } from "@/lib/report-colors";
import { Kpi, KpiStrip } from "@/components/reports/kpi";
import { ReportBreadcrumb, ReportTitle, SegLink } from "@/components/reports/report-header";

export const metadata: Metadata = { title: "Cost Centre — Reports" };

const sum = (a: number[]) => a.reduce((x, y) => x + y, 0);
const TIERS: Tier[] = ["Heading", "Sub-heading", "Leaf"];

export default async function CostCentreDetail({
  params,
  searchParams,
}: {
  params: Promise<{ id: string }>;
  searchParams: Promise<{ fy?: string; gran?: string; month?: string; tier?: string; topn?: string }>;
}) {
  const session = await auth();
  if (!session?.user) return null;
  if (!hasPermission(session.user.role, "view_analytics")) redirect("/dashboard");

  const { id } = await params;
  const sp = await searchParams;
  const ds = await getReportDataset();
  const idx = buildAccountIndex(ds.accounts);
  const gran = parseGranularity(sp.gran);
  const fy = resolveFy(ds, sp.fy);
  const yearly = gran === "yearly";
  const weekly = gran === "weekly";
  const month = resolveMonth(ds, fy, sp.month);
  const unit = yearly ? "year" : weekly ? "week" : "month";
  const tier: Tier = TIERS.includes(sp.tier as Tier) ? (sp.tier as Tier) : "Leaf";
  const topn = sp.topn === "10" ? 10 : sp.topn === "all" ? 9999 : 5;

  const row = costCentreRows(ds, fy).find((r) => r.id === id);
  if (!row) notFound();

  const monthLabel = (i: number) => `${FY_MONTHS[i]} '${String((fy + (i >= 9 ? 1 : 0)) % 100).padStart(2, "0")}`;
  const series = yearly
    ? ds.fys.map((y, i) => ({ label: fyLabel(y), value: row.fyTotals[i] }))
    : weekly
      ? WEEK_LABELS.map((w, i) => ({ label: w, value: costCentreWeekly(ds, id, fy, month)[i] }))
      : FY_MONTHS.map((m, i) => ({ label: m, value: row.months[i] }));
  const total = sum(series.map((s) => s.value));
  const avg = series.length ? total / series.length : 0;
  const peak = series.reduce((best, s) => (s.value > best.value ? s : best), series[0] ?? { label: "—", value: 0 });
  const nf = ds.fys.length;
  const yoy = nf >= 2 && row.fyTotals[nf - 2] ? ((row.fyTotals[nf - 1] - row.fyTotals[nf - 2]) / row.fyTotals[nf - 2]) * 100 : 0;

  const breakdown = topAccountsForCostCentre(ds, idx, id, fy, tier).slice(0, topn);
  const breakTotal = sum(breakdown.map((b) => b.value)) || 1;

  const periodLabel = yearly ? `${ds.fys.length} FYs` : weekly ? `${monthLabel(month)} · ${fyLabel(fy)}` : fyLabel(fy);
  const base = `/reports/cost-centres/${id}`;
  const q = (extra: Record<string, string>) => {
    const p = new URLSearchParams({ fy: String(fy), gran });
    if (weekly) p.set("month", String(month));
    for (const [k, v] of Object.entries(extra)) p.set(k, v);
    return `${base}?${p.toString()}`;
  };
  const exportHref = `/api/reports/spend?dim=cost-centre-detail&id=${id}&fy=${fy}&gran=${gran}&tier=${tier}`;

  return (
    <div>
      <ReportBreadcrumb trail={[{ label: "Cost Centres", href: `/reports/cost-centres?fy=${fy}&gran=${gran}` }, { label: row.name }]} />
      <ReportsToolbar
        fys={ds.fys}
        fy={fy}
        gran={gran}
        month={month}
        monthOptions={FY_MONTHS.map((_, i) => ({ value: i, label: monthLabel(i) }))}
        exportHref={exportHref}
      />

      <Link href={`/reports/cost-centres?fy=${fy}&gran=${gran}`} className="mb-4 inline-flex items-center gap-1.5 text-sm font-medium text-primary-600 hover:text-primary-700">
        ← Back to Cost Centres
      </Link>

      <ReportTitle title={row.name} subtitle={`Approved spend · ${periodLabel}`} />

      <KpiStrip>
        <Kpi label="Total spend" value={formatCompactINR(total)} sub={periodLabel} />
        <Kpi label={`Avg / ${unit}`} value={formatCompactINR(avg)} />
        <Kpi label={`Peak ${unit}`} value={peak.label} sub={formatCompactINR(peak.value)} />
        <Kpi label="YoY change" value={`${yoy >= 0 ? "+" : ""}${yoy.toFixed(1)}%`} sub="vs prior FY" delta={yoy} />
      </KpiStrip>

      <div className="mb-6 rounded-lg border border-neutral-200 bg-white p-5">
        <p className="mb-4 text-sm font-semibold text-neutral-900">Spend trend</p>
        <TrendChart kind={yearly ? "bar" : "line"} data={series} />
      </div>

      <div className="rounded-lg border border-neutral-200 bg-white p-5">
        <div className="mb-4 flex flex-wrap items-center justify-between gap-3">
          <p className="text-sm font-semibold text-neutral-900">Top accounting codes</p>
          <div className="flex flex-wrap items-center gap-3">
            <SegLink label="Tier" options={TIERS.map((t) => ({ value: t, label: t }))} current={tier} hrefFor={(v) => q({ tier: v, topn: sp.topn ?? "5" })} />
            <SegLink
              label="Top"
              options={[{ value: "5", label: "5" }, { value: "10", label: "10" }, { value: "all", label: "All" }]}
              current={sp.topn === "10" ? "10" : sp.topn === "all" ? "all" : "5"}
              hrefFor={(v) => q({ tier, topn: v })}
            />
          </div>
        </div>
        {breakdown.length === 0 ? (
          <p className="py-8 text-center text-sm text-neutral-400">No spend at this tier for {periodLabel}.</p>
        ) : (
          <div className="grid grid-cols-1 gap-6 lg:grid-cols-5">
            <div className="lg:col-span-3">
              <BreakdownChart data={breakdown} />
            </div>
            <div className="lg:col-span-2">
              <table className="w-full text-sm">
                <thead className="border-b border-neutral-200 text-left text-xs font-semibold uppercase tracking-wider text-neutral-400">
                  <tr>
                    <th className="py-2">{tier}</th>
                    <th className="py-2 text-right">Spend</th>
                    <th className="py-2 text-right">%</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-neutral-100">
                  {breakdown.map((b, i) => (
                    <tr key={b.id}>
                      <td className="py-2">
                        <span className="mr-2 inline-block h-2.5 w-2.5 rounded-sm align-middle" style={{ background: SERIES_COLORS[i % SERIES_COLORS.length] }} />
                        {b.label}
                      </td>
                      <td className="py-2 text-right font-medium tabular-nums">{formatCurrency(b.value)}</td>
                      <td className="py-2 text-right tabular-nums text-neutral-500">{((b.value / breakTotal) * 100).toFixed(0)}%</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
