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

import { Chip } from 'konsta/react';
import {
    CreditCardIcon,
    DownloadCloudIcon,
    GlobeIcon,
    LogOutIcon,
    MenuIcon,
    MoonIcon,
    PanelLeftClose,
    SunIcon,
    User2Icon,
} from 'lucide-react';
import { RiLockPasswordFill } from 'react-icons/ri';

import { MenuItemType } from '@/api/types';
import MenuItem from '@/components/MenuItem';
import { ServerIcon } from '@/components/ServerIcon';
import { Badge } from '@/components/ui/badge';
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 {
    Menubar,
    MenubarContent,
    MenubarGroup,
    MenubarItem,
    MenubarMenu,
    MenubarTrigger,
} from '@/components/ui/menubar';
import {
    MobileBlockTitle,
    MobileLink,
    MobileList,
    MobileListItem,
    MobileNavbar,
    MobilePage,
    MobilePanel,
    MobilePopover,
} from '@/components/ui/mobile';
import { Skeleton } from '@/components/ui/skeleton';
import {
    balanceAndPaymentDialogRef,
} from '@/componentsRoot/BalanceAndPaymentDialog';
import { changeLangDialogRef } from '@/componentsRoot/ChangeLangDialog';
import { changePasswordDialogRef } from '@/componentsRoot/ChangePasswordDialog';
import { confirmAlertRef } from '@/componentsRoot/ConfirmAlert';
import { exportDialogRef } from '@/componentsRoot/ExportDialog';
import { Lang, useCanChangeLang } from '@/lang/Lang';
import { LL } from '@/lang/LL';
import useAppConfigStore, { useAppConfig } from '@/stores/appConfig';
import { useMainPage } from '@/stores/mainPage';
import { EventEmitter } from '@/utils/event';

import SidebarAlerts from './SidebarAlerts';
import SidebarProfileItems from './SidebarProfileItems';

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

const MenuBadge = ({ children }: { children: React.ReactNode }) => {

    const { isMobile } = useAppConfigStore();
    if (isMobile) {
        return <Chip>{children}</Chip>
    }


    return <Badge variant="default">{children}</Badge>

}

