import { requireClient } from "@/lib/guards";
import { db, schema } from "@/lib/db";
import { and, desc, eq, ne } from "drizzle-orm";
import Link from "next/link";
import Icon from "@/components/Icon";

export const metadata = { title: "Tableau de bord" };

function formatEuros(cents: number): string {
  return new Intl.NumberFormat("fr-FR", {
    style: "currency",
    currency: "EUR",
  }).format(cents / 100);
}

export default async function ClientDashboardPage() {
  const session = await requireClient();
  const userId = session.user.id;

  const [activeDossiers, pendingDocs, openInvoices] = await Promise.all([
    // Dossiers en cours du client
    db
      .select()
      .from(schema.dossier)
      .where(
        and(
          eq(schema.dossier.clientId, userId),
          ne(schema.dossier.status, "termine"),
          ne(schema.dossier.status, "annule")
        )
      )
      .orderBy(desc(schema.dossier.updatedAt))
      .limit(5),

    // Documents demandés non encore uploadés
    db
      .select({
        id: schema.document.id,
        label: schema.document.label,
        description: schema.document.description,
        dossierId: schema.document.dossierId,
        dossierTitle: schema.dossier.title,
        requestedAt: schema.document.requestedAt,
      })
      .from(schema.document)
      .innerJoin(
        schema.dossier,
        eq(schema.document.dossierId, schema.dossier.id)
      )
      .where(
        and(
          eq(schema.dossier.clientId, userId),
          eq(schema.document.status, "demande")
        )
      )
      .orderBy(desc(schema.document.requestedAt)),

    // Factures non payées
    db
      .select()
      .from(schema.invoice)
      .where(
        and(
          eq(schema.invoice.clientId, userId),
          ne(schema.invoice.status, "payee"),
          ne(schema.invoice.status, "annulee")
        )
      )
      .orderBy(desc(schema.invoice.createdAt)),
  ]);

  return (
    <div className="space-y-12 max-w-5xl">
      <header>
        <span className="eyebrow">Espace client</span>
        <h1 className="display-lg !text-4xl text-primary mt-2">
          Bonjour {session.user.name.split(" ")[0]}.
        </h1>
        <p className="body-md text-on-surface-variant mt-2">
          Voici l'état de vos dossiers et documents en cours.
        </p>
      </header>

      {/* Documents à fournir — priorité visuelle si présents */}
      {pendingDocs.length > 0 && (
        <section className="bg-secondary-container border border-secondary p-8">
          <header className="flex items-center gap-3 mb-6">
            <Icon name="upload_file" className="text-on-secondary-container" />
            <h2 className="font-serif text-xl text-on-secondary-container">
              {pendingDocs.length} document
              {pendingDocs.length > 1 ? "s" : ""} à fournir
            </h2>
          </header>
          <ul className="divide-y divide-secondary/30">
            {pendingDocs.map((doc) => (
              <li key={doc.id} className="py-4">
                <Link
                  href={`/espace-client/dossiers/${doc.dossierId}`}
                  className="flex items-center justify-between gap-4 group"
                >
                  <div className="min-w-0">
                    <p className="font-serif text-on-secondary-container">
                      {doc.label}
                    </p>
                    <p className="text-xs text-on-secondary-container/80 truncate">
                      {doc.description ?? "—"} · Dossier {doc.dossierTitle}
                    </p>
                  </div>
                  <Icon
                    name="arrow_forward"
                    className="text-on-secondary-container group-hover:translate-x-1 transition-transform"
                  />
                </Link>
              </li>
            ))}
          </ul>
        </section>
      )}

      {/* Dossiers actifs */}
      <Panel
        title="Mes dossiers en cours"
        link={{ href: "/espace-client/dossiers", label: "Tous les dossiers" }}
      >
        {activeDossiers.length === 0 ? (
          <Empty label="Aucun dossier en cours pour le moment." />
        ) : (
          <ul className="divide-y divide-outline-variant/40">
            {activeDossiers.map((d) => (
              <li key={d.id} className="py-4">
                <Link
                  href={`/espace-client/dossiers/${d.id}`}
                  className="flex items-center justify-between gap-4 group"
                >
                  <div className="min-w-0">
                    <p className="font-serif text-primary truncate">
                      {d.title}
                    </p>
                    <p className="text-xs text-on-surface-variant truncate">
                      {d.reference} · Statut : {d.status.replace("_", " ")}
                    </p>
                  </div>
                  <Icon
                    name="arrow_forward"
                    className="text-on-surface-variant group-hover:translate-x-1 group-hover:text-primary transition-all"
                  />
                </Link>
              </li>
            ))}
          </ul>
        )}
      </Panel>

      {/* Factures à payer */}
      <Panel
        title="Factures en attente"
        link={{
          href: "/espace-client/factures",
          label: "Toutes les factures",
        }}
      >
        {openInvoices.length === 0 ? (
          <Empty label="Aucune facture en attente. Tout est à jour." />
        ) : (
          <ul className="divide-y divide-outline-variant/40">
            {openInvoices.map((inv) => (
              <li key={inv.id} className="py-4 flex items-center justify-between gap-4">
                <div>
                  <p className="font-serif text-primary">{inv.number}</p>
                  <p className="text-xs text-on-surface-variant">
                    {inv.description}
                  </p>
                </div>
                <p className="font-serif text-primary">
                  {formatEuros(inv.amountCents)}
                </p>
              </li>
            ))}
          </ul>
        )}
      </Panel>
    </div>
  );
}

function Panel({
  title,
  link,
  children,
}: {
  title: string;
  link?: { href: string; label: string };
  children: React.ReactNode;
}) {
  return (
    <section className="bg-white border border-outline-variant p-8">
      <header className="flex items-baseline justify-between mb-4">
        <h3 className="font-serif text-xl text-primary">{title}</h3>
        {link && (
          <Link
            href={link.href}
            className="text-xs uppercase tracking-widest font-serif text-on-surface-variant hover:text-primary transition-colors"
          >
            {link.label} →
          </Link>
        )}
      </header>
      {children}
    </section>
  );
}

function Empty({ label }: { label: string }) {
  return (
    <p className="text-sm text-on-surface-variant py-6 text-center italic">
      {label}
    </p>
  );
}
