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

import {
    DownloadCloudIcon,
    GlobeIcon,
    LogOutIcon,
    MenuIcon,
    MoonIcon,
    SunIcon,
    User2Icon,
} from 'lucide-react';

import { MenuItemType } from '@/api/types';
import { confirmAlertRef } from '@/components/ConfirmAlert';
import { exportDialogRef } from '@/components/ExportDialog';
import MenuItem from '@/components/MenuItem';
import SvgIcon from '@/components/SvgIcon';
import { Button } from '@/components/ui/button';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuGroup,
    DropdownMenuItem,
    DropdownMenuSeparator,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { GridRow } from '@/components/ui/grid';
import { Label } from '@/components/ui/label';
import {
    MobileBlockTitle,
    MobileLink,
    MobileList,
    MobileListItem,
    MobileNavbar,
    MobilePage,
    MobilePanel,
    MobilePopover,
} from '@/components/ui/mobile';
import { Skeleton } from '@/components/ui/skeleton';
import { useAppConfig } from '@/contexts/AppConfigContext';
import { Lang } from '@/lang/Lang';
import { EventEmitter } from '@/utils/event';

import { useMainPage } from '../contexts/MainPageContext';
import { profileDialogRef } from './ProfileDialog/ProfileDialog';

export const openMobileMenu = () => {
    EventEmitter.execute('mobileMenuOpened');
}

