import Link from "next/link";
import { BRAND_NAME } from "@/lib/brand";
import { getCart } from "@/lib/medusa/cart";
import { getAccountSnapshot } from "@/lib/medusa/customer";
import { getLineItemCustomizationSurchargeTotalCents } from "@/lib/personalization-pricing";
import { getMenuSettingsContent, listSanityProductCategories, type MenuSettingsItem } from "@/lib/sanity/queries";
import { CartDrawerShell } from "@/components/layout/cart-drawer-shell";
import { MobileNavShell } from "@/components/layout/mobile-nav-shell";
import { SearchAutocomplete } from "@/components/layout/search-autocomplete";
import { logoutCustomerAction } from "@/app/compte/actions";
import { readLineItemCustomizations } from "@/lib/personalization";
import { SiteTextMap, text } from "@/lib/site-text";

type HeaderProps = {
  siteText: SiteTextMap;
};

function getDefaultMenuItems(siteText: SiteTextMap): MenuSettingsItem[] {
  return [
    { label: text(siteText, "header.nav.home"), href: "/", kind: "link", isVisible: true, openInNewTab: false, children: [] },
    { label: text(siteText, "header.nav.shop"), href: "/boutique", kind: "shopDropdown", isVisible: true, openInNewTab: false, children: [] },
    { label: text(siteText, "header.nav.learnMore"), href: "/en-savoir-plus", kind: "link", isVisible: true, openInNewTab: false },
    { label: text(siteText, "header.nav.showroom", "Showroom"), href: "/showroom", kind: "link", isVisible: true, openInNewTab: false },
  ];
}

