'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";

type TranslationItem = { value: string; key: string };
type ThirdLayerItemData = { path: string; translation: TranslationItem[] };
type ThirdLayerItem = Record<string, ThirdLayerItemData>;
type SecondLayerItems = Record<string, ThirdLayerItem>;
type FirstLayerItems = Record<string, SecondLayerItems>;
type MenuStructure = FirstLayerItems;

interface MenuItemsSectionProps {
    availableApplications: string[];
    activePageUrl: string;
    lang: string;
    prefix?: string;
}

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 menuTranslationWLang = menuTranslation[lang as keyof typeof menuTranslation];
    const activeParsedLayer = (menuTranslationWLang[activePageUrl as keyof typeof menuTranslationWLang] as unknown as TranslationItem[]) || [];
    const activeFirstLayer = activeParsedLayer[0] ? activeParsedLayer[0].key : null;
    const activeSecondLayer = activeParsedLayer[1] ? activeParsedLayer[1].key : null;
    const activeThirdLayer = activeParsedLayer[2] ? activeParsedLayer[2].key : null;

    useEffect(() => {
        const newMenuStructure: MenuStructure = {};
        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] ? pathTranslation[0].key : '';
                const secondLayer = pathTranslation[1] ? pathTranslation[1].key : '';
                const thirdLayer = pathTranslation[2] ? 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);
    }, [availableApplications, menuTranslationWLang]);

    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 ? itemData.path || '' : '';
            const translation = itemData ? 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 ? 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 = anySecondLayer ? Object.values(anySecondLayer)[0] : null;
            const translation = anyThirdLayerItem ? 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="mt-1"><h3 className="text-sm font-semibold mb-1">{menuStaticTranslation[lang as keyof typeof menuStaticTranslation].menu}</h3>{renderFirstLayerItems()}</div>;
};

export default MenuItemsSection;
