import Link from "next/link";
import { X, List, ChevronDown, ChevronUp } from "lucide-react";
import { useState, useEffect } from "react";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { useTranslation } from "react-i18next";
import { isRtl } from "@/lib/direction";
import { useCategory } from "@/context/helpers/category";

function MobileCategoryItem({ category, rtl, onLinkClick }) {
  const [isExpanded, setIsExpanded] = useState(false);
  const children = category.children;
  const hasChildren = children && children.length > 0;

  return (
    <div className="w-full">
      <div className="flex items-center justify-between w-full border-b border-gray-100 dark:border-gray-700 last:border-b-0">
        <Link
          className={`flex-1 text-lg py-3 ${rtl ? "text-right" : "text-left"}`}
          href={`/categories/${category.id}`}
          onClick={onLinkClick}
        >
          {category.name}
        </Link>
        {hasChildren && (
          <button
            onClick={() => setIsExpanded(!isExpanded)}
            className="p-4 cursor-pointer"
          >
            {isExpanded ? (
              <ChevronUp className="w-6 h-6 text-mainColor" />
            ) : (
              <ChevronDown className="w-6 h-6 text-gray-400" />
            )}
          </button>
        )}
      </div>
      {hasChildren && isExpanded && (
        <div
          className={`border-gray-200 dark:border-gray-700 ${rtl ? "mr-4 border-r-2" : "ml-4 border-l-2"}`}
        >
          {children.map((child) => (
            <MobileCategoryItem
              key={child.id}
              category={child}
              rtl={rtl}
              onLinkClick={onLinkClick}
            />
          ))}
        </div>
      )}
    </div>
  );
}

// Mobile-only icon button used in the header
export default function MobileIconButton({ iconSrc, alt }) {
  const [open, setOpen] = useState(false);
  const [showCategories, setShowCategories] = useState(false);
  const { t } = useTranslation("header");
  const { categoryChildren, getCategories } = useCategory();
  const rtl = isRtl();

  useEffect(() => {
    if (open) {
      getCategories();
    }
  }, [open, getCategories]);

  const menuItems = [
    { href: "/", label: t("menu.home") },
    { label: t("categories"), isCategoryTrigger: true },
    { href: "/about", label: t("menu.about") },
    { href: "/contact", label: t("menu.contact") },
    { href: "/myOrders", label: t("menu.orders") },
  ];

  return (
    <div className="block lg:hidden ">
      <DropdownMenu
        dir={rtl ? "rtl" : "ltr"}
        open={open}
        onOpenChange={(newOpen) => {
          setOpen(newOpen);
          if (!newOpen) setShowCategories(false);
        }}
      >
        <DropdownMenuTrigger
          aria-label={open ? t("a11y.closeMenu") : t("a11y.openMenu")}
          className="p-2 rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-300 cursor-pointer"
        >
          {open ? <X className="w-6 h-6" /> : <List className="w-6 h-6" />}
        </DropdownMenuTrigger>
        <DropdownMenuContent
          dir={rtl ? "rtl" : "ltr"}
          align={rtl ? "end" : "start"}
          side="bottom"
          sideOffset={8}
          className={`top-0 ${
            rtl ? "right-0" : "left-0"
          } w-screen h-screen m-0 rounded-none border-0 p-4 bg-white dark:bg-gray-800 overflow-y-auto`}
        >
          {menuItems.map((item) => {
            if (item.isCategoryTrigger) {
              return (
                <div key="categories-section" className="w-full">
                  <button
                    onClick={() => setShowCategories(!showCategories)}
                    className={`flex items-center justify-between w-full text-lg py-4 border-b border-gray-600 dark:border-gray-400 last:border-b-0 cursor-pointer ${
                      rtl ? "text-right flex-row" : "text-left"
                    }`}
                  >
                    <span>{item.label}</span>
                    {showCategories ? (
                      <ChevronUp className="w-8 h-8 text-mainColor" />
                    ) : (
                      <ChevronDown className="w-8 h-8 text-gray-400" />
                    )}
                  </button>
                  {showCategories && (
                    <div className="w-full animate-in fade-in slide-in-from-top-1 duration-200">
                      {categoryChildren?.map((category) => (
                        <MobileCategoryItem
                          key={category.id}
                          category={category}
                          rtl={rtl}
                          onLinkClick={() => setOpen(false)}
                        />
                      ))}
                    </div>
                  )}
                </div>
              );
            }
            return (
              <DropdownMenuItem key={item.href} className="p-0">
                <Link
                  className={`block w-full text-lg py-4 border-b border-gray-600 dark:border-gray-400 last:border-b-0 ${
                    rtl ? "text-right" : "text-left"
                  }`}
                  href={item.href}
                  onClick={() => setOpen(false)}
                >
                  {item.label}
                </Link>
              </DropdownMenuItem>
            );
          })}
        </DropdownMenuContent>
      </DropdownMenu>
    </div>
  );
}
