import React, { useState, useEffect } from 'react';

interface MenuItem {
    menu_item_id: string;
    menu_title: string;
    menu_order: string;
    post_parent: string;
    actual_post_id: string;
    actual_post_title: string;
    post_type: string;
    post_status: string;
    slug: string;
    custom_url: string;
    object_type: string;
    parent_menu_item_id: string;
}

interface NestedMenuItem extends MenuItem {
    children?: NestedMenuItem[];
}

interface NavigationMenuProps {
    menuData: MenuItem[];
}

const NavigationMenu: React.FC<NavigationMenuProps> = ({ menuData }) => {
    const [nestedMenu, setNestedMenu] = useState<NestedMenuItem[]>([]);
    const [currentMenu, setCurrentMenu] = useState<string | null>(null);
    const [activeSubmenu, setActiveSubmenu] = useState<string | null>(null);

    // Transform flat array into nested structure
    useEffect(() => {
        const buildNestedMenu = (items: MenuItem[]): NestedMenuItem[] => {
            const itemMap = new Map<string, NestedMenuItem>();
            const rootItems: NestedMenuItem[] = [];

            // Create map of all items
            items.forEach(item => {
                itemMap.set(item.menu_item_id, { ...item, children: [] });
            });

            // Build hierarchy
            items.forEach(item => {
                const currentItem = itemMap.get(item.menu_item_id);
                if (!currentItem) return;

                if (item.parent_menu_item_id === "0") {
                    rootItems.push(currentItem);
                } else {
                    const parent = itemMap.get(item.parent_menu_item_id);
                    if (parent) {
                        if (!parent.children) parent.children = [];
                        parent.children.push(currentItem);
                    }
                }
            });

            // Sort by menu_order
            const sortByOrder = (items: NestedMenuItem[]): NestedMenuItem[] => {
                return items.sort((a, b) => parseInt(a.menu_order) - parseInt(b.menu_order));
            };

            const sortedRoots = sortByOrder(rootItems);
            sortedRoots.forEach(item => {
                if (item.children) {
                    item.children = sortByOrder(item.children);
                }
            });

            return sortedRoots;
        };

        setNestedMenu(buildNestedMenu(menuData));
    }, [menuData]);

    // Close menu when clicking outside
    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            if (!(event.target as Element).closest('.nav-menu-container')) {
                setCurrentMenu(null);
                setActiveSubmenu(null);
            }
        };

        document.addEventListener('click', handleClickOutside);
        return () => document.removeEventListener('click', handleClickOutside);
    }, []);

    const handleMenuEnter = (menuId: string, hasChildren: boolean) => {
        if (hasChildren) {
            setCurrentMenu(menuId);
            setActiveSubmenu(null);
        }
    };

    const handleMenuLeave = (item_id: string) => {
        // Small delay to allow moving to submenu
        if (item_id === currentMenu) {
            setCurrentMenu(null)
            setActiveSubmenu(null)
        }
        // setTimeout(() => {
        //     if (!document.querySelector('.nav-menu-container:hover')) {
        //         setCurrentMenu(null);
        //         setActiveSubmenu(null);
        //     }
        // }, 100);
    };

    const handleSubmenuEnter = (submenuId: string) => {
        setActiveSubmenu(submenuId);
    };

    const renderMenuItems = (items: NestedMenuItem[], level = 0) => {
        return items.map(item => {
            const hasChildren = item.children && item.children.length > 0;
            const isActive = currentMenu === item.menu_item_id;

            if (!hasChildren) {
                return (
                    <a
                        key={item.menu_item_id}
                        href={item.custom_url === "#" ? `/${item.slug}` : item.custom_url}
                        className="px-4 py-2 text-gray-700 hover:text-blue-600 hover:bg-gray-50 transition-colors duration-200 whitespace-nowrap"
                    >
                        {item.actual_post_title}
                    </a>
                );
            }

            return (
                <div
                    key={item.menu_item_id}
                    className="relative menu"
                    onMouseEnter={() => handleMenuEnter(item.menu_item_id, true)}
                    onMouseLeave={() => handleMenuLeave(item.menu_item_id)}
                >
                    <button
                        className="px-4 py-2 text-gray-700 hover:text-blue-600 hover:bg-gray-50 transition-colors duration-200 flex items-center gap-1 whitespace-nowrap"
                    >
                        {item.actual_post_title}
                        <svg
                            className={`w-4 h-4 transition-transform duration-200 ${isActive ? 'rotate-180' : ''}`}
                            fill="none"
                            stroke="currentColor"
                            viewBox="0 0 24 24"
                        >
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                        </svg>
                    </button>

                    {/* First level dropdown */}
                    {isActive && (
                        <div className="menu absolute left-0 top-full mt-1 w-64 bg-white shadow-lg rounded-lg py-2 z-50 border border-gray-100">
                            {item.children?.map(child => {
                                const childHasChildren = child.children && child.children.length > 0;
                                const isChildActive = activeSubmenu === child.menu_item_id;

                                return (
                                    <div
                                        key={child.menu_item_id}
                                        className="relative group"
                                        onMouseEnter={() => handleSubmenuEnter(child.menu_item_id)}
                                        onMouseLeave={() => setActiveSubmenu(null)}
                                    >
                                        {!childHasChildren ? (
                                            <a
                                                href={child.custom_url === "#" ? `/${child.slug}` : child.custom_url}
                                                className="block px-4 py-2 text-gray-700 hover:text-blue-600 hover:bg-gray-50 transition-colors duration-200"
                                            >
                                                {child.actual_post_title}
                                            </a>
                                        ) : (
                                            <>
                                                <div className="flex items-center justify-between px-4 py-2 text-gray-700 hover:text-blue-600 hover:bg-gray-50 transition-colors duration-200 cursor-pointer">
                                                    <span>{child.actual_post_title}</span>
                                                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                                                    </svg>
                                                </div>

                                                {/* Second level dropdown - appears to the right */}
                                                {isChildActive && (
                                                    <div className="absolute left-full top-0 ml-1 w-64 bg-white shadow-lg rounded-lg py-2 z-50 border border-gray-100">
                                                        {child.children?.map(grandChild => (
                                                            <a
                                                                key={grandChild.menu_item_id}
                                                                href={grandChild.custom_url === "#" ? `/${grandChild.slug}` : grandChild.custom_url}
                                                                className="block px-4 py-2 text-gray-700 hover:text-blue-600 hover:bg-gray-50 transition-colors duration-200"
                                                            >
                                                                {grandChild.actual_post_title}
                                                            </a>
                                                        ))}
                                                    </div>
                                                )}
                                            </>
                                        )}
                                    </div>
                                );
                            })}
                        </div>
                    )}
                </div>
            );
        });
    };

    return (
        <nav className="nav-menu-container relative bg-white shadow-sm">
            <div className="container mx-auto px-4">
                <div className="flex items-center space-x-1">
                    {renderMenuItems(nestedMenu)}
                </div>
            </div>
        </nav>
    );
};

export default NavigationMenu;