import { Badge } from "@/components/ui/badge";
import { Card, CardBody, CardHeader, CardTitle } from "@/components/ui/card";
import { DonutChart } from "@/components/ui/charts/donut-chart";
import { BarChart } from "@/components/ui/charts/bar-chart";
import { listTechniciens } from "@/lib/db/queries/techniciens";
import {
  techniciensActifsRatio,
  techniciensCreatedPerMonth12m,
} from "@/lib/db/queries/charts";
import { logActivity } from "@/lib/db/audit";
import { getSession } from "@/lib/auth/session";

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 const dynamic = "force-dynamic";

const dateFmt = new Intl.DateTimeFormat("fr-FR", {
  day: "2-digit",
  month: "short",
  year: "numeric",
});

export default async function TechniciensPage() {
  const session = await getSession();
  let rows: Awaited<ReturnType<typeof listTechniciens>> = [];
  let actifsSplit: Awaited<ReturnType<typeof techniciensActifsRatio>> = [];
  let createdMonthly: Awaited<
    ReturnType<typeof techniciensCreatedPerMonth12m>
  > = [];
  let loadError: string | null = null;
  try {
    [rows, actifsSplit, createdMonthly] = await Promise.all([
      listTechniciens(),
      techniciensActifsRatio(),
      techniciensCreatedPerMonth12m(),
    ]);
    void logActivity({
      type: "superadmin.techniciens_list",
      title: "Lecture du listing techniciens cross-tenant",
      description: `${rows.length} techniciens lus`,
      user_id: session?.user.id,
    });
  } catch (err) {
    loadError = err instanceof Error ? err.message : "Erreur inconnue";
  }

  const superadmins = rows.filter((r) => r.is_superadmin === 1);
  const standard = rows.filter((r) => r.is_superadmin !== 1);
  const actifsCount =
    actifsSplit.find((r) => Number(r.actif) === 1)?.count ?? 0;
  const inactifsCount =
    actifsSplit.find((r) => Number(r.actif) === 0)?.count ?? 0;

  return (
    <div className="px-6 py-6 lg:px-10">
      <header className="mb-6 flex flex-wrap items-baseline justify-between gap-3">
        <div>
          <h1 className="text-2xl font-semibold">Techniciens</h1>
          <p className="text-sm text-muted-foreground">
            Vue cross-tenant des utilisateurs terrain et des super-administrateurs.
          </p>
        </div>
        {!loadError && (
          <span className="text-xs text-muted-foreground tabular-nums">
            {superadmins.length} super-admin · {standard.length} terrain
          </span>
        )}
      </header>

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

      {!loadError && rows.length > 0 && (
        <section className="mb-6 grid gap-4 lg:grid-cols-3">
          <Card>
            <CardHeader>
              <CardTitle>Actifs vs inactifs</CardTitle>
            </CardHeader>
            <CardBody>
              <DonutChart
                segments={[
                  { label: "Actifs", value: actifsCount, color: "var(--success)" },
                  { label: "Inactifs", value: inactifsCount, color: "var(--muted-foreground)" },
                ]}
                centerValue={numFmt.format(actifsCount + inactifsCount)}
                centerLabel="Terrain"
              />
            </CardBody>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Super-administrateurs</CardTitle>
            </CardHeader>
            <CardBody>
              <div className="flex items-baseline gap-3">
                <span className="text-4xl font-semibold tabular-nums text-accent">
                  {numFmt.format(superadmins.length)}
                </span>
                <span className="text-sm text-muted-foreground">comptes</span>
              </div>
              <p className="mt-3 text-xs text-muted-foreground">
                Accès cross-tenant. Toute création/révocation passe par missioflow-app.
              </p>
            </CardBody>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Nouveaux techniciens (12 mois)</CardTitle>
            </CardHeader>
            <CardBody>
              <BarChart
                data={createdMonthly.map((m) => ({
                  label: shortMonth(m.month),
                  values: [m.count],
                }))}
                series={[{ name: "Créations", color: "var(--accent)" }]}
                height={160}
                legend={false}
                formatValue={(v) => numFmt.format(v)}
              />
            </CardBody>
          </Card>
        </section>
      )}

      {!loadError && superadmins.length > 0 && (
        <section className="mb-6">
          <h2 className="mb-2 text-sm font-medium uppercase tracking-wider text-muted-foreground">
            Super-administrateurs ({superadmins.length})
          </h2>
          <div className="overflow-hidden rounded-lg border border-accent-ring/60 bg-accent-subtle/40">
            <table className="w-full text-sm">
              <thead className="text-left text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
                <tr>
                  <th className="px-4 py-2">Nom</th>
                  <th className="px-4 py-2">Email</th>
                  <th className="px-4 py-2">Rôle</th>
                  <th className="px-4 py-2">Statut</th>
                  <th className="px-4 py-2">Créé le</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-accent-ring/40">
                {superadmins.map((t) => (
                  <tr key={t.id}>
                    <td className="px-4 py-2 font-medium">
                      {t.prenom} {t.nom}
                    </td>
                    <td className="px-4 py-2 text-xs text-muted-foreground">
                      {t.email ?? "—"}
                    </td>
                    <td className="px-4 py-2 text-xs">{t.role ?? "—"}</td>
                    <td className="px-4 py-2">
                      <Badge tone={t.actif ? "success" : "neutral"}>
                        {t.actif ? "Actif" : "Inactif"}
                      </Badge>
                    </td>
                    <td className="px-4 py-2 text-xs text-muted-foreground tabular-nums">
                      {dateFmt.format(new Date(t.created_at))}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </section>
      )}

      {!loadError && standard.length === 0 && superadmins.length === 0 && (
        <div className="rounded-md border border-border bg-surface px-4 py-8 text-center text-sm text-muted-foreground">
          Aucun technicien en base.
        </div>
      )}

      {!loadError && standard.length > 0 && (
        <section>
          <h2 className="mb-2 text-sm font-medium uppercase tracking-wider text-muted-foreground">
            Terrain ({standard.length})
          </h2>
          <div className="overflow-hidden rounded-lg border border-border bg-surface">
            <table className="w-full text-sm">
              <thead className="bg-surface-2 text-left text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
                <tr>
                  <th className="px-4 py-2.5">Tenant</th>
                  <th className="px-4 py-2.5">Nom</th>
                  <th className="px-4 py-2.5">Email</th>
                  <th className="px-4 py-2.5">Rôle</th>
                  <th className="px-4 py-2.5">Statut</th>
                  <th className="px-4 py-2.5">Embauche</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-border">
                {standard.map((t) => (
                  <tr
                    key={t.id}
                    className="text-foreground hover:bg-surface-2/60"
                  >
                    <td className="px-4 py-2.5">
                      <div className="font-medium">{t.tenant_name ?? "—"}</div>
                      {t.tenant_slug && (
                        <div className="font-mono text-[10px] text-muted-foreground">
                          {t.tenant_slug}
                        </div>
                      )}
                    </td>
                    <td className="px-4 py-2.5 font-medium">
                      {t.prenom} {t.nom}
                    </td>
                    <td className="px-4 py-2.5 text-xs text-muted-foreground">
                      {t.email ?? "—"}
                    </td>
                    <td className="px-4 py-2.5 text-xs">{t.role ?? "—"}</td>
                    <td className="px-4 py-2.5">
                      <Badge tone={t.actif ? "success" : "neutral"}>
                        {t.actif ? "Actif" : "Inactif"}
                      </Badge>
                    </td>
                    <td className="px-4 py-2.5 text-xs text-muted-foreground tabular-nums">
                      {t.date_embauche
                        ? dateFmt.format(new Date(t.date_embauche))
                        : "—"}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </section>
      )}
    </div>
  );
}
