'use client';

import React, { useState, useEffect, useRef } from "react";
import Button from "@/components/button/PrimaryButton";
import AnimatedBottomSheet from "@/components/bottomsheet/AnimatedBottomSheet";
import { Switch } from "@/components/ui/switch";
import { TicketPercentIcon, ChevronDown } from "lucide-react";
import clsx from "clsx";

type MenuFilterDrawerProps = {
  visible: boolean;
  onClose: () => void;
  searchQuery: string;
  onSearchChange: (value: string) => void;
  onApply: () => void;
  sortings: ReadonlyArray<string>;
  activeSortIndex: number;
  onSortChange: (index: number) => void;
  tMenu: (key: string) => string;
};

const MenuFilterDrawer = ({
  visible,
  onClose,
  searchQuery,
  onSearchChange,
  onApply,
  sortings,
  activeSortIndex,
  onSortChange,
  tMenu,
}: MenuFilterDrawerProps) => {
  const [tempQuery, setTempQuery] = useState(searchQuery);
  const [tempSortIndex, setTempSortIndex] = useState(activeSortIndex);
  const [sortSelectOpen, setSortSelectOpen] = useState(false);
  const sortSelectRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (visible) {
      setTempQuery(searchQuery);
      setTempSortIndex(activeSortIndex);
      setSortSelectOpen(false);
    }
  }, [visible, searchQuery, activeSortIndex]);

  useEffect(() => {
    if (!sortSelectOpen || !visible) return;
    const handleClickOutside = (e: MouseEvent) => {
      if (sortSelectRef.current && !sortSelectRef.current.contains(e.target as Node)) {
        setSortSelectOpen(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, [sortSelectOpen, visible]);

  const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setTempQuery(e.target.value);
  };

  const handleApply = () => {
    onSearchChange(tempQuery);
    onSortChange(tempSortIndex);
    onApply();
    onClose();
  };

  const handleCancel = () => {
    setTempQuery(searchQuery);
    setTempSortIndex(activeSortIndex);
    onClose();
  };

  return (
    <AnimatedBottomSheet
      title={tMenu("MenuFilterDrawer.Heading")}
      visible={visible}
      outDelay={150}
      onClick={onClose}
    >
      <div className="px-6 mt-5">
        {/* فیلتر: جستجو */}
        <div className="flex flex-col gap-2">
          <label className="text-sm2 text-foreground">
            {tMenu("MenuFilterDrawer.SelectContent.Label")}
          </label>
          <input
            type="text"
            value={tempQuery}
            onChange={handleSearchChange}
            placeholder={tMenu("MenuFilterDrawer.SelectContent.Placeholder")}
            className="w-full h-11 px-3 py-2.5 rounded-normal border border-border bg-container/29 focus:outline-none focus:ring-2 focus:ring-black text-xs!"
          />
        </div>
        {/* فیلتر: دارای کد تخفیف */}
        <div className="flex w-full mt-[23px] h-11 items-center justify-between gap-2 px-3 py-4 relative bg-container/29 rounded-xl border border-solid border-border cursor-pointer focus:outline-none focus:ring-2 focus:ring-black">
          <span className="inline-flex items-center gap-2.5 text-sm2">
            <TicketPercentIcon size={16} />
            {tMenu("MenuFilterDrawer.DiscountState")}
          </span>
          <Switch />
        </div>

        {/* مرتب‌سازی - Select با کلیک باز می‌شود */}
        <div className="mt-6" ref={sortSelectRef}>
          <label className="text-sm2 text-foreground block mb-3">
            {tMenu("MenuSortingDrawer.Heading")}
          </label>
          <button
            type="button"
            onClick={() => setSortSelectOpen((prev) => !prev)}
            className="w-full h-11 px-3 py-2.5 rounded-xl border border-border bg-container/29 flex items-center justify-between gap-2 text-right text-sm2 text-foreground focus:outline-none focus:ring-2 focus:ring-black"
          >
            <span>{tMenu(`MenuSortingDrawer.Options.${sortings[tempSortIndex]}`)}</span>
            <ChevronDown
              className={clsx("w-4 h-4 shrink-0 transition-transform", sortSelectOpen && "rotate-180")}
            />
          </button>
          {sortSelectOpen && (
            <div className="mt-1 rounded-xl border border-border bg-container/29 overflow-hidden">
              {sortings.map((value, index) => {
                const isActive = index === tempSortIndex;
                return (
                  <button
                    key={value}
                    type="button"
                    onClick={() => {
                      setTempSortIndex(index);
                      setSortSelectOpen(false);
                    }}
                    className={clsx(
                      "flex items-center justify-between w-full py-3 px-3 text-sm2 transition-colors text-right",
                      isActive ? "text-primary font-semibold bg-primary/10" : "text-foreground hover:bg-muted/50"
                    )}
                  >
                    <span>{tMenu(`MenuSortingDrawer.Options.${value}`)}</span>
                  </button>
                );
              })}
            </div>
          )}
        </div>
      </div>
      <hr className="text-white/40 mt-12" />
      <div className="px-9 pt-6 flex justify-between gap-[22px]">
        <div className="w-full">
          <Button className="dark:bg-white! dark:text-black!" onClick={handleApply}>{tMenu("MenuFilterDrawer.ButtonOk")}</Button>
        </div>
        <div className="w-full">
          <Button className="bg-disabled! text-disabled-text!" onClick={handleCancel}>
            {tMenu("MenuFilterDrawer.ButtonCancel")}
          </Button>
        </div>
      </div>
    </AnimatedBottomSheet>
  );
};

export default MenuFilterDrawer;
