import Link from "next/link";
import type { Metadata } from "next";
import { redirect } from "next/navigation";
import { deleteQuoteAction, restoreQuoteToCartAction } from "@/app/actions/cart";
import { getAccountSnapshot } from "@/lib/medusa/customer";
import { getQuoteExpirationDate, isQuoteExpired } from "@/lib/medusa/quotes";
import { formatEuro } from "@/lib/utils/money";
import { getResolvedSiteText } from "@/lib/site-text-server";
import { text } from "@/lib/site-text";

export const metadata: Metadata = {
  title: "Mes devis",
  robots: { index: false, follow: false },
};

type Props = {
  searchParams: Promise<{ quote?: string }>;
};

function formatDate(value?: string | Date | null) {
  if (!value) return "-";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "-";
  return new Intl.DateTimeFormat("fr-FR", { dateStyle: "medium" }).format(date);
}

function formatExpirationDate(value?: string | null) {
  const expiresAt = getQuoteExpirationDate(value);
  if (!expiresAt) return "-";
  return formatDate(expiresAt);
}

export default async function CompteDevisPage({ searchParams }: Props) {
  const [{ quote }, account, siteText] = await Promise.all([searchParams, getAccountSnapshot(), getResolvedSiteText()]);
  const t = (key: string, fallback?: string) => text(siteText, key, fallback);
  const selectedQuoteId = (quote || "").trim();

  if (!account.authenticated || !account.customer) {
    redirect("/connexion");
  }

  return (
    <div className="space-y-6">
      <header className="rounded-[1.9rem] border border-[#ffdede] bg-[linear-gradient(135deg,#fffafa_0%,#fff0f0_55%,#ffe7e7_100%)] p-6 shadow-[0_20px_42px_rgba(49,18,18,0.1)] md:p-8">
        <p className="text-xs font-semibold uppercase tracking-[0.18em] text-[var(--accent-3)]">{t("quotes.eyebrow")}</p>
        <h1 className="mt-2 font-serif text-5xl text-[var(--foreground)] md:text-6xl">{t("quotes.title")}</h1>
        <p className="mt-2 text-[var(--muted)]">{account.quotes.length} devis</p>
      </header>

      {account.quotes.length === 0 ? (
        <section className="rounded-[1.5rem] border border-[#ffe0e0] bg-white p-6 shadow-[0_14px_32px_rgba(49,18,18,0.08)]">
          <p className="text-sm text-[var(--muted)]">{t("quotes.empty")}</p>
          <Link href="/boutique" className="mt-4 inline-flex rounded-xl bg-[var(--accent)] px-4 py-2 text-sm font-semibold text-white hover:bg-[var(--accent-2)]">
            {t("orders.emptyCta")}
          </Link>
        </section>
      ) : (
        <section className="space-y-3">
          {account.quotes.map((quoteItem) => (
            <details
              key={quoteItem.id}
              id={`devis-${quoteItem.id}`}
              open={selectedQuoteId === quoteItem.id}
              className="rounded-[1.2rem] border border-[#ffe0e0] bg-white p-4 shadow-[0_10px_24px_rgba(49,18,18,0.06)] open:border-[var(--accent)]"
            >
              <summary className="flex cursor-pointer list-none flex-wrap items-center justify-between gap-3">
                <span className="font-semibold text-[var(--foreground)]">
                  {quoteItem.reference || `${t("quotes.reference")} #${quoteItem.id.slice(-6)}`}
                </span>
                <span className="text-sm text-[var(--muted)]">{formatDate(quoteItem.created_at)}</span>
                <span className="text-sm font-semibold text-[var(--accent)]">{formatEuro(quoteItem.total || 0)}</span>
              </summary>

              <div className="mt-4 grid gap-2 rounded-xl border border-[#ffe8e8] bg-[#fffafa] p-4 text-sm text-[var(--muted)]">
                <p className="flex items-center justify-between">
                  <span>{t("quotes.reference")}</span>
                  <span className="font-medium text-[var(--foreground)]">{quoteItem.reference || quoteItem.id}</span>
                </p>
                <p className="flex items-center justify-between">
                  <span>{t("account.date")}</span>
                  <span className="font-medium text-[var(--foreground)]">{formatDate(quoteItem.created_at)}</span>
                </p>
                <p className="flex items-center justify-between">
                  <span>Valable jusqu&apos;au</span>
                  <span className="font-medium text-[var(--foreground)]">{formatExpirationDate(quoteItem.created_at)}</span>
                </p>
                {quoteItem.event_date ? (
                  <p className="flex items-center justify-between">
                    <span>Date evenement</span>
                    <span className="font-medium text-[var(--foreground)]">{quoteItem.event_date}</span>
                  </p>
                ) : null}
                <p className="flex items-center justify-between">
                  <span>{t("account.subtotal")}</span>
                  <span className="font-medium text-[var(--foreground)]">{formatEuro(quoteItem.subtotal || 0)}</span>
                </p>
                <p className="flex items-center justify-between">
                  <span>{t("account.shipping")}</span>
                  <span className="font-medium text-[var(--foreground)]">{formatEuro(quoteItem.shipping_total || 0)}</span>
                </p>
                <p className="flex items-center justify-between border-t border-[#ffe1e1] pt-2 text-base">
                  <span className="font-semibold text-[var(--foreground)]">{t("cart.total")}</span>
                  <span className="font-semibold text-[var(--foreground)]">{formatEuro(quoteItem.total || 0)}</span>
                </p>
                <div className="pt-2">
                  <div className="flex flex-wrap gap-2">
                    <a
                      href={`/api/devis/${encodeURIComponent(quoteItem.id)}/pdf`}
                      className="inline-flex rounded-lg border border-[#ffd0d0] bg-white px-3 py-1.5 text-sm font-semibold text-[var(--accent-3)] hover:bg-[#fff3f3]"
                    >
                      {t("quotes.downloadPdf")}
                    </a>
                    {isQuoteExpired(quoteItem.created_at) ? (
                      <span className="inline-flex rounded-lg border border-[#ffe1e1] bg-[#fff6f6] px-3 py-1.5 text-sm font-semibold text-[#a21717]">
                        Offre expiree
                      </span>
                    ) : (
                      <form action={restoreQuoteToCartAction}>
                        <input type="hidden" name="quoteId" value={quoteItem.id} />
                        <button
                          type="submit"
                          className="inline-flex rounded-lg border border-[var(--accent-3)] bg-white px-3 py-1.5 text-sm font-semibold text-[var(--accent-3)] hover:bg-[#fff3f3]"
                        >
                          Remettre au panier
                        </button>
                      </form>
                    )}
                    <form action={deleteQuoteAction}>
                      <input type="hidden" name="quoteId" value={quoteItem.id} />
                      <button
                        type="submit"
                        className="inline-flex rounded-lg border border-[#ffd8d8] bg-white px-3 py-1.5 text-sm font-semibold text-[#b42318] hover:bg-[#fff1f1]"
                      >
                        Supprimer
                      </button>
                    </form>
                  </div>
                </div>

                {Array.isArray(quoteItem.items) && quoteItem.items.length > 0 ? (
                  <div className="mt-2 rounded-lg border border-[#ffe1e1] bg-white p-3">
                    <p className="text-xs font-semibold uppercase tracking-[0.12em] text-[var(--accent-3)]">{t("orders.itemsTitle")}</p>
                    <div className="mt-2 space-y-2">
                      {quoteItem.items.map((item, index) => (
                        <div key={`${quoteItem.id}-${item.line_id || index}`} className="flex items-center justify-between gap-3 text-sm">
                          <div>
                            <p className="font-medium text-[var(--foreground)]">{item.product_title || "Article"}</p>
                            <p className="text-[var(--muted)]">{t("orders.quantity")}: {item.quantity || 1}</p>
                          </div>
                          <p className="font-medium text-[var(--foreground)]">{formatEuro(item.total || 0)}</p>
                        </div>
                      ))}
                    </div>
                  </div>
                ) : null}
              </div>
            </details>
          ))}
        </section>
      )}
    </div>
  );
}
