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

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

import { MenuItemType } from '@/api/types';
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 {
    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 { changePasswordDialogRef } from '@/componentsRoot/ChangePasswordDialog';
import { confirmAlertRef } from '@/componentsRoot/ConfirmAlert';
import { exportDialogRef } from '@/componentsRoot/ExportDialog';
import { tCompanyBankDialogRef } from '@/componentsRoot/TCompanyBankDialog';
import { tCompanyDialogRef } from '@/componentsRoot/TCompanyDialog';
import { Lang } from '@/lang/Lang';
import useAppConfigStore, { useAppConfig } from '@/stores/appConfig';
import { useMainPage } from '@/stores/mainPage';
import { EventEmitter } from '@/utils/event';

import { profileDialogRef } from '../../../componentsRoot/ProfileDialog';
import SidebarAlerts from './SidebarAlerts';

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

export const AppSidebar = ({ menubar }: { menubar?: boolean }) => {

    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 } = 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'>{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();
                        }}
                    />

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

                    {profile?.canAddTCompanyData && <>
                        <MobileListItem
                            title={Lang.key('company_data')}
                            link
                            chevron={false}
                            media={<Building2Icon />}
                            onClick={() => {
                                tCompanyDialogRef.current?.open();
                                setPopoverOpened(false);
                                setMobileMenuOpened(false);
                            }}
                        />

                        <MobileListItem
                            title={Lang.key('company_bank_data')}
                            link
                            chevron={false}
                            media={<ReceiptText />}
                            onClick={() => {
                                tCompanyBankDialogRef.current?.open();
                                setPopoverOpened(false);
                                setMobileMenuOpened(false);
                            }}
                        />
                    </>}
                    {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();
                        }}
                    />
                    <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>
        </>
    }


    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>
                    <MenubarItem
                        onClick={() => {
                            profileDialogRef.current?.open();
                        }}
                    >
                        <User2Icon /> {Lang.key('profile')}
                    </MenubarItem>

                    {!!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>
                    <MenubarItem
                        onClick={() => {
                            Lang.manualChangeLang(Lang.getCurrentLang() == "ru" ? "en" : "ru");
                        }}
                    >
                        <GlobeIcon /> {Lang.getCurrentLang() != "ru" ? "Переключить на русский" : "Switch to English"}
                    </MenubarItem>
                    <MenubarItem
                        onClick={() => {
                            onLogOut();
                        }}
                    >
                        <LogOutIcon /> {Lang.key('log_out')}
                    </MenubarItem>
                </MenubarContent>
            </MenubarMenu>


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



                    return <MenubarMenu>


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


                                icon={item.icon || item.children[0].icon} />
                            {item.label}</MenubarTrigger>
                        <MenubarContent>
                            <MenubarGroup>
                                {item.children.map((item) => (
                                    <MenubarItem
                                        onClick={() => {
                                            onMenuItemClick(item);
                                        }}
                                    >
                                        <SvgIcon

                                            icon={item.icon} /> {item.label}
                                    </MenubarItem>))}

                            </MenubarGroup>

                        </MenubarContent>
                    </MenubarMenu>




                }


                return <MenubarMenu>


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


                            icon={item.icon} /> {item.label}</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 ? <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>

                            {!!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>
                        {profile?.canAddTCompanyData && <>
                            <DropdownMenuSeparator />
                            <DropdownMenuGroup>
                                <DropdownMenuItem onClick={() => {
                                    tCompanyDialogRef.current?.open();
                                    setPopoverOpened(false);
                                    setMobileMenuOpened(false);
                                }}>
                                    <Building2Icon />  {Lang.key('company_data')}


                                </DropdownMenuItem>
                                <DropdownMenuItem onClick={() => {
                                    tCompanyBankDialogRef.current?.open();
                                    setPopoverOpened(false);
                                    setMobileMenuOpened(false);
                                }}>
                                    <ReceiptText />  {Lang.key('company_bank_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'>

            <SidebarAlerts />

            {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>


    </>




}