export const AppSidebar = ({ menubar, onCollapse }: { menubar?: boolean; onCollapse?: () => void }) => {

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


    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 } = useAppConfigStore();
    const { 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>

                    <SidebarAlerts />

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


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

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

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

                                            after={badges[item.key!] && <MenuBadge>{badges[item.key!]}</MenuBadge>}

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

                                        </MenuItem>
                                    ))}

                                </ul>
                            </div>


                        }

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

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

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

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

                            after={badges[item.key!] && <MenuBadge>{badges[item.key!]}</MenuBadge>}

                            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>

                    <SidebarProfileItems
                        variant="mobile"
                        onMobileAction={() => {
                            setPopoverOpened(false);
                            setMobileMenuOpened(false);
                        }}
                    />

                    {!!profile?.balances?.length && <MobileListItem
                        title={Lang.key('payment_and_balance')}
                        link
                        chevron={false}
                        media={<CreditCardIcon />}
                        onClick={() => {
                            setPopoverOpened(false);
                            setMobileMenuOpened(false);
                            balanceAndPaymentDialogRef.current?.open();
                        }}
                    />}


                    {profile?.changePassword && <MobileListItem
                        title={Lang.key('change_password')}
                        link
                        chevron={false}
                        media={<RiLockPasswordFill size={20} />}
                        onClick={() => {
                            setPopoverOpened(false);
                            setMobileMenuOpened(false);
                            changePasswordDialogRef.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();
                        }}
                    />
                    {initLoaded && canChangeLang && <MobileListItem
                        title={Lang.key('change_language')}
                        link
                        chevron={false}
                        media={<GlobeIcon />}
                        onClick={() => {
                            setPopoverOpened(false);
                            setMobileMenuOpened(false);
                            changeLangDialogRef.current?.open();
                        }}
                    />}
                    <MobileListItem
                        title={Lang.key('log_out')}
                        link
                        chevron={false}
                        media={<LogOutIcon />}
                        onClick={() => {
                            setPopoverOpened(false);
                            setMobileMenuOpened(false);
                            onLogOut();
                        }}
                    />
                </MobileList>
            </MobilePopover>
        </>
    }


    if (menubar) {

        return <Menubar className='overflow-y-auto'>

            <MenubarMenu>
                <MenubarTrigger>
                    {initLoaded ? <>

                        <img src={icon}
                            className='w-4 h-4 rounded-sm mr-2'
                            alt="logo" />
                        {title}

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

                    </>}

                </MenubarTrigger>
            </MenubarMenu>

            <MenubarMenu>
                <MenubarTrigger><User2Icon size={16} className='mr-2' /> {Lang.key('profile')}</MenubarTrigger>
                <MenubarContent>
                    <SidebarProfileItems variant="menubar" />

                    {!!profile?.balances?.length && <MenubarItem
                        onClick={() => {
                            balanceAndPaymentDialogRef.current?.open();
                        }}
                    >
                        <CreditCardIcon /> {Lang.key('payment_and_balance')}
                    </MenubarItem>}
                    <MenubarItem
                        onClick={() => {
                            exportDialogRef.current?.open();
                        }}
                    >
                        <DownloadCloudIcon /> {Lang.key('export_data')}
                    </MenubarItem>
                    <MenubarItem
                        onClick={() => {
                            toggleTheme();
                        }}
                    >
                        {isDarkTheme ? <SunIcon /> : <MoonIcon />} {isDarkTheme ? Lang.key('light_theme') : Lang.key('dark_theme')}
                    </MenubarItem>
                    {initLoaded && canChangeLang && <MenubarItem
                        onClick={() => {
                            changeLangDialogRef.current?.open();
                        }}
                    >
                        <GlobeIcon /> {Lang.key('change_language')}
                    </MenubarItem>}
                    <MenubarItem
                        onClick={() => {
                            onLogOut();
                        }}
                    >
                        <LogOutIcon /> {Lang.key('log_out')}
                    </MenubarItem>
                </MenubarContent>
            </MenubarMenu>


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



                    return <MenubarMenu>





                        <MenubarTrigger>
                            <ServerIcon
                                className='mr-2'
                                size={16}


                                icon={item.icon || item.children[0].icon} />
                            <LL value={item.label} /></MenubarTrigger>
                        <MenubarContent>
                            <MenubarGroup>
                                {item.children.map((item) => (
                                    <MenubarItem

                                        onClick={() => {
                                            onMenuItemClick(item);
                                        }}
                                    >
                                        <ServerIcon

                                            icon={item.icon} /> <LL value={item.label} />
                                        {badges[item.key!] && <MenuBadge>{badges[item.key!]}</MenuBadge>}
                                    </MenubarItem>))}

                            </MenubarGroup>

                        </MenubarContent>
                    </MenubarMenu>




                }


                return <MenubarMenu>



                    <MenubarTrigger
                        onClick={() => {
                            onMenuItemClick(item);
                        }}
                    ><ServerIcon
                            className='mr-2'
                            size={16}


                            icon={item.icon} /> <LL value={item.label} />

                        {badges[item.key!] && <MenuBadge>{badges[item.key!]}</MenuBadge>}
                    </MenubarTrigger>

                </MenubarMenu>





            })}



            </> : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map((item) => {
                return <></>
            })}

        </Menubar>

    }


    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 ? <div className="flex items-center gap-1">
                    {onCollapse && (
                        <Button
                            tooltip={Lang.key('collapse_sidebar')}
                            variant="outline"
                            size="icon-sm"
                            onClick={onCollapse}
                            aria-label={Lang.key('collapse_sidebar')}
                        >
                            <PanelLeftClose />
                        </Button>
                    )}
                    <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                            <Button
                                variant="outline"
                                size="icon-sm"
                                tooltip={Lang.key('profile')}
                                aria-label={Lang.key('profile')}
                            >
                                <MenuIcon />
                            </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent className="w-56" align="start">


                            <DropdownMenuSeparator />
                            <SidebarProfileItems />
                            <DropdownMenuSeparator />
                            <DropdownMenuGroup>
                                {!!profile?.balances?.length && <DropdownMenuItem onClick={() => {
                                    balanceAndPaymentDialogRef.current?.open();
                                }}>
                                    <CreditCardIcon /> {Lang.key('payment_and_balance')}
                                </DropdownMenuItem>}




                                {profile?.changePassword && <DropdownMenuItem onClick={() => {
                                    changePasswordDialogRef.current?.open();
                                }}>
                                    <RiLockPasswordFill />  {Lang.key('change_password')}
                                </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>
                            {initLoaded && canChangeLang && <DropdownMenuItem onClick={() => {
                                changeLangDialogRef.current?.open();
                            }}>
                                <GlobeIcon /> {Lang.key('change_language')}
                            </DropdownMenuItem>}


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

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

            <SidebarAlerts />

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


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

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

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

                                    after={badges[item.key!] && <MenuBadge>{badges[item.key!]}</MenuBadge>}
                                    key={item.key ?? ''}>

                                </MenuItem>
                            ))}

                        </div>
                    </div>


                }

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

                    after={badges[item.key!] && <MenuBadge>{badges[item.key!]}</MenuBadge>}
                    active={selectMenu?.key == item.key}

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

                        icon={item.icon} />}
                    label={<span
                        style={{
                            color: selectMenu?.key == item.key ? color : undefined
                        }}
                    ><LL value={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>
    </>




}