'use client';
import { useState, type JSX } from 'react';
import { INavItem } from '../lib/data';
import { ChevronDown, ChevronRight } from 'lucide-react';
import Link from 'next/link';
import { AnimatePresence, motion } from 'framer-motion';
import useFilterStore from '@/shared/store/filterStore';

interface INavMenuItemProps {
  item: INavItem;
}

const NavMenuItem = ({ item }: INavMenuItemProps): JSX.Element => {
  const [isOpen, setIsOpen] = useState(false);
  const { setCategoryId, setCurrentPage } = useFilterStore();

  const handleSelectCategory = (id: number | null) => {
    setCategoryId(id);
    setCurrentPage(1);
  };
  return (
    <li
      onMouseEnter={() => setIsOpen(true)}
      onMouseLeave={() => setIsOpen(false)}
      className="group relative z-30"
    >
      <Link
        href={item.link || ''}
        onClick={() => {
          if (item.link === '/products') {
            handleSelectCategory(null);
          }
        }}
        className="flex justify-between duration-300 h-[50px] relative items-center gap-1 cursor-pointer text-[16px] hover:text-accent font-semibold text-muted"
      >
        <span>{item.title}</span>
        {item.children && (
          <ChevronDown size="16px" strokeWidth={3} className="pt-[2px]" />
        )}
        <div className="absolute right-0 w-0 bottom-0 h-[3px] group-hover:w-[102%] duration-500 bg-gradient-to-r from-primary to-secondary" />
      </Link>

      <AnimatePresence>
        {item.children && isOpen && (
          <motion.div
            initial={{ opacity: 0, scaleY: 0, originY: 0 }}
            animate={{ opacity: 1, scaleY: 1, originY: 0 }}
            exit={{ opacity: 0, scaleY: 0, originY: 0 }}
            transition={{ duration: 0.4 }}
            className="absolute bottom-0 left-0 text-[14px] font-semibold text-muted bg-white min-w-[200px] translate-y-[100%] z-40 p-[10px] border shadow-sm rounded-sm w-max overflow-hidden"
            style={{ transformOrigin: 'left' }}
          >
            {item.children.map((child) => (
              <Link
                href={child.link || ''}
                key={child.id}
                onClick={() => {
                  if (item.link === '/products') {
                    handleSelectCategory(child.id);
                  }
                  setIsOpen(false);
                }}
                className="cursor-pointer hover:text-accent duration-300 py-[7px] px-[10px] group/submenu hover:bg-muted-foreground rounded-sm flex justify-between items-center"
              >
                <span>{child.title}</span>
                <ChevronRight
                  size="14px"
                  strokeWidth={3}
                  className="pt-[2px] text-primary scale-0 group-hover/submenu:scale-100 transition-transform duration-500"
                />
              </Link>
            ))}
          </motion.div>
        )}
      </AnimatePresence>
    </li>
  );
};

export default NavMenuItem;
