// CategoryMenu.tsx
"use client";

import { useState, useEffect, useRef } from "react";
import Link from "next/link";
import { useCategories } from "@/lib/hooks";
import { Skeleton } from "@/components/ui/skeleton";
import { ChevronRight } from "lucide-react";

interface CategoryMenuProps {
  isOpen: boolean;
  onClose: () => void;
}

export default function CategoryMenu({ isOpen, onClose }: CategoryMenuProps) {
  const [hoveredCategory, setHoveredCategory] = useState<number | null>(null);
  const { data: categories, isLoading } = useCategories();
  const menuRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!isOpen) return;

    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as HTMLElement;

      if (target.closest("[data-catalog-trigger]")) {
        return;
      }

      if (menuRef.current && !menuRef.current.contains(target)) {
        onClose();
      }
    };

    const timeoutId = setTimeout(() => {
      document.addEventListener("mousedown", handleClickOutside);
    }, 100);

    return () => {
      clearTimeout(timeoutId);
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [isOpen, onClose]);

  useEffect(() => {
    if (!isOpen) return;

    const handleEscape = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        onClose();
      }
    };

    document.addEventListener("keydown", handleEscape);
    return () => document.removeEventListener("keydown", handleEscape);
  }, [isOpen, onClose]);

  if (!isOpen) return null;

  const categoryList = categories || [];
  const activeCategory =
    hoveredCategory !== null ? categoryList[hoveredCategory] : null;

  return (
    <>
      {/* Overlay */}
      <div
        className="fixed inset-0 bg-black/30 backdrop-blur-sm z-30 animate-fade-in"
        onClick={onClose}
      />

      {/* Menu */}
      <div
        ref={menuRef}
        className="fixed left-0 right-0 top-16 z-40 bg-white border-b border-gray-200 rounded-b-lg shadow-2xl max-w-[1600px] mx-auto animate-slide-up"
      >
        <div className="mx-auto px-6">
          <div className="flex">
            <CategoryList
              categories={categoryList}
              isLoading={isLoading}
              onCategoryHover={setHoveredCategory}
              onCategoryClick={onClose}
              hoveredIndex={hoveredCategory}
            />

            {activeCategory?.children && (
              <SubcategoryList
                category={activeCategory}
                onSubcategoryClick={onClose}
              />
            )}
          </div>
        </div>
      </div>
    </>
  );
}

interface CategoryListProps {
  categories: any[];
  isLoading: boolean;
  onCategoryHover: (index: number) => void;
  onCategoryClick: () => void;
  hoveredIndex: number | null;
}

function CategoryList({
  categories,
  isLoading,
  onCategoryHover,
  onCategoryClick,
  hoveredIndex,
}: CategoryListProps) {
  return (
    <div className="w-[300px] border-r border-gray-200">
      <div className="max-h-[calc(100vh-5rem)] overflow-y-auto py-3">
        {isLoading
          ? Array.from({ length: 8 }).map((_, i) => (
              <div key={i} className="mx-4 my-2">
                <Skeleton className="h-12 rounded-lg" />
              </div>
            ))
          : categories.map((category, index) => (
              <Link
                key={category.id}
                href={`/category/${category.slug}?category_id=${category.id}`}
                onClick={onCategoryClick}
                onMouseEnter={() => onCategoryHover(index)}
                className={`flex items-center justify-between gap-3 mx-2 px-4 py-3.5 rounded-lg transition-all duration-200 group ${
                  hoveredIndex === index
                    ? "bg-gray-900 text-white shadow-md"
                    : "hover:bg-gray-100 text-gray-900"
                }`}
              >
                <div className="flex items-center gap-3">
                  {category.icon_class && (
                    <i
                      className={`${category.icon_class} text-xl ${
                        hoveredIndex === index ? "text-white" : "text-gray-700"
                      }`}
                    />
                  )}
                  <span className="font-medium">{category.name}</span>
                </div>
                {category.children && category.children.length > 0 && (
                  <ChevronRight
                    className={`h-4 w-4 transition-all duration-200 ${
                      hoveredIndex === index
                        ? "text-white translate-x-0.5"
                        : "text-gray-400 group-hover:text-gray-700"
                    }`}
                  />
                )}
              </Link>
            ))}
      </div>
    </div>
  );
}

interface SubcategoryListProps {
  category: any;
  onSubcategoryClick: () => void;
}

function SubcategoryList({
  category,
  onSubcategoryClick,
}: SubcategoryListProps) {
  return (
    <div className="flex-1 p-8 animate-fade-in">
      <div className="mb-6">
        <h3 className="text-2xl font-bold text-gray-900 mb-2">
          {category.name}
        </h3>
        <div className="h-1 w-32 bg-gray-900 rounded-full" />
      </div>

      <div className="grid grid-cols-3 gap-x-6 gap-y-3">
        {category.children?.map((subCategory: any) => (
          <Link
            key={subCategory.id}
            href={`/category/${subCategory.slug}?category_id=${subCategory.id}`}
            onClick={onSubcategoryClick}
            className="text-gray-700 hover:text-gray-900 text-sm py-2 px-3 hover:bg-gray-50 transition-all duration-200 font-medium group flex items-center gap-2"
          >
            <span className="flex-1">{subCategory.name}</span>
            <ChevronRight className="h-3.5 w-3.5 text-gray-400 opacity-0 group-hover:opacity-100 transition-all duration-200 -translate-x-1 group-hover:translate-x-0" />
          </Link>
        ))}
      </div>
    </div>
  );
}
