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

type Props = {
  searchParams: Promise<{ notice?: string; section?: string; order?: string }>;
};

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

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 ComptePage({ searchParams }: Props) {
  const [{ notice, section, order }, account, siteText] = await Promise.all([searchParams, getAccountSnapshot(), getResolvedSiteText()]);
  const t = (key: string, fallback?: string) => text(siteText, key, fallback);

  const noticeMap: Record<string, string> = {
    "profile-updated": "Profil mis à jour.",
    "profile-error": "Impossible de mettre à jour le profil.",
    "address-invalid": "Adresse incomplète. Vérifiez les champs obligatoires.",
    "address-added": "Adresse ajoutée.",
    "address-deleted": "Adresse supprimée.",
    "address-error": "Impossible de modifier les adresses.",
    "quote-saved": "Devis enregistré dans votre compte.",
    "account-deleted": t("notice.account-deleted"),
    "account-delete-error": t("notice.account-delete-error"),
  };

  const feedback = notice ? noticeMap[notice] : null;
  const focusOrders = section === "orders";
  const focusQuotes = section === "quotes";
  const selectedOrderId = (order || "").trim();

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

  const customerName = [account.customer.first_name, account.customer.last_name].filter(Boolean).join(" ");
  const recentOrders = account.orders.slice(0, 3);

  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">
        <div className="flex flex-wrap items-start justify-between gap-4">
          <div>
            <p className="text-xs font-semibold uppercase tracking-[0.18em] text-[var(--accent-3)]">{t("account.eyebrow")}</p>
            <h1 className="mt-2 font-serif text-5xl text-[var(--foreground)] md:text-6xl">{customerName || t("account.defaultName")}</h1>
            <p className="mt-2 text-[var(--muted)]">{account.customer.email}</p>
          </div>
          <form action={logoutCustomerAction}>
            <button type="submit" className="inline-flex rounded-xl border border-[#ffd4d4] bg-white px-4 py-2 text-sm font-semibold text-[var(--foreground)] hover:bg-[#fff3f3]">
              {t("account.logout")}
            </button>
          </form>
        </div>
        {feedback ? (
          <p className="mt-4 rounded-xl border border-[#ffd9d9] bg-white/90 px-4 py-3 text-sm text-[var(--foreground)]">{feedback}</p>
        ) : null}
        <div className="mt-4 inline-flex rounded-full border border-[#ffd4d4] bg-white px-3 py-1 text-sm font-semibold text-[var(--foreground)]">
          {t("account.ordersCount")}: {account.ordersCount}
        </div>
        <div className="mt-3">
          <Link href="/compte/commandes" className="inline-flex rounded-xl border border-[#ffd4d4] bg-white px-4 py-2 text-sm font-semibold text-[var(--accent-3)] hover:bg-[#fff3f3]">
            {t("account.openOrders")}
          </Link>
        </div>
      </header>

      <section className="grid gap-6 lg:grid-cols-[1.1fr_1fr]">
        <article className="space-y-4 rounded-[1.5rem] border border-[#ffe0e0] bg-white p-6 shadow-[0_14px_32px_rgba(49,18,18,0.08)]">
          <h2 className="font-serif text-3xl text-[var(--foreground)]">{t("account.personalInfo")}</h2>
          <form action={updateCustomerProfileAction} className="grid gap-4">
            <div className="grid gap-4 sm:grid-cols-2">
              <label className="block space-y-1 text-sm">
                <span className="font-medium text-[var(--foreground)]">{t("auth.field.firstName")}</span>
                <input
                  name="firstName"
                  defaultValue={account.customer.first_name || ""}
                  className="w-full rounded-xl border border-[#ffd8d8] px-3 py-2 outline-none focus:border-[#f55050]"
                />
              </label>
              <label className="block space-y-1 text-sm">
                <span className="font-medium text-[var(--foreground)]">{t("auth.field.lastName")}</span>
                <input
                  name="lastName"
                  defaultValue={account.customer.last_name || ""}
                  className="w-full rounded-xl border border-[#ffd8d8] px-3 py-2 outline-none focus:border-[#f55050]"
                />
              </label>
            </div>
            <label className="block space-y-1 text-sm">
              <span className="font-medium text-[var(--foreground)]">{t("auth.field.phone")}</span>
              <input
                name="phone"
                defaultValue={account.customer.phone || ""}
                className="w-full rounded-xl border border-[#ffd8d8] px-3 py-2 outline-none focus:border-[#f55050]"
              />
            </label>
            <button type="submit" className="inline-flex w-fit rounded-xl bg-[var(--accent)] px-5 py-2.5 text-sm font-semibold text-white hover:bg-[var(--accent-2)]">
              {t("account.save")}
            </button>
          </form>
        </article>

        <article className="space-y-4 rounded-[1.5rem] border border-[#ffe0e0] bg-white p-6 shadow-[0_14px_32px_rgba(49,18,18,0.08)]">
          <h2 className="font-serif text-3xl text-[var(--foreground)]">{t("account.newAddress")}</h2>
          <form action={createCustomerAddressAction} className="grid gap-3">
            <div className="grid gap-3 sm:grid-cols-2">
              <input name="firstName" placeholder={t("auth.field.firstName")} className="rounded-xl border border-[#ffd8d8] px-3 py-2 outline-none focus:border-[#f55050]" />
              <input name="lastName" placeholder={t("auth.field.lastName")} className="rounded-xl border border-[#ffd8d8] px-3 py-2 outline-none focus:border-[#f55050]" />
            </div>
            <input name="company" placeholder={t("account.placeholder.company")} className="rounded-xl border border-[#ffd8d8] px-3 py-2 outline-none focus:border-[#f55050]" />
            <input name="address1" required placeholder={t("account.placeholder.address1")} className="rounded-xl border border-[#ffd8d8] px-3 py-2 outline-none focus:border-[#f55050]" />
            <input name="address2" placeholder={t("account.placeholder.address2")} className="rounded-xl border border-[#ffd8d8] px-3 py-2 outline-none focus:border-[#f55050]" />
            <div className="grid gap-3 sm:grid-cols-3">
              <input name="city" required placeholder={t("account.placeholder.city")} className="rounded-xl border border-[#ffd8d8] px-3 py-2 outline-none focus:border-[#f55050]" />
              <input name="postalCode" required placeholder={t("account.placeholder.postalCode")} className="rounded-xl border border-[#ffd8d8] px-3 py-2 outline-none focus:border-[#f55050]" />
              <input
                name="countryCode"
                required
                maxLength={2}
                placeholder={t("account.placeholder.country")}
                className="rounded-xl border border-[#ffd8d8] px-3 py-2 uppercase outline-none focus:border-[#f55050]"
              />
            </div>
            <input name="province" placeholder={t("account.placeholder.province")} className="rounded-xl border border-[#ffd8d8] px-3 py-2 outline-none focus:border-[#f55050]" />
            <input name="phone" placeholder={t("auth.field.phone")} className="rounded-xl border border-[#ffd8d8] px-3 py-2 outline-none focus:border-[#f55050]" />
            <div className="grid gap-2 text-sm text-[var(--muted)] sm:grid-cols-2">
              <label className="inline-flex items-center gap-2">
                <input type="checkbox" name="isDefaultShipping" />
                {t("account.defaultShipping")}
              </label>
              <label className="inline-flex items-center gap-2">
                <input type="checkbox" name="isDefaultBilling" />
                {t("account.defaultBilling")}
              </label>
            </div>
            <button type="submit" className="inline-flex w-fit rounded-xl bg-[var(--accent-3)] px-5 py-2.5 text-sm font-semibold text-white hover:bg-[#2c1717]">
              {t("account.addAddress")}
            </button>
          </form>
        </article>
      </section>

      <section className="grid gap-6 xl:grid-cols-[1.1fr_1fr]">
        <article
          id="mes-commandes"
          className={`space-y-4 rounded-[1.5rem] border bg-white p-6 shadow-[0_14px_32px_rgba(49,18,18,0.08)] ${
            focusOrders ? "border-[var(--accent)]" : "border-[#ffe0e0]"
          }`}
        >
          <h2 className="font-serif text-3xl text-[var(--foreground)]">{t("account.ordersTitle")}</h2>
          {recentOrders.length === 0 ? (
            <p className="text-sm text-[var(--muted)]">{t("account.ordersEmpty")}</p>
          ) : (
            <div className="grid gap-3">
              {recentOrders.map((order) => (
                <article key={order.id} className="rounded-xl border border-[#ffe8e8] bg-[#fffafa] p-4">
                  <p className="font-semibold text-[var(--foreground)]">
                    {t("account.order")} #{order.display_id || order.id?.slice(-6)}
                  </p>
                  <p className="mt-1 text-sm text-[var(--muted)]">{t("account.date")}: {formatDate(order.created_at)}</p>
                  <p className="text-sm text-[var(--muted)]">{t("account.status")}: {order.status || t("account.inProgress")}</p>
                  <p className="mt-1 text-sm font-semibold text-[var(--accent)]">{formatEuro(order.total)}</p>
                  <a
                    href={`/compte/commandes?order=${encodeURIComponent(order.id)}#commande-${encodeURIComponent(order.id)}`}
                    className="mt-3 inline-flex rounded-lg border border-[#ffd0d0] bg-white px-3 py-1 text-sm font-semibold text-[var(--accent-3)] hover:bg-[#fff3f3]"
                  >
                    {t("account.seeDetail")}
                  </a>
                  {selectedOrderId === order.id ? (
                    <div className="mt-3 rounded-lg border border-[#ffdede] bg-white p-3 text-sm text-[var(--muted)]">
                      <p className="font-medium text-[var(--foreground)]">{t("account.orderDetail")}</p>
                      <p className="mt-1">ID: {order.id}</p>
                      <p className="mt-1">{t("account.paymentStatus")}: {order.payment_status || "-"}</p>
                      <p className="mt-1">{t("account.shippingStatus")}: {order.fulfillment_status || "-"}</p>
                      {typeof (order as { metadata?: Record<string, unknown> | null }).metadata?.order_note === "string" &&
                      String((order as { metadata?: Record<string, unknown> | null }).metadata?.order_note || "").trim() ? (
                        <p className="mt-1">
                          Note: {String((order as { metadata?: Record<string, unknown> | null }).metadata?.order_note || "")}
                        </p>
                      ) : null}
                      <p className="mt-1">{t("account.subtotal")}: {formatEuro(order.subtotal)}</p>
                      <p className="mt-1">{t("account.shipping")}: {formatEuro(order.shipping_total)}</p>
                      <p className="mt-1">{t("account.taxes")}: {formatEuro(order.tax_total)}</p>
                      <p className="mt-1">{t("account.discount")}: {formatEuro(order.discount_total)}</p>
                    </div>
                  ) : null}
                </article>
              ))}
            </div>
          )}
        </article>

        <article className="space-y-4 rounded-[1.5rem] border border-[#ffe0e0] bg-white p-6 shadow-[0_14px_32px_rgba(49,18,18,0.08)]">
          <h2 className="font-serif text-3xl text-[var(--foreground)]">{t("account.addressesTitle")}</h2>
          {account.addresses.length === 0 ? (
            <p className="text-sm text-[var(--muted)]">{t("account.addressesEmpty")}</p>
          ) : (
            <div className="grid gap-3">
              {account.addresses.map((address) => (
                <article key={address.id} className="rounded-xl border border-[#ffe8e8] bg-[#fffafa] p-4">
                  <p className="font-semibold text-[var(--foreground)]">
                    {[address.first_name, address.last_name].filter(Boolean).join(" ") || t("account.addressFallback")}
                  </p>
                  <p className="mt-1 text-sm text-[var(--muted)]">
                    {[address.address_1, address.address_2].filter(Boolean).join(", ")}
                  </p>
                  <p className="text-sm text-[var(--muted)]">
                    {[address.postal_code, address.city, address.country_code?.toUpperCase()].filter(Boolean).join(" ")}
                  </p>
                  <form action={deleteCustomerAddressAction} className="mt-3">
                    <input type="hidden" name="addressId" value={address.id} />
                    <button type="submit" className="rounded-lg border border-[#f5505040] px-3 py-1 text-sm font-medium text-[var(--accent)]">
                      {t("account.delete")}
                    </button>
                  </form>
                </article>
              ))}
            </div>
          )}
        </article>
      </section>

      <section>
        <article
          id="mes-devis"
          className={`space-y-4 rounded-[1.5rem] border bg-white p-6 shadow-[0_14px_32px_rgba(49,18,18,0.08)] ${
            focusQuotes ? "border-[var(--accent)]" : "border-[#ffe0e0]"
          }`}
        >
          <h2 className="font-serif text-3xl text-[var(--foreground)]">Mes devis</h2>
          {account.quotes.length === 0 ? (
            <p className="text-sm text-[var(--muted)]">Aucun devis enregistré pour le moment.</p>
          ) : (
            <div className="grid gap-3">
              {account.quotes.map((quote) => (
                <article key={quote.id} className="rounded-xl border border-[#ffe8e8] bg-[#fffafa] p-4">
                  <p className="font-semibold text-[var(--foreground)]">{quote.reference || `Devis ${quote.id.slice(-6)}`}</p>
                  <p className="mt-1 text-sm text-[var(--muted)]">{t("account.date")}: {formatDate(quote.created_at)}</p>
                  <p className="text-sm text-[var(--muted)]">Valable jusqu&apos;au: {formatExpirationDate(quote.created_at)}</p>
                  {quote.event_date ? (
                    <p className="text-sm text-[var(--muted)]">Date de l&apos;événement: {quote.event_date}</p>
                  ) : null}
                  <p className="mt-1 text-sm font-semibold text-[var(--accent)]">{formatEuro(quote.total || 0)}</p>
                  {quote.items?.length ? (
                    <div className="mt-3 space-y-2 rounded-lg border border-[#ffdede] bg-white p-3 text-sm text-[var(--muted)]">
                      {quote.items.map((item, index) => (
                        <p key={`${quote.id}-${item.line_id || index}`}>
                          {(item.product_title || "Produit")} x {item.quantity || 1}
                        </p>
                      ))}
                    </div>
                  ) : null}
                  <div className="mt-3 flex flex-wrap gap-2">
                    <a
                      href={`/compte/devis?quote=${encodeURIComponent(quote.id)}#devis-${encodeURIComponent(quote.id)}`}
                      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]"
                    >
                      Voir le détail
                    </a>
                    <a
                      href={`/api/devis/${encodeURIComponent(quote.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élécharger le devis PDF
                    </a>
                    {isQuoteExpired(quote.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 expirée
                      </span>
                    ) : (
                      <form action={restoreQuoteToCartAction}>
                        <input type="hidden" name="quoteId" value={quote.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>
                    )}
                  </div>
                </article>
              ))}
            </div>
          )}
        </article>
      </section>

      <section>
        <article className="space-y-4 rounded-[1.5rem] border border-[#ffd6d6] bg-white p-6 shadow-[0_14px_32px_rgba(49,18,18,0.08)]">
          <h2 className="font-serif text-3xl text-[var(--foreground)]">{t("account.deleteAccountTitle")}</h2>
          <p className="max-w-2xl text-sm text-[var(--muted)]">{t("account.deleteAccountText")}</p>
          <form action={deleteCustomerAccountAction} className="space-y-4">
            <label className="flex items-start gap-3 rounded-xl border border-[#ffd8d8] bg-[#fff8f8] px-4 py-3 text-sm text-[var(--foreground)]">
              <input
                name="deleteAccountConfirmation"
                type="checkbox"
                value="yes"
                required
                className="mt-0.5 h-4 w-4 rounded border-[#f0b8b8] text-[var(--accent)] focus:ring-[var(--accent)]"
              />
              <span className="leading-6">{t("account.deleteAccountConfirm")}</span>
            </label>
            <button type="submit" className="inline-flex rounded-xl bg-[var(--accent)] px-5 py-2.5 text-sm font-semibold text-white hover:bg-[var(--accent-2)]">
              {t("account.deleteAccountButton")}
            </button>
          </form>
        </article>
      </section>
    </div>
  );
}