export const AppSidebar = () => {

    const { menu, selectMenu, setSelectMenu, profile } = useMainPage();
    const { color, title, icon, initLoaded, isDarkTheme, toggleTheme } = useAppConfig();


    const onLogOut = () => {
        confirmAlertRef.current?.open({
            title: Lang.key('log_out_title'),
            description: Lang.key('log_out_description'),
            buttons: [
                { label: Lang.key('cancel'), onClick: () => { } },
                {
                    label: Lang.key('log_out'), onClick: () => {

                        localStorage.clear();
                        window.location.reload();
                    }
                },
            ]
        });
    }

    const { isMobile, openDialog } = useAppConfig();

    const [popoverOpened, setPopoverOpened] = useState(false);

    const popoverTargetRef = useRef<HTMLDivElement>(null);


    const onMenuItemClick = (item: MenuItemType) => {

        setMobileMenuOpened(false);

        if (item.single) {

            openDialog({
                modalKey: `collection_view_${item?.collection}_single`,
                collection: item?.collection ?? "",
                _id: 'single'
            });

            return;

        }

        setSelectMenu(item);
    }

    useEffect(() => {
        if (isMobile) {
            EventEmitter.subscribe('mobileMenuOpened', () => {
                setMobileMenuOpened(true);
            });
            return () => {
                EventEmitter.delete('mobileMenuOpened');
            };
        }
    }, [isMobile]);

    const [mobileMenuOpened, setMobileMenuOpened] = useState(false);

    if (isMobile) {
        return <>
            <MobilePanel
                floating
                side="left"

                opened={mobileMenuOpened} onBackdropClick={() => setMobileMenuOpened(false)}>
                <MobilePage>
                    <MobileNavbar

                        left={<>

                            {initLoaded ? <div className='flex items-center gap-2 px-2'>

                                <img src={icon}
                                    className='w-8 h-8 rounded-sm'
                                    alt="logo" />
                                <div className='text-base font-medium'>{title}</div>

                            </div> : <div>
                                <Skeleton className='w-8 h-8 rounded-sm' />
                                <Skeleton className='w-24 h-4' />

                            </div>}
                        </>}

                        right={<MobileLink
                            ref={popoverTargetRef}
                            iconOnly onClick={() => setPopoverOpened(true)}>
                            <MenuIcon />
                        </MobileLink>}

                    >



                    </MobileNavbar>

                    {menu.length > 0 ? <ul>{menu?.map((item) => {
                        if (item.children) {


                            return <div className='mb-4'>
                                <MobileBlockTitle className='mb-0'>{item.label}</MobileBlockTitle>
                                <ul>

                                    {item.children.map((item) => (
                                        <MenuItem

                                            onClick={() => {
                                                onMenuItemClick(item);
                                            }}
                                            active={selectMenu?.key == item.key}
                                            media={<SvgIcon
                                                color={selectMenu?.key == item.key ? color : undefined}
                                                icon={item.icon} />}
                                            label={<span
                                                style={{
                                                    color: selectMenu?.key == item.key ? color : undefined
                                                }}
                                            >{item.label}</span>}

                                            key={item.key ?? ''}>

                                        </MenuItem>
                                    ))}

                                </ul>
                            </div>


                        }

                        return <MenuItem
                            onClick={() => {
                                onMenuItemClick(item);
                            }}

                            active={selectMenu?.key == item.key}

                            media={<SvgIcon
                                color={selectMenu?.key == item.key ? color : undefined}

                                icon={item.icon} />}
                            label={<span
                                style={{
                                    color: selectMenu?.key == item.key ? color : undefined
                                }}
                            >{item.label}</span>}


                            key={item.key ?? ''}>

                        </MenuItem>



                    })}</ul> : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map((item) => {
                        return <Skeleton className='w-full h-8 mb-2' key={item} />
                    })}


                </MobilePage>

            </MobilePanel>

            <MobilePopover opened={popoverOpened}
                target={popoverTargetRef.current}
                onBackdropClick={() => setPopoverOpened(false)}>
                <MobileList nested>
                    <MobileListItem
                        title={Lang.key('profile')}
                        link
                        chevron={false}
                        media={<User2Icon />}
                        onClick={() => {
                            setPopoverOpened(false);
                            setMobileMenuOpened(false);
                            profileDialogRef.current?.open();
                        }}
                    />
                    <MobileListItem
                        title={Lang.key('export_data')}
                        link
                        chevron={false}
                        media={<DownloadCloudIcon />}
                        onClick={() => {
                            setPopoverOpened(false);
                            exportDialogRef.current?.open();
                        }}
                    />
                    <MobileListItem
                        title={isDarkTheme ? Lang.key('light_theme') : Lang.key('dark_theme')}
                        link
                        chevron={false}
                        media={isDarkTheme ? <SunIcon /> : <MoonIcon />}
                        onClick={() => {
                            toggleTheme();
                        }}
                    />
                    <MobileListItem
                        title={Lang.getCurrentLang() != "ru" ? "Переключить на русский" : "Switch to English"}
                        link
                        chevron={false}
                        media={<GlobeIcon />}
                        onClick={() => {
                            Lang.manualChangeLang(Lang.getCurrentLang() == "ru" ? "en" : "ru");
                        }}
                    />
                    <MobileListItem
                        title={Lang.key('log_out')}
                        link
                        chevron={false}
                        media={<LogOutIcon />}
                        onClick={() => {
                            setPopoverOpened(false);
                            setMobileMenuOpened(false);
                            onLogOut();
                        }}
                    />
                </MobileList>
            </MobilePopover>
        </>
    }

    return <>


        <GridRow autoSize className='flex flex-col'>
            <div className='flex items-center justify-between p-4'>
                <div className='flex items-center gap-2 px-2'>

                    {initLoaded ? <>

                        <img src={icon}
                            className='w-8 h-8 rounded-sm'
                            alt="logo" />
                        <div className='text-base font-medium'>{title}</div>

                    </> : <>
                        <Skeleton className='w-8 h-8 rounded-sm' />
                        <Skeleton className='w-24 h-4' />

                    </>}


                </div>

                {initLoaded ? <DropdownMenu>
                    <DropdownMenuTrigger asChild>
                        <Button variant="outline" size="icon-sm">
                            <MenuIcon />
                        </Button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent className="w-56" align="start">

                        <DropdownMenuGroup>
                            <DropdownMenuItem

                                onClick={() => {
                                    profileDialogRef.current?.open();
                                }}
                            >
                                <User2Icon />  {Lang.key('profile')}

                            </DropdownMenuItem>


                            <DropdownMenuItem onClick={() => {
                                exportDialogRef.current?.open();
                            }}>
                                <DownloadCloudIcon />  {Lang.key('export_data')}

                            </DropdownMenuItem>

                        </DropdownMenuGroup>
                        <DropdownMenuSeparator />
                        <DropdownMenuItem onClick={toggleTheme}>
                            {isDarkTheme ? <SunIcon /> : <MoonIcon />}  {isDarkTheme ? Lang.key('light_theme') : Lang.key('dark_theme')}
                        </DropdownMenuItem>
                        <DropdownMenuItem onClick={() => {
                            Lang.manualChangeLang(Lang.getCurrentLang() == "ru" ? "en" : "ru");
                        }}>
                            <GlobeIcon />  {Lang.getCurrentLang() != "ru" ? "Переключить на русский" : "Switch to English"}
                        </DropdownMenuItem>

                        <DropdownMenuSeparator />
                        <DropdownMenuItem onClick={onLogOut}>
                            <LogOutIcon />  {Lang.key('log_out')}

                        </DropdownMenuItem>
                    </DropdownMenuContent>
                </DropdownMenu>
                    : <Skeleton className='w-8 h-8' />}
            </div>
        </GridRow>
        <GridRow className='flex flex-col p-4'>

            {menu.length > 0 ? <>{menu?.map((item) => {
                if (item.children) {


                    return <div className='mb-4'>
                        <Label>{item.label}</Label>
                        <div>

                            {item.children.map((item) => (
                                <MenuItem

                                    onClick={() => {
                                        onMenuItemClick(item);
                                    }}
                                    active={selectMenu?.key == item.key}
                                    media={<SvgIcon
                                        color={selectMenu?.key == item.key ? color : undefined}
                                        icon={item.icon} />}
                                    label={<span
                                        style={{
                                            color: selectMenu?.key == item.key ? color : undefined
                                        }}
                                    >{item.label}</span>}

                                    key={item.key ?? ''}>

                                </MenuItem>
                            ))}

                        </div>
                    </div>


                }

                return <MenuItem
                    onClick={() => {
                        onMenuItemClick(item);
                    }}

                    active={selectMenu?.key == item.key}

                    media={<SvgIcon
                        color={selectMenu?.key == item.key ? color : undefined}

                        icon={item.icon} />}
                    label={<span
                        style={{
                            color: selectMenu?.key == item.key ? color : undefined
                        }}
                    >{item.label}</span>}


                    key={item.key ?? ''}>

                </MenuItem>



            })}



            </> : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map((item) => {
                return <Skeleton className='w-full h-8 mb-2' key={item} />
            })}

        </GridRow>
        <GridRow autoSize >
            <div></div>
        </GridRow>


    </>




}