import { notFound } from "next/navigation";
import Link from "next/link";
import { eq, desc, sql } from "drizzle-orm";
import { db, schema } from "@/lib/db";
import Icon from "@/components/Icon";
import EditClientForm from "./EditClientForm";

export const metadata = { title: "Client" };

export default async function ClientDetailPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;

  const user = (
    await db
      .select()
      .from(schema.user)
      .where(eq(schema.user.id, id))
      .limit(1)
  )[0];
  if (!user) notFound();

  const profile = (
    await db
      .select()
      .from(schema.clientProfile)
      .where(eq(schema.clientProfile.userId, id))
      .limit(1)
  )[0];

  // Compte les dossiers (info utile pour l'admin avant de supprimer)
  const dossierCountRow = await db
    .select({ c: sql<number>`count(*)::int` })
    .from(schema.dossier)
    .where(eq(schema.dossier.clientId, id));
  const dossierCount = dossierCountRow[0]?.c ?? 0;

  // Liste les dossiers récents pour contextualiser
  const recentDossiers = await db
    .select({
      id: schema.dossier.id,
      reference: schema.dossier.reference,
      title: schema.dossier.title,
      status: schema.dossier.status,
      createdAt: schema.dossier.createdAt,
    })
    .from(schema.dossier)
    .where(eq(schema.dossier.clientId, id))
    .orderBy(desc(schema.dossier.createdAt))
    .limit(5);

  return (
    <div className="space-y-10 max-w-4xl">
      <Link
        href="/socialexadmin/clients"
        className="inline-flex items-center gap-2 text-xs uppercase tracking-widest text-on-surface-variant hover:text-primary transition-colors font-serif"
      >
        <Icon name="arrow_back" className="!text-base" />
        Retour aux clients
      </Link>

      <header className="border-b border-outline-variant pb-8">
        <span className="eyebrow">Fiche client</span>
        <h1 className="display-lg !text-4xl text-primary mt-2">
          {user.name}
        </h1>
        <div className="flex items-center gap-6 mt-3 text-sm text-on-surface-variant flex-wrap">
          <span>
            <Icon name="mail" className="!text-sm align-middle mr-1" />
            {user.email}
          </span>
          <span>
            <Icon name="event" className="!text-sm align-middle mr-1" />
            Inscrit le{" "}
            {new Date(user.createdAt).toLocaleDateString("fr-FR", {
              day: "numeric",
              month: "long",
              year: "numeric",
            })}
          </span>
          <span className="font-mono text-xs">{user.id}</span>
        </div>
      </header>

      <EditClientForm
        userId={user.id}
        initial={{
          name: user.name,
          email: user.email,
          company: profile?.company ?? "",
          siret: profile?.siret ?? "",
          phone: profile?.phone ?? "",
          addressStreet: profile?.addressStreet ?? "",
          addressZip: profile?.addressZip ?? "",
          addressCity: profile?.addressCity ?? "",
          addressCountry: profile?.addressCountry ?? "FR",
          notes: profile?.notes ?? "",
        }}
        dossierCount={dossierCount}
      />

      {recentDossiers.length > 0 && (
        <section className="space-y-4">
          <h2 className="font-serif text-2xl text-primary">Dossiers récents</h2>
          <div className="bg-white border border-outline-variant divide-y divide-outline-variant/40">
            {recentDossiers.map((d) => (
              <Link
                key={d.id}
                href={`/socialexadmin/dossiers/en-cours`}
                className="flex items-center justify-between gap-4 p-4 hover:bg-surface-container-low transition-colors"
              >
                <div className="min-w-0">
                  <p className="font-mono text-xs text-on-surface-variant">
                    {d.reference}
                  </p>
                  <p className="font-serif text-base text-primary truncate">
                    {d.title}
                  </p>
                </div>
                <span className="text-xs uppercase tracking-widest text-on-surface-variant font-serif shrink-0">
                  {d.status.replace(/_/g, " ")}
                </span>
              </Link>
            ))}
          </div>
        </section>
      )}
    </div>
  );
}
