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

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

const MenuIndex = () => {
  const { data: foodsData } = useGetFoods();
  const { data: categoriesData } = useGetCategories();
  const foods = useMemo<Food[]>(() => foodsData?.data || [], [foodsData?.data]);
  const categories = useMemo<Category[]>(() => categoriesData?.data || [], [categoriesData?.data]);
  const { t: tCommon } = useTranslation('common');
  const { t: tMenu } = useTranslation('menu', { keyPrefix: "Menu" });
  const { state: filterModal, toggle: toggleFilterModal } = useToggle();
  const { state: sortingModal, toggle: toggleSortingModal } = useToggle();
  const [sorting, setSorting] = useQueryState('sortBy', { defaultValue: '0' });
  const [search, setSearch] = useQueryState("q", { defaultValue: '' });
  const [selectedCategory, setSelectedCategory] = useQueryState('category', { defaultValue: '0' });
  const [selectedIngredients, setSelectedIngredients] = useQueryState('ingredients', { defaultValue: '' });
  const [selectedDeliveryId, setSelectedDeliveryId] = useQueryState('delivery', { defaultValue: '0' });
  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);

  useEffect(() => {
    if (isInitialMount) {
      setSearch(null);
      setSelectedCategory(null);
      setSelectedIngredients(null);
      setSelectedDeliveryId(null);
      setSorting(null);
      setIsInitialMount(false);
    }
  }, [isInitialMount, setSearch, setSelectedCategory, setSelectedIngredients, setSelectedDeliveryId, 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((index: number) => {
    setSelectedCategory(String(index));
  }, [setSelectedCategory]);

  const sortingIndex = Number(sorting);
  const activeSortingIndex = Number.isNaN(sortingIndex) ? 0 : sortingIndex;
  const activeSortingKey = sortings[activeSortingIndex] ?? sortings[0];
  const activeSortingLabel = tMenu(`MenuSortingDrawer.Options.${activeSortingKey}`);

  const changeSorting = (index: number) => {
    setSorting(() => String(index));
    toggleSortingModal();
  };

  const changeSelectedIngredients = useCallback((value: string) => {
    setSelectedIngredients(value);
  }, [setSelectedIngredients]);

  const changeSelectedDelivery = useCallback((value: string) => {
    setSelectedDeliveryId(() => value);
  }, [setSelectedDeliveryId]);

  const filteredReceiptItems = useMemo(() => {
    if (!foods.length) return [];
    const lowerSearch = search.toLowerCase();
    const lowerIngredients = selectedIngredients ? selectedIngredients.toLowerCase() : "";
    const selectedCatId =
      selectedCategory === "0" ? null : categories[+selectedCategory - 1]?.id;

    const filtered = foods.filter((item) => {
      const matchesCategory =
        selectedCategory === "0" || item.category?.id === selectedCatId;
      const itemName = item.name || item.title || item.foodName || "";
      const matchesSearch =
        !search || itemName.toLowerCase().includes(lowerSearch);

      const matchesIngredients = !selectedIngredients ||
        (item.content && Array.isArray(item.content) &&
          item.content.some((content: string) =>
            content.toLowerCase().includes(lowerIngredients)
          ));

      const matchesDelivery = selectedDeliveryId === "0" ||
        (selectedDeliveryId === "pickup" && item.pickupServe) ||
        (selectedDeliveryId === "inPlace" && item.inPlaceServe);

      return matchesCategory && matchesSearch && matchesIngredients && matchesDelivery;
    });

    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, selectedIngredients, selectedDeliveryId, foods, categories, sorting]);
  return (
    <div className="flex flex-col gap-4 items-center pt-8 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 justify-between items-center relative" ref={smallCategoriesRef} >
          <span className="text-base font-medium">
            {selectedCategory === '0' ? 'همه' : categories[+selectedCategory - 1]?.title || ''}
          </span>
          <div className="inline-flex gap-2 justify-around items-center">
            <button onClick={toggleFilterModal} className="rounded-xl h-8 bg-container ps-4 pe-2 py-1.5 inline-flex items-center justify-between gap-[7px]">
              <Candle2 className="stroke-foreground" size={16} />
              <span className="text-xs leading-5 font-medium">{tMenu('MenuFilterDrawer.Label')}</span>
            </button>
            <button
              onClick={toggleSortingModal}
              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">{activeSortingLabel}</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: .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">
              {foodsData ? 'غذایی یافت نشد' : 'در حال بارگذاری...'}
            </div>
          ) : (
            filteredReceiptItems.map((food) => (
              <MenuItemRenderer key={food.id}>
                <MenuItem food={food} />
              </MenuItemRenderer>
            ))
          )}
        </VerticalScrollView>
      </section>

      <MenuFilterDrawer
        visible={filterModal}
        onClose={toggleFilterModal}
        selectedIngredients={selectedIngredients}
        selectedDeliveryId={selectedDeliveryId}
        onIngredientsChange={changeSelectedIngredients}
        onDeliveryChange={changeSelectedDelivery}
        onApply={() => { }}
        tMenu={tMenu}
      />

      <MenuSortingDrawer
        visible={sortingModal}
        onClose={toggleSortingModal}
        sortings={sortings}
        activeIndex={activeSortingIndex}
        onSelect={changeSorting}
        tMenu={tMenu}
      />
    </div>
  );
};

export default MenuIndex;
