import {Center, Image, rem, Stack, Tooltip, UnstyledButton, useMantineColorScheme} from '@mantine/core';
import {IconCash, IconHome2, IconLogout, IconMan, IconMoon, IconSun,} from '@tabler/icons-react';
import classes from './Navbar.module.css';
import {useAppDispatch} from "../../redux/store.ts";
import {logout} from "../../features/authSlice.ts";
import {useNavigate, useRouterState} from "@tanstack/react-router";

interface NavbarLinkProps {
    icon: typeof IconHome2;
    label?: string;
    active?: boolean;
    href: string;

    onClick?(navlink: NavbarLinkProps): void;

    index: number;
}

function NavbarLink(props: NavbarLinkProps) {
    const {icon: Icon, label, active, onClick} = props;
    return (
        <Tooltip display={!label ? "none" : "flex"} label={label} position="right" transitionProps={{duration: 0}}>
            <UnstyledButton onClick={() => onClick && onClick(props)}
                            className={classes.link}
                            data-active={active || undefined}>
                <Icon style={{width: rem(20), height: rem(20)}} stroke={1.5}/>
            </UnstyledButton>
        </Tooltip>
    );
}

const mockdata = [
    {
        icon: IconHome2,
        label: 'Главная',
        href: '/'
    },
    {
        icon: IconCash,
        label: 'Сделки',
        href: '/leads'
    },
    {
        icon: IconMan,
        label: 'Клиенты',
        href: '/clients'
    }
];

export function Navbar() {
    const dispatch = useAppDispatch();
    const navigate = useNavigate();
    const router = useRouterState();
    const {colorScheme, toggleColorScheme} = useMantineColorScheme({keepTransitions: false});
    const onLogoutClick = () => {
        dispatch(logout());
        navigate({to: '/login'});
    }
    const onNavlinkClick = (props: NavbarLinkProps) => {
        navigate({to: props.href});
    }
    const links = mockdata.map((link, index) => (
        <NavbarLink
            {...link}
            index={index}
            key={link.label}
            active={router.location.pathname === link.href}
            onClick={onNavlinkClick}
        />
    ));

    return (
        <nav className={classes.navbar}>
            <Center>
                <Image
                    style={{filter: "drop-shadow(0 0 30px #fff)"}}
                    src={colorScheme == "dark" ? "/icons/logo-light.png" : "/icons/logo.png"}
                />
            </Center>

            <div className={classes.navbarMain}>
                <Stack justify="center" gap={rem(10)}>
                    {links}
                </Stack>
            </div>

            <Stack justify="center" gap={0}>
                <NavbarLink label={"Сменить тему"} onClick={toggleColorScheme}
                            icon={colorScheme == "dark" ? IconSun : IconMoon} href={"#"} index={-1}/>
                <NavbarLink index={-1} href={"#"} onClick={onLogoutClick} icon={IconLogout} label="Выйти"/>
            </Stack>
        </nav>
    );
}