"use client";

import { useEffect, useRef, useState } from "react";
import Image from "next/image";
import { ArrowRight, ArrowUpRight, Search, X } from "lucide-react";
import { collections } from "@/data/storefront";
import { type CatalogProduct } from "@/data/catalog";
import { ProductOptions } from "@/components/shop/product-options";
import { SavedItems } from "@/components/shop/saved-items";
import Link from "next/link";

import { useSiteSettings } from '@/components/layout/site-settings';
import { navigationLinks } from '@/lib/site-settings';

export type Panel = "menu" | "search" | "wishlist" | "bag" | "about" | "product";

export function StorefrontDialog({ panel, product, initialVariantId, onClose, onCollection, onWishlist, onProduct, onBrowse, onCart, onCheckout, onAdded, onSearch }: { panel: Panel | null; product?: CatalogProduct; initialVariantId?: string; onClose: () => void; onCollection: (id: string) => void; onWishlist: () => void; onProduct: (id: string) => void; onBrowse: () => void; onCart: () => void; onCheckout: () => void; onAdded: () => void; onSearch: (query: string) => void }) {
  const header = useSiteSettings().header;
  const savedNavigation = header ? navigationLinks(header.navigation) : null;
  const dialogRef = useRef<HTMLDialogElement>(null);
  const [query, setQuery] = useState("");

  useEffect(() => {
    const dialog = dialogRef.current;
    if (!dialog) return;
    if (panel && !dialog.open) dialog.showModal();
    if (!panel && dialog.open) dialog.close();
    if (panel) {
      const focusTarget = dialog.querySelector<HTMLElement>(panel === "search" ? "input" : "#dialog-title");
      focusTarget?.focus({ preventScroll: true });
      const previousOverflow = document.body.style.overflow;
      document.body.style.overflow = "hidden";
      return () => { document.body.style.overflow = previousOverflow; };
    }
  }, [panel]);

  function close() { setQuery(""); onClose(); }
  const results = collections.filter((item) => `${item.name} ${item.categories.join(" ")}`.toLowerCase().includes(query.toLowerCase().trim()));
  const title = panel === "product" ? "Choose your options" : panel === "search" ? "Find your everyday" : panel === "menu" ? "Explore Fashion Mart" : panel === "bag" ? "Your shopping bag" : panel === "wishlist" ? "Your wishlist" : "Our story";

  return (
    <dialog ref={dialogRef} className={`storefront-dialog ${panel === "product" ? "collection-dialog" : ""}`} aria-labelledby="dialog-title" onCancel={(event) => { event.preventDefault(); close(); }} onClick={(event) => { if (event.target === event.currentTarget) { const rect = event.currentTarget.getBoundingClientRect(); if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) close(); } }}>
      <div className="dialog-header"><h2 id="dialog-title" tabIndex={-1}>{title}</h2><button type="button" className="icon-button" onClick={close} aria-label="Close dialog"><X size={21} /></button></div>
      {panel === "product" && product && <ProductOptions key={`${product.id}:${initialVariantId ?? "new"}`} product={product} initialVariantId={initialVariantId} onViewDetails={close} onAdded={onAdded} />}
      {(panel === "bag" || panel === "wishlist") && <SavedItems mode={panel} onProduct={onProduct} onBrowse={onBrowse} onCart={onCart} onCheckout={onCheckout} />}
      {panel === "search" && <div className="dialog-body"><form onSubmit={(event) => { event.preventDefault(); const search = query.trim(); setQuery(""); onSearch(search); }}><label htmlFor="collection-search" className="search-label">Search products or browse a collection</label><div className="search-field"><Search size={19} /><input autoFocus id="collection-search" value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Try polo, kurti or kids…" /><button type="submit" aria-label="Search products"><ArrowRight size={19} /></button></div></form><div className="search-results" aria-live="polite">{results.length ? results.map((item) => <button type="button" key={item.id} onClick={() => { setQuery(""); onCollection(item.id); }}><Image src={item.image} alt="" width={52} height={64} /><span><strong>{item.name}</strong><small>{item.categories.join(" · ")}</small></span><ArrowUpRight size={17} /></button>) : <p className="no-results">Press Enter to search products.</p>}</div></div>}
      {panel === "menu" && savedNavigation && <nav className="mobile-dialog-navigation" aria-label="Mobile navigation">{savedNavigation.map((item,index) => <Link key={`${item.href}-${index}`} href={item.href} onClick={close}>{item.label}<ArrowUpRight size={17} /></Link>)}<Link href="/account/portal" onClick={close}>My account</Link><Link href="/cart" onClick={close}>Shopping bag</Link></nav>}
      {panel === "menu" && !savedNavigation && <nav className="mobile-dialog-navigation" aria-label="Mobile navigation"><Link href="/" onClick={close}>Home <ArrowUpRight size={17} /></Link>{collections.map((item) => <button type="button" key={item.id} onClick={() => onCollection(item.id)}>{item.name} <ArrowUpRight size={17} /></button>)}<button type="button" onClick={onWishlist}>My wishlist <ArrowUpRight size={17} /></button><Link href="/cart" onClick={close}>Shopping bag <ArrowUpRight size={17} /></Link><Link href="/account" onClick={close}>My account <ArrowUpRight size={17} /></Link><Link href="/account/orders" onClick={close}>My orders <ArrowUpRight size={17} /></Link><Link href="/shop" onClick={close}>All collections <ArrowUpRight size={17} /></Link></nav>}
      {panel === "about" && <div className="dialog-body about-copy"><p className="eyebrow">WEAR YOUR EVERYDAY</p><h3>A wardrobe for every version of you.</h3><p>Fashion Mart brings together clothing for men, women, kids and active days. Our idea is simple: personal style should feel comfortable, easy and your own.</p><p>From everyday essentials to a little something different, find pieces that fit the way you live.</p><button type="button" className="text-link" onClick={onBrowse}>Meet the collections <ArrowRight size={16} /></button></div>}
    </dialog>
  );
}
