"use client";

import { useMemo, useState } from "react";
import Link from "next/link";
import Image from "next/image";
import { AnimatePresence, motion } from "framer-motion";
import { Search, ShoppingBag, X, ChevronDown } from "lucide-react";
import CatalogMobileBottomNav from "@/components/CatalogMobileBottomNav";
import { withAlpha } from "@/lib/color-contrast";
import { useVisaoDaLoja } from "@/components/VisaoDaLojaContext";
import { normalizeWhatsappForLink } from "@/lib/phone";

type MobileCategory = {
  id: string;
  name: string;
  slug?: string | null;
  parent_id?: string | null;
};

type SearchProduct = {
  id: string;
  name: string;
  image_url?: string | null;
  price?: number | null;
  price_on_request?: boolean | null;
};

type ProductMobileNavShellProps = {
  slug: string;
  profileId: string;
  primaryColor: string;
  logoUrl?: string | null;
  storeName: string;
  storeSlogan?: string | null;
  whatsappDigits?: string;
  categories: MobileCategory[];
  announcementCouponId?: string | null;
  initialSelectedCategoryId?: string | null;
  storiesGroups?: any[];
  catalogStoriesEnabled?: boolean;
};

export default function ProductMobileNavShell({
  slug,
  profileId,
  primaryColor,
  logoUrl,
  storeName,
  storeSlogan,
  whatsappDigits,
  categories,
}: ProductMobileNavShellProps) {
  const [isMobileSearchOpen, setIsMobileSearchOpen] = useState(false);
  const [isMobileCategoriesOpen, setIsMobileCategoriesOpen] = useState(false);
  const [expandedMobileParentIds, setExpandedMobileParentIds] = useState<Set<string>>(new Set());
  const [searchTerm, setSearchTerm] = useState("");
  const [searchProducts, setSearchProducts] = useState<SearchProduct[]>([]);
  const [searchLoaded, setSearchLoaded] = useState(false);
  const { textoNoLugarDoPreco: textoSemPreco } = useVisaoDaLoja();

  const rootCategories = useMemo(
    () => categories.filter((category) => !category.parent_id),
    [categories]
  );
  const subcategoriesByParent = useMemo(() => {
    const map = new Map<string, MobileCategory[]>();
    categories.forEach((category) => {
      if (!category.parent_id) return;
      const list = map.get(category.parent_id) || [];
      list.push(category);
      map.set(category.parent_id, list);
    });
    return map;
  }, [categories]);

  const filteredProducts = useMemo(() => {
    const term = searchTerm.trim().toLowerCase();
    if (!term) return searchProducts.slice(0, 8);
    return searchProducts
      .filter((product) => product.name.toLowerCase().includes(term))
      .slice(0, 12);
  }, [searchProducts, searchTerm]);

  /* A lista vem do servidor (/api/catalog/produtos), ja respeitando quem
     esta olhando: sem preco para quem a regra da loja nao deixa ver. Antes o
     navegador consultava o banco direto com a chave publica. */
  const loadSearchProducts = async () => {
    if (searchLoaded) return;
    try {
      const resposta = await fetch(`/api/catalog/produtos?slug=${encodeURIComponent(slug)}`);
      const dados = (await resposta.json().catch(() => null)) as { produtos?: SearchProduct[] } | null;
      setSearchProducts(Array.isArray(dados?.produtos) ? dados.produtos : []);
    } catch {
      setSearchProducts([]);
    }
    setSearchLoaded(true);
  };

  const toggleMobileParentCategory = (categoryId: string) => {
    setExpandedMobileParentIds((prev) => {
      const next = new Set(prev);
      if (next.has(categoryId)) {
        next.delete(categoryId);
      } else {
        next.add(categoryId);
      }
      return next;
    });
  };

  const closeCategoryMenus = () => {
    setIsMobileCategoriesOpen(false);
    setExpandedMobileParentIds(new Set());
  };

  const mobileHoverBg = withAlpha(primaryColor, 0.06);
  const mobileSubmenuLine = withAlpha(primaryColor, 0.2);
  const resolvedWhatsappDigits = normalizeWhatsappForLink(whatsappDigits);

  const formatMoney = (value: number) =>
    new Intl.NumberFormat("pt-BR", { style: "currency", currency: "BRL" }).format(value);

  return (
    <>
      <CatalogMobileBottomNav
        slug={slug}
        primaryColor={primaryColor}
        categoriesHref={`/${slug}`}
        whatsappDigits={resolvedWhatsappDigits}
        isSearchActive={isMobileSearchOpen}
        isCategoriesActive={isMobileCategoriesOpen}
        onHomeClick={() => {
          closeCategoryMenus();
          setIsMobileSearchOpen(false);
        }}
        onSearchClick={() => {
          setIsMobileCategoriesOpen(false);
          setIsMobileSearchOpen(true);
          void loadSearchProducts();
        }}
        onCategoriesClick={() => {
          setIsMobileSearchOpen(false);
          setIsMobileCategoriesOpen((prev) => !prev);
        }}
        />

      {/* Mobile Search Overlay */}
      {isMobileSearchOpen && (
        <div className="md:hidden fixed inset-0 bg-white z-[80] pt-20 px-4 animate-in slide-in-from-bottom-10 duration-200">
          <button
            onClick={() => setIsMobileSearchOpen(false)}
            className="absolute top-5 right-4 p-2 rounded-full bg-gray-100"
          >
            <X size={20} />
          </button>
          <div className="max-w-lg mx-auto space-y-4">
            <div className="relative">
              <Search className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-400" size={20} />
              <input
                type="text"
                value={searchTerm}
                onChange={(event) => setSearchTerm(event.target.value)}
                placeholder="Buscar produtos..."
                className="w-full h-14 pl-12 pr-4 rounded-2xl border border-gray-200 bg-gray-50 text-sm font-medium outline-none focus:ring-2 focus:ring-gray-200"
                autoFocus
              />
            </div>
            <div className="space-y-2 max-h-[70vh] overflow-y-auto pb-20">
              {filteredProducts.map((product) => (
                <Link
                  key={product.id}
                  href={`/${slug}/p/${product.id}`}
                  onClick={() => setIsMobileSearchOpen(false)}
                  className="flex items-center gap-4 p-3 bg-gray-50 rounded-xl border border-gray-100"
                >
                  <div className="w-12 h-12 bg-white rounded-lg flex items-center justify-center shrink-0">
                    {product.image_url ? (
                      <Image src={product.image_url} alt={product.name} width={48} height={48} className="w-full h-full object-cover rounded-lg" />
                    ) : (
                      <ShoppingBag size={20} className="text-gray-300" />
                    )}
                  </div>
                  <div>
                    <p className="font-medium text-gray-900 line-clamp-1">{product.name}</p>
                    <p className="text-sm text-gray-500 font-bold">
                      {product.price_on_request ? textoSemPreco : formatMoney(Number(product.price || 0))}
                    </p>
                  </div>
                </Link>
              ))}
              {!filteredProducts.length ? (
                <div className="rounded-xl border border-gray-200 bg-gray-50 p-4 text-sm text-gray-500">
                  Nenhum produto encontrado.
                </div>
              ) : null}
            </div>
          </div>
        </div>
      )}

      <AnimatePresence initial={false}>
        {isMobileCategoriesOpen && (
          <div className="md:hidden fixed inset-0 z-[80]">
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              transition={{ duration: 0.22, ease: "easeOut" }}
              className="absolute inset-0 bg-black/52"
              onClick={closeCategoryMenus}
            />
            <motion.aside
              initial={{ x: "-100%" }}
              animate={{ x: 0 }}
              exit={{ x: "-100%" }}
              transition={{ type: "tween", duration: 0.3, ease: [0.25, 0.1, 0.25, 1] }}
              className="absolute left-0 top-0 bottom-0 w-[84%] max-w-[320px] bg-white rounded-r-3xl border-r border-slate-100 border-t border-slate-100 shadow-[12px_0_32px_rgba(15,23,42,0.25)] flex flex-col transform-gpu will-change-transform"
            >
              <div className="px-5 pt-5 pb-3">
                <div className="flex items-start justify-between">
                  <div className="flex items-center gap-2.5 min-w-0">
                    {logoUrl ? (
                      <div className="h-10 w-14 p-0.5 border shadow-sm shrink-0 rounded-md" style={{ backgroundColor: withAlpha(primaryColor, 0.18), borderColor: withAlpha(primaryColor, 0.28) }}>
                        <Image src={logoUrl} alt={storeName} width={56} height={40} className="h-full w-full object-contain" />
                      </div>
                    ) : (
                      <div className="h-9 w-9 rounded-lg bg-slate-50 border border-slate-100 shadow-sm flex items-center justify-center shrink-0">
                        <ShoppingBag size={18} className="text-slate-700" />
                      </div>
                    )}
                    <div className="min-w-0">
                      <span className="text-[13px] font-semibold text-slate-800 line-clamp-1 block">{storeName}</span>
                      {storeSlogan ? <span className="text-[11px] text-slate-500 line-clamp-1 block">{storeSlogan}</span> : null}
                    </div>
                  </div>
                  <button onClick={closeCategoryMenus} className="h-10 w-10 rounded-full bg-slate-100/90 text-slate-500 flex items-center justify-center">
                    <X size={17} />
                  </button>
                </div>
                <div className="mt-4 text-[11px] uppercase tracking-[0.14em] font-bold text-slate-400">Categorias</div>
              </div>
              <div className="h-px bg-slate-100" />

              <div className="flex-1 overflow-y-auto px-3 py-3 pb-[96px] space-y-1.5">
                <Link href={`/${slug}`} onClick={closeCategoryMenus} className="relative block rounded-xl px-3 py-2.5 text-left text-slate-700 hover:bg-slate-50 transition-all">
                  <span className="pl-3 inline-flex items-center gap-2 text-[13px] font-semibold">
                    <span>🛍️</span>
                    <span>Todas os Produtos</span>
                  </span>
                </Link>

                {rootCategories.map((category) => {
                  const hasChildren = (subcategoriesByParent.get(category.id) || []).length > 0;
                  const isExpanded = expandedMobileParentIds.has(category.id);
                  return (
                    <div key={category.id} className="space-y-1">
                      <div className="relative flex items-center rounded-xl px-3 py-2.5 text-[13px] text-slate-700">
                        <Link
                          href={category.slug ? `/${slug}/c/${category.slug}` : `/${slug}`}
                          onClick={closeCategoryMenus}
                          className="pl-3 line-clamp-1 font-medium flex-1"
                        >
                          {category.name}
                        </Link>
                        {hasChildren ? (
                          <button
                            type="button"
                            onClick={(event) => {
                              event.preventDefault();
                              event.stopPropagation();
                              toggleMobileParentCategory(category.id);
                            }}
                            className="ml-2 h-6 w-6 rounded-full flex items-center justify-center"
                            style={isExpanded ? { backgroundColor: mobileHoverBg } : undefined}
                          >
                            <ChevronDown size={14} className={`text-slate-400 transition-transform ${isExpanded ? "rotate-180" : ""}`} />
                          </button>
                        ) : null}
                      </div>
                      {hasChildren && isExpanded ? (
                        <div className="ml-5 pl-2 space-y-1 border-l" style={{ borderColor: mobileSubmenuLine }}>
                          {(subcategoriesByParent.get(category.id) || []).map((subcategory) => (
                            <Link
                              key={subcategory.id}
                              href={subcategory.slug ? `/${slug}/c/${subcategory.slug}` : `/${slug}`}
                              onClick={closeCategoryMenus}
                              className="block rounded-lg px-3 py-2 text-[12px] text-slate-600 hover:text-slate-900 hover:bg-slate-50"
                            >
                              <span className="inline-flex items-center gap-2">
                                <span className="text-[10px]">•</span>
                                <span>{subcategory.name}</span>
                              </span>
                            </Link>
                          ))}
                        </div>
                      ) : null}
                    </div>
                  );
                })}
              </div>
            </motion.aside>
          </div>
        )}
      </AnimatePresence>
    </>
  );
}
