import { AppShell, Avatar, Burger, Button, Flex, Group, Image, Menu, NavLink, rem, Text, useMantineColorScheme } from '@mantine/core';
import { useDisclosure } from '@mantine/hooks';
import { Outlet, useNavigate } from 'react-router-dom';
import { IconChevronDown, IconLogout, IconSettings, IconMoon, IconSun } from '@tabler/icons-react';
import { getUserData, logout, useAuthStore } from '../store/auth';
import { useEffect, useState } from 'react';
import { UserData } from '../interfaces/auth';
import { pages } from '../constants/app';

function DashboardLayout() {
    const [mobileOpened, { toggle: toggleMobile }] = useDisclosure()
    const [desktopOpened, { toggle: toggleDesktop }] = useDisclosure(true)
    const navigate = useNavigate()

    const getPageTitle = () => {
        const currentPath = location.pathname
        const allPages = [...pages]
        const currentPage = allPages.find(page => page.path === currentPath)
        return currentPage ? currentPage.label : "Панель управления"
    }

    const authStore = useAuthStore()
    const [userData, setUserData] = useState<UserData>()

    useEffect(() => {
        if (authStore) {
            const stored = getUserData()
            if (stored) {
                setUserData(stored)
            }
        }
    }, [authStore])

    const { colorScheme, setColorScheme } = useMantineColorScheme();

    return (
        <AppShell
            header={{ height: 60 }}
            navbar={{
                width: desktopOpened ? 200 : 50,
                breakpoint: 'sm',
                collapsed: { mobile: !mobileOpened },
            }}
        >
            <AppShell.Header>
                <Flex h="100%" px="md" w='100%' align='center' gap='sm'>
                    <Group>
                        <Burger opened={mobileOpened} onClick={toggleMobile} hiddenFrom="sm" size="sm" />
                        <Burger opened={desktopOpened} onClick={toggleDesktop} visibleFrom="sm" size="sm" />
                    </Group>

                    <Group w='auto'>
                        {getPageTitle()}
                    </Group>

                    <Group id='header-portal' w='auto' ml='auto'>

                    </Group>

                    <Group style={{ flexShrink: 0 }}>
                        <Menu
                            width={260}
                            position="bottom-end"
                            transitionProps={{ transition: 'pop-top-right' }}
                            withinPortal
                        >
                            <Menu.Target>
                                <Button variant='transparent'>
                                    <Group gap={7}>
                                        <Avatar name={`${userData?.name} ${userData?.surname}`} radius="xl" size={30} />
                                        <Text fw={500} size="sm" lh={1} mr={3}>
                                            {`${userData?.name} ${userData?.surname}`}
                                        </Text>
                                        <IconChevronDown style={{ width: rem(12), height: rem(12) }} stroke={1.5} />
                                    </Group>
                                </Button>
                            </Menu.Target>
                            <Menu.Dropdown>
                                <Menu.Label>{userData?.login}</Menu.Label>
                                <Menu.Item
                                    leftSection={
                                        colorScheme === 'dark' ? <IconMoon style={{ width: rem(16), height: rem(16) }} stroke={1.5} /> : <IconSun style={{ width: rem(16), height: rem(16) }} stroke={1.5} />
                                    }
                                    onClick={() => colorScheme === 'dark' ? setColorScheme('light') : setColorScheme('dark')}
                                >
                                    Тема: {colorScheme === 'dark' ? 'тёмная' : 'светлая'}
                                </Menu.Item>
                                <Menu.Item
                                    leftSection={
                                        <IconSettings style={{ width: rem(16), height: rem(16) }} stroke={1.5} />
                                    }
                                    onClick={() => navigate('/settings')}
                                >
                                    Настройки профиля
                                </Menu.Item>
                                <Menu.Item
                                    onClick={() => {
                                        logout()
                                        navigate("/auth/signin")
                                    }}
                                    leftSection={<IconLogout style={{ width: rem(16), height: rem(16) }} stroke={1.5} />}
                                >
                                    Выход
                                </Menu.Item>

                                <Menu.Item>
                                    <Flex gap='sm' align='center'>
                                        <Image src={'/logo2.svg'} w={32} />
                                        <Text>0.1.0</Text>
                                    </Flex>
                                </Menu.Item>
                            </Menu.Dropdown>
                        </Menu>
                    </Group>
                </Flex>
            </AppShell.Header>
            <AppShell.Navbar style={{ transition: "width 0.2s ease" }}>
                {pages.filter((page) => page.drawer).filter((page) => page.enabled).map((item) => (
                    <NavLink
                        key={item.path}
                        onClick={() => navigate(item.path)}
                        label={item.label}
                        leftSection={item.icon}
                        active={location.pathname === item.path}
                        style={{ textWrap: 'nowrap' }}
                    />
                ))}
            </AppShell.Navbar>
            <AppShell.Main>
                <Flex w={{
                    sm: desktopOpened ? 'calc(100% - 200px)' : 'calc(100% - 50px)',
                    base: '100%'
                }} h={'calc(100% - 60px)'} style={{ transition: "width 0.2s ease" }} pos={'fixed'}>
                    <Outlet />
                </Flex>
            </AppShell.Main>
        </AppShell>
    )
}

export default DashboardLayout