'use client';
import React, { FC, useEffect, useState } from "react";
import { menuTranslation } from "@/languages/mutual/menu";
import FirstLayerDropdown from "./firstLayerComponent";
import SecondLayerDropdown from "./secondLayerComponent";
import ThirdLayerDropdown from "./thirdLayerComponent";
import {
    TranslationItem,
    ThirdLayerItem,
    SecondLayerItems,
    MenuStructure,
    MenuItemsSectionProps,
} from "./types";

const menuStaticTranslation = {
    tr: { menu: "Menü" },
    en: { menu: "Menu" }
}

const MenuItemsSection: FC<MenuItemsSectionProps> = ({ availableApplications, activePageUrl, lang, prefix }) => {
    const [expandedFirstLayer, setExpandedFirstLayer] = useState<string | null>(null);
    const [expandedSecondLayer, setExpandedSecondLayer] = useState<string | null>(null);
    const [menuStructure, setMenuStructure] = useState<MenuStructure>({});
    const [activeFirstLayer, setActiveFirstLayer] = useState<string | null>(null);
    const [activeSecondLayer, setActiveSecondLayer] = useState<string | null>(null);
    const [activeThirdLayer, setActiveThirdLayer] = useState<string | null>(null);


    useEffect(() => {
        const newMenuStructure: MenuStructure = {};
        const menuTranslationWLang = menuTranslation[lang as keyof typeof menuTranslation];
        const activeParsedLayer = (menuTranslationWLang[activePageUrl as keyof typeof menuTranslationWLang] as unknown as TranslationItem[]) || [];
        availableApplications.forEach((appPath: string) => {
            const pathTranslation = menuTranslationWLang[appPath as keyof typeof menuTranslationWLang] as unknown as TranslationItem[] | undefined;
            if (pathTranslation && pathTranslation.length >= 3) {
                const firstLayer = pathTranslation[0]?.key || '';
                const secondLayer = pathTranslation[1]?.key || '';
                const thirdLayer = pathTranslation[2]?.key || '';
                if (!newMenuStructure[firstLayer]) { newMenuStructure[firstLayer] = {} }
                if (!newMenuStructure[firstLayer][secondLayer]) { newMenuStructure[firstLayer][secondLayer] = {} }
                newMenuStructure[firstLayer][secondLayer][thirdLayer] = { path: appPath, translation: pathTranslation };
            }
        });

        setMenuStructure(newMenuStructure);
        setActiveFirstLayer(activeParsedLayer[0]?.key || null);
        setActiveSecondLayer(activeParsedLayer[1]?.key || null);
        setActiveThirdLayer(activeParsedLayer[2]?.key || null);
    }, [availableApplications, lang, activePageUrl]);

    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) => {
        return Object.entries(thirdLayerItems).map(([thirdLayerKey, itemData]) => {
            const isActive = activeFirstLayer === firstLayerKey && activeSecondLayer === secondLayerKey && activeThirdLayer === thirdLayerKey;
            const url = itemData?.path || '';
            const translation = itemData?.translation || [];
            const displayText = translation[2]?.value || thirdLayerKey;

            return <div key={`${thirdLayerKey}-item`} className="ml-2 my-1"><ThirdLayerDropdown isActive={isActive} innerText={displayText} url={`${prefix || ''}${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 anyThirdLayerItem = Object.values(thirdLayerItems)[0];
            const translation = anyThirdLayerItem?.translation || [];
            const displayText = translation[1]?.value || secondLayerKey;

            return (
                <div key={`${secondLayerKey}-item`} className="ml-2 my-1">
                    <SecondLayerDropdown isActive={isActive} isExpanded={isExpanded} innerText={displayText} 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 anySecondLayer = Object.values(secondLayerItems)[0] || {};
            const anyThirdLayerItem = Object.values(anySecondLayer)[0];
            const translation = anyThirdLayerItem?.translation || [];
            const displayText = translation[0]?.value || firstLayerKey;

            return (
                <div key={`${firstLayerKey}-item`} className="mb-2">
                    {<FirstLayerDropdown isActive={isActive} isExpanded={isExpanded} innerText={displayText} onClick={() => handleFirstLayerClick(firstLayerKey)} />}
                    {isExpanded && <div className="mt-1">{renderSecondLayerItems(firstLayerKey, secondLayerItems)}</div>}
                </div>
            );
        });
    };

    return (
        <>
            <div className="flex flex-col">
                <div className="mt-1 flex justify-center"><h3 className="text-sm font-semibold mb-1">{menuStaticTranslation[lang as keyof typeof menuStaticTranslation].menu}</h3></div>
                <br />
                {
                    availableApplications.length !== 0 && <div className="">{renderFirstLayerItems()}</div>
                }
                {
                    availableApplications.length === 0 && <div>
                        <div className="flex justify-center items-center h-full">
                            <div className="text-center text-gray-500 dark:text-gray-400">
                                <p className="text-sm">No menu items available</p>
                                <p className="text-xs mt-1">Please check your permissions or contact an administrator</p>
                            </div>
                        </div>
                    </div>
                }
            </div>
        </>
    )

};

export default MenuItemsSection;
