"use client";
import CategoryScroll from "@/app/[name]/(Main)/components/CategoryScroll";
import MenuFilterDrawer from "@/app/[name]/(Main)/components/MenuFilterDrawer";
import MenuSkeleton from "@/app/[name]/(Main)/components/MenuSkeleton";
import TextAlignIcon from "@/components/icons/TextAlignIcon";
import SearchBox from "@/components/input/SearchBox";
import MenuItem, { type MenuItemViewMode } from "@/components/listview/MenuItem";
import MenuItemRenderer from "@/components/listview/MenuItemRenderer";
import VerticalScrollView from "@/components/listview/VerticalScrollView";
import useToggle from "@/hooks/helpers/useToggle";
import clsx from "clsx";
import { motion } from "framer-motion";
import { RowHorizontal, RowVertical } from "iconsax-react";
import { useQueryState } from "next-usequerystate";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { useGetCategories, useGetProducts } from "./hooks/useMenuData";
import type { Category, Product } from "./types/Types";

const sortings = ["PopularityDescending", "RateDescending", "PriceAscending", "PriceDescending"] as const;

const MenuIndex = () => {
  const { data: productsData, isLoading: productsLoading } = useGetProducts();
  const { data: categoriesData, isLoading: categoriesLoading } = useGetCategories();
  const products = useMemo<Product[]>(() => productsData?.data || [], [productsData?.data]);
  const categories = useMemo<Category[]>(() => categoriesData?.data || [], [categoriesData?.data]);

  const isLoading = productsLoading || categoriesLoading;
  const { t: tCommon } = useTranslation("common");
  const { t: tMenu } = useTranslation("menu", { keyPrefix: "Menu" });
  const { state: filterSortModal, toggle: toggleFilterSortModal } = useToggle();
  const [sorting, setSorting] = useQueryState("sortBy", { defaultValue: "0" });
  const [search, setSearch] = useQueryState("q", { defaultValue: "" });
  const [selectedCategory, setSelectedCategory] = useQueryState("category", { defaultValue: "0" });
  const [filterSearch, setFilterSearch] = useQueryState("ingredients", { defaultValue: "" });
  const smallCategoriesRef: React.RefObject<HTMLDivElement | null> = useRef(null);
  const wrapperRef: React.RefObject<HTMLDivElement | null> = useRef(null);
  const [smallCategoriesVisible, setSmallCategoriesVisibility] = useState(false);
  const [isInitialMount, setIsInitialMount] = useState(true);
  const [viewMode, setViewMode] = useState<MenuItemViewMode>("list");

  useEffect(() => {
    const stored = localStorage.getItem("menuViewMode");
    if (stored === "grid" || stored === "list") setViewMode(stored);
  }, []);

  const setViewModeAndPersist = useCallback((mode: MenuItemViewMode) => {
    setViewMode(mode);
    if (typeof window !== "undefined") localStorage.setItem("menuViewMode", mode);
  }, []);

  useEffect(() => {
    if (isInitialMount) {
      setSearch(null);
      // category را نگه می‌داریم تا در بک زدن حفظ شود
      // setSelectedCategory(null);
      setFilterSearch(null);
      setSorting(null);
      setIsInitialMount(false);
    }
  }, [isInitialMount, setSearch, setFilterSearch, setSorting]);

  const onScroll = useCallback(() => {
    if (!wrapperRef?.current?.parentElement?.parentElement?.scrollTop || !smallCategoriesRef.current?.offsetTop) return;

    if (wrapperRef.current.parentElement?.parentElement.scrollTop >= smallCategoriesRef.current.offsetTop) {
      setSmallCategoriesVisibility(true);
    } else {
      setSmallCategoriesVisibility(false);
    }
  }, [wrapperRef, smallCategoriesRef]);

  useEffect(() => {
    if (!wrapperRef.current) return;

    const parent = wrapperRef.current.parentElement?.parentElement;
    if (!parent) return;

    parent.addEventListener("scroll", onScroll);

    return () => {
      parent.removeEventListener("scroll", onScroll);
    };
  }, [onScroll]);

  const updateSearch = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      setSearch(e.target.value);
    },
    [setSearch],
  );

  const updateCategory = useCallback(
    (categoryId: string) => {
      setSelectedCategory(categoryId);
    },
    [setSelectedCategory],
  );

  const sortingIndex = Number(sorting);
  const activeSortingIndex = Number.isNaN(sortingIndex) ? 0 : sortingIndex;

  const changeSorting = useCallback(
    (index: number) => {
      setSorting(() => String(index));
    },
    [setSorting],
  );

  const changeFilterSearch = useCallback(
    (value: string) => {
      setFilterSearch(value);
    },
    [setFilterSearch],
  );

  const filteredReceiptItems = useMemo(() => {
    if (!products.length) return [];
    const lowerSearch = search.toLowerCase();
    const lowerFilterQuery = filterSearch ? filterSearch.toLowerCase() : "";
    const selectedCatId = selectedCategory === "0" ? null : selectedCategory;

    // اگر دستهٔ اصلی انتخاب شده، خودش + همهٔ زیردسته‌ها را در نظر بگیر تا غذاهای زیردسته هم بیایند
    const effectiveCategoryIds = (() => {
      if (!selectedCatId) return null;
      const parent = categories.find((c) => c.id === selectedCatId);
      if (parent?.children?.length) {
        return new Set([parent.id, ...parent.children.map((ch) => ch.id)]);
      }
      return new Set([selectedCatId]);
    })();

    const filtered = products.filter((item) => {
      const matchesCategory = !selectedCatId || (item.category?.id != null && effectiveCategoryIds?.has(item.category.id));
      const itemName = item.name ?? item.title;
      const matchesSearch = !search || itemName.toLowerCase().includes(lowerSearch);

      // جستجو در عنوان و توضیحات (و در صورت وجود در محتویات)
      const matchesFilterSearch =
        !filterSearch ||
        (() => {
          const titleMatch = itemName.toLowerCase().includes(lowerFilterQuery);
          const description = item.description || item.desc || "";
          const descMatch = description.toLowerCase().includes(lowerFilterQuery);
          if (titleMatch || descMatch) return true;
          if (item.content && Array.isArray(item.content) && item.content.length > 0) {
            return item.content.some((content: string) => content.toLowerCase().includes(lowerFilterQuery));
          }
          return false;
        })();

      return matchesCategory && matchesSearch && matchesFilterSearch;
    });

    const sortingKey = sortings[Number(sorting)] || sortings[0];

    return [...filtered].sort((a, b) => {
      switch (sortingKey) {
        case "PopularityDescending":
          return (b.points ?? 0) - (a.points ?? 0);
        case "RateDescending":
          return (b.rate ?? 0) - (a.rate ?? 0);
        case "PriceAscending":
          return (a.price ?? 0) - (b.price ?? 0);
        case "PriceDescending":
          return (b.price ?? 0) - (a.price ?? 0);
        default:
          return 0;
      }
    });
  }, [selectedCategory, search, filterSearch, products, sorting, categories]);

  if (isLoading) {
    return <MenuSkeleton viewMode={viewMode} />;
  }

  return (
    <div className="flex flex-col gap-2 items-center pt-4 mb-8" ref={wrapperRef}>
      <div className="w-full">
        <SearchBox value={search} placeholder={tCommon("SearchPlaceholder")} onChange={updateSearch} />
        <CategoryScroll categories={categories} selectedCategory={selectedCategory} onSelect={updateCategory} />
      </div>

      <section className="w-full">
        <div className="flex gap-2 justify-between items-center relative" ref={smallCategoriesRef}>
          <span className="sm:text-base text-sm font-medium">{selectedCategory === "0" ? "" : categories.find((c) => c.id === selectedCategory)?.title || ""}</span>
          <div className="inline-flex gap-2 justify-end items-center">
            <div className="inline-flex rounded-xl h-8 bg-container p-1">
              <button
                onClick={() => setViewModeAndPersist("list")}
                className={clsx(
                  "rounded-lg h-6 w-8 inline-flex items-center justify-center transition-colors",
                  viewMode === "list" ? "bg-background text-foreground" : "text-foreground/60 hover:text-foreground",
                )}
                title="نمایش یک ستونه"
              >
                <RowVertical color="black" className="w-4 h-4" />
              </button>
              <button
                onClick={() => setViewModeAndPersist("grid")}
                className={clsx(
                  "rounded-lg h-6 w-8 inline-flex items-center justify-center transition-colors",
                  viewMode === "grid" ? "bg-background text-foreground" : "text-foreground/60 hover:text-foreground",
                )}
                title="نمایش دو ستونه"
              >
                <RowHorizontal color="black" className="w-4 h-4" />
              </button>
            </div>
            <button onClick={toggleFilterSortModal} className="rounded-xl h-8 bg-container ps-4 pe-2 py-1.5 inline-flex items-center gap-2">
              <TextAlignIcon className="text-foreground" />
              <span className="text-xs leading-5 font-medium">{tMenu("MenuFilterDrawer.Label")}</span>
            </button>
          </div>
        </div>

        <motion.div
          initial={{ y: smallCategoriesVisible ? 0 : -50, opacity: smallCategoriesVisible ? 1 : 0 }}
          animate={{ y: smallCategoriesVisible ? 0 : -50, opacity: smallCategoriesVisible ? 1 : 0 }}
          transition={{ duration: 0.1 }}
          className={clsx("fixed left-0 z-10 top-0 px-4 pt-16 bg-[#F4F5F9CC] dark:bg-background/70 backdrop-blur-[44px] right-0 xl:pr-72 xl:pt-20", ``)}
        >
          <CategoryScroll categories={categories} selectedCategory={selectedCategory} onSelect={updateCategory} variant="small" />
        </motion.div>

        <VerticalScrollView className="mt-5! overflow-y-auto h-full">
          {filteredReceiptItems.length === 0 ? (
            <div className="text-center text-foreground/60 py-8">{productsData ? "کالایی یافت نشد" : "در حال بارگذاری..."}</div>
          ) : viewMode === "grid" ? (
            <div className="grid grid-cols-2 gap-3">
              {filteredReceiptItems.map((product) => (
                <MenuItemRenderer key={product.id} variant="grid">
                  <MenuItem product={product} viewMode="grid" />
                </MenuItemRenderer>
              ))}
            </div>
          ) : (
            filteredReceiptItems.map((product) => (
              <MenuItemRenderer key={product.id} variant="list">
                <MenuItem product={product} viewMode="list" />
              </MenuItemRenderer>
            ))
          )}
        </VerticalScrollView>
      </section>

      <MenuFilterDrawer
        visible={filterSortModal}
        onClose={toggleFilterSortModal}
        searchQuery={filterSearch}
        onSearchChange={changeFilterSearch}
        onApply={() => {}}
        sortings={sortings}
        activeSortIndex={activeSortingIndex}
        onSortChange={changeSorting}
        tMenu={tMenu}
      />
    </div>
  );
};

export default MenuIndex;
