import { Suspense } from "react";
import { getDashboardStats } from "@/lib/dashboard-queries";
import { FollowUpWidget } from "@/components/admin/dashboard/FollowUpWidget";
import { MessagesWidget } from "@/components/admin/dashboard/MessagesWidget";
import {
  getAnalyticsByYear,
  getTotalTrackedHours,
  getClientProfitability,
} from "@/lib/analytics-queries";
import { getRevenueForecast12Months, getOffersSoldBreakdown } from "@/lib/forecast-queries";
import { YearSelector } from "@/components/admin/YearSelector";
import { ForecastChart } from "@/components/admin/ForecastChart";
import { OffersSoldChart } from "@/components/admin/OffersSoldChart";
import { ClientProfitability } from "@/components/admin/dashboard/ClientProfitability";

export const revalidate = 0;

function MetricCard({
  label,
  value,
  valueAccent,
  delta,
  sub,
}: {
  label: string;
  value: string;
  valueAccent?: boolean;
  delta?: string;
  sub?: string;
}) {
  return (
    <div className="bg-card p-5 rounded-xl border border-border-light shadow-card">
      <span className="text-[10px] uppercase font-bold text-muted-foreground tracking-wider">
        {label}
      </span>
      <div className="flex items-baseline gap-2 mt-1">
        <span
          className={`text-2xl font-bold font-mono ${
            valueAccent ? "text-emerald-700 dark:text-emerald-400" : "text-foreground"
          }`}
        >
          {value}
        </span>
        {delta ? (
          <span className="text-xs font-medium text-emerald-600 dark:text-emerald-400">{delta}</span>
        ) : sub ? (
          <span className="text-xs text-muted-foreground">{sub}</span>
        ) : null}
      </div>
    </div>
  );
}

function fmtEur0(n: number) {
  return n.toLocaleString("it-IT", {
    style: "currency",
    currency: "EUR",
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
  });
}

export default async function AdminDashboard({
  searchParams,
}: {
  searchParams: Promise<{ year?: string }>;
}) {
  const { year: yearParam } = await searchParams;
  const year = parseInt(yearParam ?? "") || new Date().getFullYear();

  const { kpi } = await getDashboardStats();

  const [data, totalHours, profitability, forecast, offersSold] = await Promise.all([
    getAnalyticsByYear(year),
    getTotalTrackedHours(year),
    getClientProfitability(year),
    getRevenueForecast12Months(),
    getOffersSoldBreakdown(),
  ]);

  const collectedPct =
    data.contracted > 0 ? Math.round((data.collected / data.contracted) * 100) : 0;

  return (
    <div className="flex flex-col gap-8">
      {/* KPI strip */}
      <section className="grid grid-cols-2 lg:grid-cols-4 gap-6">
        <MetricCard
          label="Clienti Attivi"
          value={String(kpi.clientiAttivi)}
          delta={kpi.clientiNuoviMese > 0 ? `+${kpi.clientiNuoviMese} questo mese` : undefined}
          sub="Totale corrente"
        />
        <MetricCard
          label="Contrattualizzato"
          value={fmtEur0(data.contracted)}
          sub={`Totale anno ${year}`}
        />
        <MetricCard
          label="Incassato Reale"
          value={fmtEur0(data.collected)}
          valueAccent={data.collected > 0}
          sub={`${collectedPct}% del totale`}
        />
        <MetricCard label="Ore Tracciate" value={`${totalHours}h`} sub="Su progetti attivi" />
      </section>

      {/* Griglia contenuti: 2/3 + 1/3 */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        {/* Colonna 2/3 */}
        <div className="lg:col-span-2 flex flex-col gap-8">
          <ForecastChart data={forecast} headerAction={<YearSelector currentYear={year} />} />
          <ClientProfitability data={profitability} />
        </div>

        {/* Colonna 1/3 */}
        <div className="lg:col-span-1 flex flex-col gap-8">
          <Suspense
            fallback={<div className="animate-pulse h-40 bg-muted rounded-xl" />}
          >
            <FollowUpWidget />
          </Suspense>
          <Suspense
            fallback={<div className="animate-pulse h-40 bg-muted rounded-xl" />}
          >
            <MessagesWidget />
          </Suspense>
          <OffersSoldChart data={offersSold} />
        </div>
      </div>
    </div>
  );
}
