import { requireClient } from "@/lib/guards";
import { db, schema } from "@/lib/db";
import { desc, eq } from "drizzle-orm";
import { isStripeConfigured } from "@/lib/stripe";
import { payInvoiceAction } from "../_actions/pay-invoice";

export const metadata = { title: "Mes factures" };

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

const statusLabels: Record<string, { label: string; cls: string }> = {
  brouillon: {
    label: "Brouillon",
    cls: "bg-surface-container text-on-surface-variant",
  },
  envoyee: {
    label: "À payer",
    cls: "bg-secondary-container text-on-secondary-container",
  },
  payee: { label: "Payée", cls: "bg-primary text-on-primary" },
  annulee: { label: "Annulée", cls: "bg-error-container text-on-error-container" },
};

const errorMessages: Record<string, string> = {
  invalid: "Identifiant de facture invalide.",
  notfound: "Facture introuvable.",
  already: "Cette facture a déjà été réglée ou annulée.",
  stripe:
    "Le paiement par carte est temporairement indisponible. Vous pouvez régler par virement (coordonnées sur votre facture).",
};

export default async function FacturesClientPage({
  searchParams,
}: {
  searchParams: Promise<{
    paid?: string;
    canceled?: string;
    error?: string;
  }>;
}) {
  const session = await requireClient();
  const { paid, canceled, error } = await searchParams;

  const invoices = await db
    .select()
    .from(schema.invoice)
    .where(eq(schema.invoice.clientId, session.user.id))
    .orderBy(desc(schema.invoice.createdAt));

  const stripeEnabled = isStripeConfigured();

  return (
    <div className="space-y-10 max-w-5xl">
      <header>
        <span className="eyebrow">Espace client</span>
        <h1 className="display-lg !text-4xl text-primary mt-2">Mes factures</h1>
      </header>

      {/* Bandeaux retour Stripe */}
      {paid && (
        <div
          role="status"
          className="border border-primary/30 bg-primary/[0.04] px-5 py-4"
        >
          <p className="body-md text-primary">
            Paiement reçu pour la facture <strong>{paid}</strong>. Merci, votre
            dossier avance.
          </p>
        </div>
      )}
      {canceled && (
        <div
          role="status"
          className="border border-outline-variant bg-surface-container-low px-5 py-4"
        >
          <p className="body-md text-on-surface-variant">
            Paiement non finalisé. Vous pouvez recommencer à tout moment.
          </p>
        </div>
      )}
      {error && errorMessages[error] && (
        <div
          role="alert"
          className="border border-error/40 px-5 py-4"
          style={{ backgroundColor: "rgba(186, 26, 26, 0.06)" }}
        >
          <p className="body-md text-error">{errorMessages[error]}</p>
        </div>
      )}

      {invoices.length === 0 ? (
        <div className="bg-white border border-outline-variant p-16 text-center">
          <p className="body-md text-on-surface-variant italic">
            Aucune facture émise pour l'instant.
          </p>
        </div>
      ) : (
        <div className="bg-white border border-outline-variant overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-outline-variant/60 text-left">
                <th className="eyebrow !text-on-surface-variant p-4">N°</th>
                <th className="eyebrow !text-on-surface-variant p-4">
                  Description
                </th>
                <th className="eyebrow !text-on-surface-variant p-4">Montant</th>
                <th className="eyebrow !text-on-surface-variant p-4">Statut</th>
                <th className="eyebrow !text-on-surface-variant p-4">Date</th>
                <th className="eyebrow !text-on-surface-variant p-4 text-right">
                  Action
                </th>
              </tr>
            </thead>
            <tbody>
              {invoices.map((inv) => {
                const s = statusLabels[inv.status] ?? {
                  label: inv.status,
                  cls: "",
                };
                const canPay = inv.status === "envoyee" && stripeEnabled;
                return (
                  <tr
                    key={inv.id}
                    className="border-b border-outline-variant/40 last:border-b-0"
                  >
                    <td className="font-serif text-primary p-4">{inv.number}</td>
                    <td className="text-on-surface-variant p-4 max-w-md">
                      {inv.description}
                    </td>
                    <td className="font-serif text-primary p-4">
                      {formatEuros(inv.amountCents)}
                    </td>
                    <td className="p-4">
                      <span
                        className={`inline-block px-2.5 py-1 text-[10px] uppercase tracking-widest font-serif ${s.cls}`}
                      >
                        {s.label}
                      </span>
                    </td>
                    <td className="text-on-surface-variant p-4 text-xs">
                      {new Date(inv.createdAt).toLocaleDateString("fr-FR")}
                    </td>
                    <td className="p-4 text-right">
                      {canPay ? (
                        <form action={payInvoiceAction}>
                          <input
                            type="hidden"
                            name="invoiceId"
                            value={inv.id}
                          />
                          <button
                            type="submit"
                            className="text-xs uppercase tracking-widest font-serif text-secondary hover:text-primary underline underline-offset-4"
                          >
                            Payer par carte
                          </button>
                        </form>
                      ) : null}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