export async function Header({ siteText }: HeaderProps) {
  const [cart, categories, account, menuSettings] = await Promise.all([
    getCart(),
    listSanityProductCategories(12),
    getAccountSnapshot(),
    getMenuSettingsContent(),
  ]);
  const isAuthenticated = account.authenticated;
  const visibleMenuItems = (menuSettings?.items || []).reduce<MenuSettingsItem[]>((acc, item) => {
    if (item.isVisible === false || !item.label || !item.href) {
      return acc;
    }

    acc.push({
      ...item,
      children: (item.children || []).filter((child) => child.isVisible !== false && child.label && child.href),
    });
    return acc;
  }, []);
  const menuItems = visibleMenuItems.length
    ? visibleMenuItems
    : getDefaultMenuItems(siteText);
  const cartCustomizationSurchargeCents = (cart?.items || []).reduce(
    (total, item) => total + getLineItemCustomizationSurchargeTotalCents({ quantity: item.quantity || 1, metadata: item.metadata || null }),
    0,
  );
  const itemCount = (cart?.items || []).reduce((total, item) => total + (item.quantity || 0), 0);
  const activePromoCodes = Array.from(
    new Set([
      ...(((cart as { promotions?: Array<{ code?: string | null }> } | null)?.promotions || [])
        .map((promotion) => promotion.code || "")
        .filter(Boolean)),
      ...(((cart as { discounts?: Array<{ code?: string | null }> } | null)?.discounts || [])
        .map((discount) => discount.code || "")
        .filter(Boolean)),
    ]),
  );
  const drawerItems = (cart?.items || []).map((item) => ({
    id: item.id,
    productTitle: item.product_title || "Produit",
    variantTitle: item.variant_title || null,
    imageUrl: (item as { thumbnail?: string | null }).thumbnail ?? null,
    quantity: item.quantity || 0,
    total: typeof item.total === "number" ? item.total + getLineItemCustomizationSurchargeTotalCents({ quantity: item.quantity || 1, metadata: item.metadata || null }) : null,
    theme: item.metadata?.theme ? String(item.metadata.theme) : null,
    paperFinish: item.metadata?.paper_finish ? String(item.metadata.paper_finish) : null,
    eventDate: item.metadata?.event_date ? String(item.metadata.event_date) : null,
    personalization: item.metadata?.personalization ? String(item.metadata.personalization) : null,
    customizations: readLineItemCustomizations(item.metadata),
  }));

  return (
    <header className="sticky top-0 z-40 border-b border-[var(--line)] bg-[#fff7f7e8] backdrop-blur-2xl">
      <div className="border-b border-[var(--line)] bg-[var(--accent-3)] px-4 py-2 text-center text-[11px] font-semibold uppercase tracking-[0.2em] text-white">
        {text(siteText, "header.topBanner")}
      </div>

      <div className="mx-auto flex w-full max-w-7xl items-center justify-between gap-3 px-4 py-3 md:gap-5 md:px-8 md:py-4">
        <Link href="/" className="inline-flex shrink-0 flex-col items-center gap-1 px-1 py-1 transition">
          <span className="brand-wordmark text-[2rem] leading-none text-[var(--accent-3)] hover:text-[var(--accent-2)] sm:text-[2.2rem] md:text-[2.45rem]">
            {BRAND_NAME}
          </span>
          <span className="brand-french-flag" role="img" aria-label="Drapeau français">
            <span className="bg-[#0055A4]" />
            <span className="bg-white" />
            <span className="bg-[#EF4135]" />
          </span>
        </Link>

        <SearchAutocomplete className="relative hidden flex-1 items-center rounded-full border border-[#ffffffd9] bg-white/92 p-1 shadow-[0_16px_36px_rgba(42,15,15,0.1)] md:flex md:max-w-2xl" />

        <div className="flex items-center gap-2 md:hidden">
          <CartDrawerShell
            itemCount={itemCount}
            subtotal={typeof cart?.subtotal === "number" ? cart.subtotal + cartCustomizationSurchargeCents : null}
            shippingTotal={cart?.shipping_total ?? null}
            discountTotal={cart?.discount_total ?? null}
            total={typeof cart?.total === "number" ? cart.total + cartCustomizationSurchargeCents : null}
            items={drawerItems}
            promoCodes={activePromoCodes}
          />
          <MobileNavShell categories={categories} isAuthenticated={isAuthenticated} menuItems={menuItems} />
        </div>

        <nav className="hidden items-center gap-1 rounded-full border border-[#ffffffd9] bg-white/88 p-1 text-sm font-semibold text-[var(--foreground)] shadow-[0_12px_30px_rgba(17,28,23,0.08)] md:flex">
          {menuItems.map((item) =>
            item.kind === "shopDropdown" || (item.children?.length || 0) > 0 ? (
              <div key={item._key || `${item.label}-${item.href}`} className="group relative">
                <Link
                  href={item.href}
                  className="inline-flex items-center gap-1 rounded-full px-4 py-2 transition-all duration-200 hover:-translate-y-[1px] hover:bg-[var(--surface-2)] hover:text-[var(--foreground)]"
                >
                  <span>{item.label}</span>
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" className="h-3.5 w-3.5">
                    <path strokeLinecap="round" strokeLinejoin="round" d="m6 9 6 6 6-6" />
                  </svg>
                </Link>

                <div className="pointer-events-none absolute left-0 top-full z-50 w-64 pt-2 opacity-0 transition duration-150 group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100">
                  <div className="translate-y-1 rounded-2xl border border-[#ffdede] bg-white p-2 shadow-[0_20px_40px_rgba(49,18,18,0.14)] transition duration-150 group-hover:translate-y-0 group-focus-within:translate-y-0">
                    <Link
                      href={item.href}
                      className="block rounded-xl px-3 py-2 text-sm font-semibold text-[var(--accent-3)] hover:bg-[var(--surface-2)]"
                    >
                      {item.kind === "shopDropdown" ? text(siteText, "header.categories.all") : item.label}
                    </Link>
                    {item.children?.length ? <div className="my-1 h-px bg-[#ffe4e4]" /> : null}
                    {item.children?.length ? (
                      <div className="space-y-1">
                        {item.children.map((child) => (
                          <Link
                            key={child._key || `${child.label}-${child.href}`}
                            href={child.href}
                            target={child.openInNewTab ? "_blank" : undefined}
                            rel={child.openInNewTab ? "noreferrer" : undefined}
                            className="block rounded-xl px-3 py-2 text-sm text-[var(--foreground)] hover:bg-[var(--surface-2)]"
                          >
                            <span className="line-clamp-1">{child.label}</span>
                          </Link>
                        ))}
                      </div>
                    ) : null}
                    {item.kind === "shopDropdown" ? <div className="my-1 h-px bg-[#ffe4e4]" /> : null}
                    {item.kind === "shopDropdown" ? (
                      <div className="max-h-72 overflow-auto pr-1">
                        {categories.length > 0 ? (
                          categories.map((category) => (
                            <Link
                              key={category._id}
                              href={`/boutique?categorie=${encodeURIComponent(category.slug)}`}
                              className="block rounded-xl px-3 py-2 text-sm text-[var(--foreground)] hover:bg-[var(--surface-2)]"
                            >
                              <span className="line-clamp-1">{category.title}</span>
                            </Link>
                          ))
                        ) : (
                          <p className="px-3 py-2 text-sm text-[var(--muted)]">{text(siteText, "header.categories.empty")}</p>
                        )}
                      </div>
                    ) : null}
                  </div>
                </div>
              </div>
            ) : (
              <Link
                key={item._key || `${item.label}-${item.href}`}
                href={item.href}
                target={item.openInNewTab ? "_blank" : undefined}
                rel={item.openInNewTab ? "noreferrer" : undefined}
                className="rounded-full px-4 py-2 transition-all duration-200 hover:-translate-y-[1px] hover:bg-[var(--surface-2)] hover:text-[var(--foreground)]"
              >
                {item.label}
              </Link>
            ),
          )}

          <div className="group relative">
            <Link
              href="/compte"
              className="inline-flex items-center gap-1 rounded-full px-4 py-2 transition-all duration-200 hover:-translate-y-[1px] hover:bg-[var(--surface-2)] hover:text-[var(--foreground)]"
            >
              <span>{text(siteText, "header.nav.account")}</span>
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" className="h-3.5 w-3.5">
                <path strokeLinecap="round" strokeLinejoin="round" d="m6 9 6 6 6-6" />
              </svg>
            </Link>

            <div className="pointer-events-none absolute left-0 top-full z-50 w-64 pt-2 opacity-0 transition duration-150 group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100">
              <div className="translate-y-1 rounded-2xl border border-[#ffdede] bg-white p-2 shadow-[0_20px_40px_rgba(49,18,18,0.14)] transition duration-150 group-hover:translate-y-0 group-focus-within:translate-y-0">
                {isAuthenticated ? (
                  <>
                    <Link
                      href="/compte"
                      className="block rounded-xl px-3 py-2 text-sm font-semibold text-[var(--accent-3)] hover:bg-[var(--surface-2)]"
                    >
                      {text(siteText, "header.account.manage")}
                    </Link>
                    <Link
                      href="/compte/commandes"
                      className="mt-1 block rounded-xl px-3 py-2 text-sm text-[var(--foreground)] hover:bg-[var(--surface-2)]"
                    >
                      {text(siteText, "header.account.orders")}
                    </Link>
                    <Link
                      href="/compte/devis"
                      className="mt-1 block rounded-xl px-3 py-2 text-sm text-[var(--foreground)] hover:bg-[var(--surface-2)]"
                    >
                      {text(siteText, "header.account.quotes")}
                    </Link>
                    <Link
                      href="/compte?section=payment"
                      className="mt-1 block rounded-xl px-3 py-2 text-sm text-[var(--foreground)] hover:bg-[var(--surface-2)]"
                    >
                      {text(siteText, "header.account.payment")}
                    </Link>
                    <div className="my-2 h-px bg-[#ffe4e4]" />
                    <form action={logoutCustomerAction}>
                      <button
                        type="submit"
                        className="w-full rounded-xl border border-[#f5505040] px-3 py-2 text-left text-sm font-semibold text-[var(--accent)] transition hover:bg-[#fff5f5]"
                      >
                        {text(siteText, "header.account.logout")}
                      </button>
                    </form>
                  </>
                ) : (
                  <div className="space-y-1">
                    <Link
                      href="/connexion"
                      className="block rounded-xl border border-[#ffdede] px-3 py-2 text-sm font-semibold text-[var(--accent-3)] transition hover:bg-[var(--surface-2)]"
                    >
                      {text(siteText, "header.account.login")}
                    </Link>
                    <Link
                      href="/inscription"
                      className="block rounded-xl border border-[#ffdede] px-3 py-2 text-sm font-semibold text-[var(--accent-3)] transition hover:bg-[var(--surface-2)]"
                    >
                      {text(siteText, "header.account.signup")}
                    </Link>
                  </div>
                )}
              </div>
            </div>
          </div>

          <CartDrawerShell
            itemCount={itemCount}
            subtotal={typeof cart?.subtotal === "number" ? cart.subtotal + cartCustomizationSurchargeCents : null}
            shippingTotal={cart?.shipping_total ?? null}
            discountTotal={cart?.discount_total ?? null}
            total={typeof cart?.total === "number" ? cart.total + cartCustomizationSurchargeCents : null}
            items={drawerItems}
            promoCodes={activePromoCodes}
          />
        </nav>
      </div>

    </header>
  );
}
