'use client';
import { FC } from "react";
import { DropdownMenuItem } from "@/components/mutual/shadcnui/dropdown-menu";

interface LanguageSelectionItemProps {
    activeLang: string,
    buttonsLang: string,
    refUrl: string,
    innerText: string,
    onlineData: any,
    onlineLoading: boolean,
    onlineError: any,
    refreshOnline: () => Promise<void>,
    updateOnline: (newOnline: any) => Promise<boolean>
}

const RenderButtonComponent: FC<LanguageSelectionItemProps> = (
    { activeLang, buttonsLang, refUrl, innerText, onlineData, onlineLoading, onlineError, refreshOnline, updateOnline }) => {
    const setOnlineObject = async () => {
        if (!onlineData || onlineLoading) return;

        try {
            console.log("Updating language to:", buttonsLang);
            const success = await updateOnline({
                ...onlineData,
                lang: buttonsLang,
                lastAction: new Date()
            });

            if (success) {
                console.log("Language updated successfully");
                await refreshOnline();
            } else {
                console.error("Failed to update language");
            }
        } catch (error) {
            console.error("Error updating language:", error);
        }
    }

    return (
        <DropdownMenuItem
            onClick={setOnlineObject}
            className="flex w-full h-12 items-center justify-center text-center text-md cursor-pointer">
            {innerText}
        </DropdownMenuItem>
    )
}

const LanguageSelectionItem: React.FC<LanguageSelectionItemProps> = ({ activeLang, buttonsLang, refUrl, innerText, onlineData, onlineLoading, onlineError, refreshOnline, updateOnline }) => {

    const currentLang = onlineData?.lang || activeLang;
    const isActive = buttonsLang !== currentLang;
    const RenderButtonProp = {
        refUrl,
        innerText,
        activeLang,
        buttonsLang,
        onlineData,
        onlineLoading,
        onlineError,
        refreshOnline,
        updateOnline
    }

    // Only render the button if it's not the current language
    return (
        <>
            {isActive ? (
                <div><RenderButtonComponent {...RenderButtonProp} /></div>
            ) : (
                <DropdownMenuItem
                    disabled={!isActive}
                    className="flex w-full h-12 items-center justify-center text-center text-md opacity-50 cursor-not-allowed">
                    {innerText}
                </DropdownMenuItem>
            )}
        </>
    )
}

export default LanguageSelectionItem;
