'use client';
import { FC, useState, useEffect } from "react";
import { MenuProps } from "@/validations/mutual/dashboard/props";
import { langGetKey } from "@/lib/langGet";
import { parseURlFormString } from "@/lib/menuGet";
import { menuTranslation } from "@/languages/mutual/menu"
import FirstLayerDropdown from "./firstLayerComponent";
import SecondLayerDropdown from "./secondLayerComponent";
import ThirdLayerDropdown from "./thirdLayerComponent";

// Define types for menu structure
type ThirdLayerItem = Record<string, any>;
type SecondLayerItems = Record<string, ThirdLayerItem>;
type FirstLayerItems = Record<string, SecondLayerItems>;
type MenuStructure = FirstLayerItems;



// Helper function to get translation for a URL path
const getMenuTranslation = (translations: any, urlPath: string) => {
    // Try exact match first
    if (translations[urlPath]) {
        return translations[urlPath];
    }

    // Remove leading slash if present for lookup
    const cleanPath = urlPath.startsWith('/') ? urlPath.substring(1) : urlPath;
    if (translations[cleanPath]) {
        return translations[cleanPath];
    }

    // Add leading slash if not present for lookup
    const pathWithSlash = urlPath.startsWith('/') ? urlPath : `/${urlPath}`;
    if (translations[pathWithSlash]) {
        return translations[pathWithSlash];
    }

    // Try to find the closest matching path
    const keys = Object.keys(translations);
    for (const key of keys) {
        // Remove leading slash for comparison
        const cleanKey = key.startsWith('/') ? key.substring(1) : key;
        const cleanUrlPath = urlPath.startsWith('/') ? urlPath.substring(1) : urlPath;

        if (cleanUrlPath.includes(cleanKey) || cleanKey.includes(cleanUrlPath)) {
            return translations[key];
        }
    }

    // If no match found, return the last part of the URL as fallback
    const parts = urlPath.split('/');
    return parts[parts.length - 1] || urlPath;
};

const MenuComponent: FC<MenuProps> = ({ lang, availableApplications, activePageUrl }) => {

    const [expandedFirstLayer, setExpandedFirstLayer] = useState<string | null>(null);
    const [expandedSecondLayer, setExpandedSecondLayer] = useState<string | null>(null);
    const [menuStructure, setMenuStructure] = useState<MenuStructure>({});

    const menuTranslationWLang = menuTranslation[lang];
    const activePathLayers = parseURlFormString(activePageUrl).data;
    const activeFirstLayer = activePathLayers[0] || null;
    const activeSecondLayer = activePathLayers[1] || null;
    const activeThirdLayer = activePathLayers.slice(2, activePathLayers.length).join("/");

    useEffect(() => {
        const newMenuStructure: MenuStructure = {};
        availableApplications.forEach(appPath => {
            const cleanPath = appPath.startsWith('/') ? appPath.substring(1) : appPath;
            const pathParts = cleanPath.split('/');
            if (pathParts.length >= 3) {
                const firstLayer = pathParts[0];
                const secondLayer = pathParts[1];
                const thirdLayer = pathParts.slice(2).join('/');
                if (!newMenuStructure[firstLayer]) { newMenuStructure[firstLayer] = {} }
                if (!newMenuStructure[firstLayer][secondLayer]) { newMenuStructure[firstLayer][secondLayer] = {} }
                newMenuStructure[firstLayer][secondLayer][thirdLayer] = true;
            }
        });
        setMenuStructure(newMenuStructure);
    }, [availableApplications]);

    useEffect(() => { if (activeFirstLayer) { setExpandedFirstLayer(activeFirstLayer); if (activeSecondLayer) { setExpandedSecondLayer(activeSecondLayer) } } }, [activeFirstLayer, activeSecondLayer]);

    const handleFirstLayerClick = (key: string) => { if (expandedFirstLayer === key) { setExpandedFirstLayer(null); setExpandedSecondLayer(null) } else { setExpandedFirstLayer(key); setExpandedSecondLayer(null) } };
    const handleSecondLayerClick = (key: string) => { if (expandedSecondLayer === key) { setExpandedSecondLayer(null) } else { setExpandedSecondLayer(key) } };

    const renderThirdLayerItems = (firstLayerKey: string, secondLayerKey: string, thirdLayerItems: ThirdLayerItem) => {
        const baseUrl = `/${firstLayerKey}/${secondLayerKey}`;
        return Object.keys(thirdLayerItems).map(thirdLayerKey => {
            const isActive = activeFirstLayer === firstLayerKey && activeSecondLayer === secondLayerKey && activeThirdLayer === thirdLayerKey;
            const mergeUrl = `${baseUrl}/${thirdLayerKey}`;
            const url = `/${lang}${baseUrl}/${thirdLayerKey}`;
            console.log('mergeUrl', mergeUrl);
            return <div key={`${thirdLayerKey}-item`} className="ml-2 my-1"><ThirdLayerDropdown isActive={isActive} innerText={getMenuTranslation(menuTranslationWLang, mergeUrl)} url={url} /></div>
        });
    };

    const renderSecondLayerItems = (firstLayerKey: string, secondLayerItems: SecondLayerItems) => {
        return Object.entries(secondLayerItems).map(([secondLayerKey, thirdLayerItems]) => {
            const isActive = activeFirstLayer === firstLayerKey && activeSecondLayer === secondLayerKey;
            const isExpanded = expandedSecondLayer === secondLayerKey;
            const mergeUrl = `/${firstLayerKey}/${secondLayerKey}`;
            console.log('mergeUrl', mergeUrl);
            return (
                <div key={`${secondLayerKey}-item`} className="ml-2 my-1">
                    <SecondLayerDropdown isActive={isActive} isExpanded={isExpanded} innerText={getMenuTranslation(menuTranslationWLang, mergeUrl)} onClick={() => handleSecondLayerClick(secondLayerKey)} />
                    {isExpanded && (<div className="ml-2 mt-1">{renderThirdLayerItems(firstLayerKey, secondLayerKey, thirdLayerItems)}</div>)}
                </div>
            );
        });
    };

    const renderFirstLayerItems = () => {
        return Object.entries(menuStructure).map(([firstLayerKey, secondLayerItems]) => {
            const isActive = activeFirstLayer === firstLayerKey;
            const isExpanded = expandedFirstLayer === firstLayerKey;
            const mergeUrl = `/${firstLayerKey}`;
            console.log('mergeUrl', mergeUrl);
            return (
                <div key={`${firstLayerKey}-item`} className="mb-2">
                    <FirstLayerDropdown isActive={isActive} isExpanded={isExpanded} innerText={getMenuTranslation(menuTranslationWLang, mergeUrl)} onClick={() => handleFirstLayerClick(firstLayerKey)} />
                    {isExpanded && (<div className="mt-1">{renderSecondLayerItems(firstLayerKey, secondLayerItems)}</div>)}
                </div>
            );
        });
    };

    return (
        <div className="fixed top-24 p-5 left-0 right-0 w-80 border-emerald-150 border-r-2 overflow-y-auto h-[calc(100vh-6rem)]">
            <div className="flex flex-col">
                {renderFirstLayerItems()}
            </div>
        </div>
    );
};



export default MenuComponent;
