import { getSession } from "@/lib/auth/session";
import { logActivity } from "@/lib/db/audit";
import {
  getDashboardStats,
  topActiveTenants,
} from "@/lib/db/queries/dashboard";
import {
  interventionsPerDay30j,
  rapportsPerDay30j,
  facturesPerDay30j,
  apiCallsPerHour24h,
  interventionsPerMonth12m,
  rapportsPerMonth12m,
  facturesPerMonth12m,
} from "@/lib/db/queries/charts";
import { Card, CardBody, CardHeader, CardTitle } from "@/components/ui/card";
import { KpiCard } from "@/components/ui/kpi-card";
import { DonutChart } from "@/components/ui/charts/donut-chart";
import { BarChart } from "@/components/ui/charts/bar-chart";

export const dynamic = "force-dynamic";

const numFmt = new Intl.NumberFormat("fr-FR");
const monthFmt = new Intl.DateTimeFormat("fr-FR", {
  month: "short",
  year: "2-digit",
});
function shortMonth(yyyyMm: string): string {
  return monthFmt.format(new Date(`${yyyyMm}-01T00:00:00`));
}

export default async function DashboardPage() {
  const session = await getSession();
  const user = session!.user;
  const firstName = user.name.split(/\s+/)[0] || user.email;
  const today = new Date().toLocaleDateString("fr-FR", {
    weekday: "long",
    day: "numeric",
    month: "long",
  });

  void logActivity({
    type: "superadmin.dashboard_view",
    title: "Vue tableau de bord cross-tenant",
    user_id: user.id,
  });

  let stats: Awaited<ReturnType<typeof getDashboardStats>> | null = null;
  let topTenants: Awaited<ReturnType<typeof topActiveTenants>> = [];
  let interventionsDaily: Awaited<
    ReturnType<typeof interventionsPerDay30j>
  > = [];
  let rapportsDaily: Awaited<ReturnType<typeof rapportsPerDay30j>> = [];
  let facturesDaily: Awaited<ReturnType<typeof facturesPerDay30j>> = [];
  let apiHourly: Awaited<ReturnType<typeof apiCallsPerHour24h>> = [];
  let interventionsMonthly: Awaited<
    ReturnType<typeof interventionsPerMonth12m>
  > = [];
  let rapportsMonthly: Awaited<ReturnType<typeof rapportsPerMonth12m>> = [];
  let facturesMonthly: Awaited<ReturnType<typeof facturesPerMonth12m>> = [];
  let loadError: string | null = null;

  try {
    [
      stats,
      topTenants,
      interventionsDaily,
      rapportsDaily,
      facturesDaily,
      apiHourly,
      interventionsMonthly,
      rapportsMonthly,
      facturesMonthly,
    ] = await Promise.all([
      getDashboardStats(),
      topActiveTenants(),
      interventionsPerDay30j(),
      rapportsPerDay30j(),
      facturesPerDay30j(),
      apiCallsPerHour24h(),
      interventionsPerMonth12m(),
      rapportsPerMonth12m(),
      facturesPerMonth12m(),
    ]);
  } catch (err) {
    loadError = err instanceof Error ? err.message : "Erreur inconnue";
  }

  return (
    <div className="px-8 pt-10 lg:px-12 lg:pt-14">
      <header className="flex flex-col gap-1.5 mf-fade-in">
        <p className="text-xs uppercase tracking-[0.18em] text-muted-foreground">
          {today}
        </p>
        <h1 className="text-3xl font-semibold tracking-tight text-foreground">
          Bonjour {firstName} <span aria-hidden="true">👋</span>
        </h1>
        <p className="text-sm text-muted-foreground">
          Vue d&apos;ensemble du SaaS missioflow.
        </p>
      </header>

      {loadError && (
        <div className="mt-6 rounded-md border border-red-200 bg-danger-subtle px-4 py-3 text-sm text-danger">
          Impossible de charger les statistiques : {loadError}
        </div>
      )}

      {!loadError && stats && (
        <>
          {/* KPI principaux avec sparklines */}
          <section className="mt-8 grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
            <KpiCard
              label="Tenants"
              value={numFmt.format(stats.tenants_total)}
              hint={`${stats.tenants_active} actifs · ${stats.tenants_trial} en essai`}
              tone="accent"
            />
            <KpiCard
              label="Interventions 30j"
              value={numFmt.format(stats.interventions_30j)}
              hint={`${numFmt.format(stats.interventions_total)} au total`}
              spark={interventionsDaily.map((d) => d.count)}
              tone="success"
            />
            <KpiCard
              label="API calls 24h"
              value={numFmt.format(stats.api_calls_24h)}
              hint={
                stats.api_errors_24h > 0
                  ? `${stats.api_errors_24h} erreurs détectées`
                  : "Aucune erreur"
              }
              spark={apiHourly.map((h) => h.total)}
              tone={stats.api_errors_24h > 0 ? "warning" : "success"}
            />
            <KpiCard
              label="Techniciens"
              value={numFmt.format(stats.techniciens_actifs)}
              hint={`${stats.techniciens_total} au total · ${stats.superadmins} super-admins`}
              tone="neutral"
            />
          </section>

          {/* Donut tenants + top 5 actifs */}
          <section className="mt-6 grid gap-4 lg:grid-cols-2">
            <Card>
              <CardHeader>
                <CardTitle>Répartition des tenants</CardTitle>
              </CardHeader>
              <CardBody>
                <DonutChart
                  segments={[
                    {
                      label: "Actifs",
                      value: stats.tenants_active,
                      color: "var(--success)",
                    },
                    {
                      label: "En essai",
                      value: stats.tenants_trial,
                      color: "var(--warning)",
                    },
                    {
                      label: "Suspendus",
                      value: stats.tenants_suspended,
                      color: "var(--danger)",
                    },
                  ]}
                  centerValue={numFmt.format(stats.tenants_total)}
                  centerLabel="Total"
                />
              </CardBody>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>Top tenants — interventions 30j</CardTitle>
              </CardHeader>
              <CardBody>
                {topTenants.length === 0 ? (
                  <p className="text-sm text-muted-foreground">
                    Aucune intervention sur les 30 derniers jours.
                  </p>
                ) : (
                  <BarChart
                    orientation="horizontal"
                    data={topTenants.map((t) => ({
                      label: t.name,
                      values: [t.intervention_count_30j],
                    }))}
                    series={[{ name: "Interventions" }]}
                    showValues
                    legend={false}
                    formatValue={(v) => numFmt.format(v)}
                  />
                )}
              </CardBody>
            </Card>
          </section>

          {/* Bloc volume métier */}
          <section className="mt-6 grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
            <KpiCard
              label="Sites"
              value={numFmt.format(stats.sites)}
              tone="neutral"
            />
            <KpiCard
              label="Machines"
              value={numFmt.format(stats.machines)}
              tone="neutral"
            />
            <KpiCard
              label="Rapports 30j"
              value={numFmt.format(stats.rapports_30j)}
              spark={rapportsDaily.map((d) => d.count)}
              tone="accent"
            />
            <KpiCard
              label="Factures 30j"
              value={numFmt.format(stats.factures_30j)}
              spark={facturesDaily.map((d) => d.count)}
              tone="accent"
            />
          </section>

          {/* A2 + rapports/factures mensuels — volume métier 12 mois */}
          <section className="mt-6">
            <Card>
              <CardHeader>
                <CardTitle>Volume métier — 12 mois</CardTitle>
              </CardHeader>
              <CardBody>
                <BarChart
                  mode="grouped"
                  height={200}
                  data={interventionsMonthly.map((m, i) => ({
                    label: shortMonth(m.month),
                    values: [
                      m.count,
                      rapportsMonthly[i]?.count ?? 0,
                      facturesMonthly[i]?.count ?? 0,
                    ],
                  }))}
                  series={[
                    { name: "Interventions", color: "var(--accent)" },
                    { name: "Rapports", color: "var(--success)" },
                    { name: "Factures", color: "var(--warning)" },
                  ]}
                  formatValue={(v) => numFmt.format(v)}
                />
              </CardBody>
            </Card>
          </section>
        </>
      )}
    </div>
  );
}
