"use client";

import { useState } from "react";
import type { TenantRow, TenantStatus } from "@/lib/db/queries/tenants";
import { Badge } from "@/components/ui/badge";
import { TenantDetailModal } from "./tenant-detail-modal";

const STATUS_TONE: Record<TenantStatus, "warning" | "success" | "danger" | "neutral"> = {
  trial: "warning",
  active: "success",
  suspended: "danger",
  canceled: "neutral",
};

const STATUS_LABEL: Record<TenantStatus, string> = {
  trial: "Essai",
  active: "Actif",
  suspended: "Suspendu",
  // « Annulé » et non « Résilié » : depuis le Lot 2 du mur de facturation (mf_ask #150),
  // un tenant canceled n'est plus terminal — l'admin peut se réactiver en self-service.
  canceled: "Annulé",
};

const PLAN_LABEL: Record<string, string> = {
  starter: "Starter",
  pro: "Pro",
  enterprise: "Enterprise",
  // Plan per-seat — seul plan vendable depuis le Lot 4 pricing (mf_ask #134).
  flex: "Flex",
};

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

const priceFmt = new Intl.NumberFormat("fr-FR", {
  style: "currency",
  currency: "EUR",
  maximumFractionDigits: 0,
});

export function TenantsTable({ rows }: { rows: TenantRow[] }) {
  const [openId, setOpenId] = useState<number | null>(null);

  return (
    <>
      <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">Nom</th>
              <th className="px-4 py-2.5">Slug</th>
              <th className="px-4 py-2.5">Statut</th>
              <th className="px-4 py-2.5">Plan</th>
              <th className="px-4 py-2.5 text-right">Tech.</th>
              <th className="px-4 py-2.5 text-right">Sites</th>
              <th className="px-4 py-2.5 text-right">Machines</th>
              <th className="px-4 py-2.5">Créé le</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-border">
            {rows.map((t) => (
              <tr
                key={t.id}
                onClick={() => setOpenId(t.id)}
                className="cursor-pointer text-foreground transition-colors hover:bg-accent-subtle/40"
                title="Cliquez pour ouvrir le détail abonnement"
              >
                <td className="px-4 py-2.5">
                  <div className="font-medium">{t.name}</div>
                  {t.admin_email && (
                    <div className="text-xs text-muted-foreground">
                      {t.admin_email}
                    </div>
                  )}
                </td>
                <td className="px-4 py-2.5 font-mono text-xs text-muted-foreground">
                  {t.slug}
                </td>
                <td className="px-4 py-2.5">
                  <Badge tone={STATUS_TONE[t.status]}>
                    {STATUS_LABEL[t.status]}
                  </Badge>
                </td>
                <td className="px-4 py-2.5">
                  <div className="font-medium">
                    {t.plan_name ?? PLAN_LABEL[t.plan_code] ?? t.plan_code}
                  </div>
                  {t.plan_monthly_price && (
                    <div className="text-xs text-muted-foreground tabular-nums">
                      {priceFmt.format(Number(t.plan_monthly_price))}/mois
                    </div>
                  )}
                </td>
                <td className="px-4 py-2.5 text-right tabular-nums">
                  {t.tech_count}
                </td>
                <td className="px-4 py-2.5 text-right tabular-nums">
                  {t.site_count}
                </td>
                <td className="px-4 py-2.5 text-right tabular-nums">
                  {t.machine_count}
                </td>
                <td className="px-4 py-2.5 text-xs text-muted-foreground tabular-nums">
                  {dateFmt.format(new Date(t.created_at))}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <TenantDetailModal
        tenantId={openId}
        onClose={() => setOpenId(null)}
      />
    </>
  );
}
