'use client';

import React, { useMemo, useRef, useState } from 'react';
import { motion, PanInfo, Variants } from 'framer-motion';
import SideMenuItem from './SideMenuItem';
import NotificationBellIcon from '../icons/NotificationBellIcon';
import CupIcon from '../icons/CupIcon';
import TicketDiscountIcon from '../icons/TickerDiscountIcon';
import CalendarSearchIcon from '../icons/CalendarSearchIcon';
import ReceiptIcon from '../icons/ReceiptIcon';
import GameControllerIcon from '../icons/GameControllerIcon';
import ThumbsUpIcon from '../icons/ThumbsUpIcon';
import NoteBoardIcon from '../icons/NoteBoardIcon';
import DirectboxReceiveIcon from '../icons/DirectboxReceiveIcon';
import SettingIcon from '../icons/SettingsIcon';
import ExitIcon from '../icons/ExitIcon';
import BlurredOverlayContainer from '../overlays/BlurredOverlayContainer';
import NightModeSwitch from '../button/NightModeSwitch';
import Button from '../button/PrimaryButton';
import { useAuthStore } from '@/zustand/authStore';
import { useParams, usePathname, useRouter } from 'next/navigation';
import clsx from 'clsx';
import { useTranslation } from 'react-i18next';
import { DocumentCopy, Instagram, Share, Whatsapp } from 'iconsax-react';
import TelegramIcon from '../icons/TelegramIcon';

type MenuItemType = {
    href: string | undefined;
    title: string;
    icon: React.ReactElement;
    auth?: boolean;
};

const menuItems: Array<Array<MenuItemType>> = [
    [
        { href: '/', title: 'Notifications', icon: <NotificationBellIcon width={20} height={20} /> },
        { href: 'my-services', title: 'CustomerClub', icon: <CupIcon width={20} height={20} /> },
        { href: 'services', title: 'Discounts', icon: <TicketDiscountIcon width={20} height={20} /> },
        { href: 'order/history', title: 'Orders', icon: <CalendarSearchIcon width={20} height={20} /> },
        { href: 'transactions', title: 'Transactions', icon: <ReceiptIcon width={20} height={20} /> },
        { href: '/', title: 'Games', icon: <GameControllerIcon width={20} height={20} /> },
        { href: '?share', title: 'ShareWithFriends', icon: <ThumbsUpIcon width={20} height={20} /> },
        { href: 'report', title: 'ReportProblem', icon: <NoteBoardIcon width={20} height={20} /> },
        { href: 'invoices', title: 'InstallApp', icon: <DirectboxReceiveIcon width={20} height={20} /> }
    ],
    [],
    [
        { auth: true, href: undefined, title: 'Preferences', icon: <SettingIcon width={20} height={20} /> },
        { auth: true, href: '?logout', title: 'Logout', icon: <ExitIcon width={20} height={20} /> }
    ]
];

type Props = {
    menuState: boolean;
    toggleMenuState: React.MouseEventHandler<HTMLDivElement> | undefined;
    nightModeState: boolean;
    togglenightModeState: React.MouseEventHandler<HTMLDivElement> | undefined;
};

function SideMenu({ menuState, toggleMenuState, nightModeState, togglenightModeState }: Props) {
    const menuStateMemo = useMemo(() => menuState, [menuState]);
    const [logoutModalVisible, setLogoutModalVisible] = useState(false);
    const [shareModalVisible, setShareModalVisible] = useState(false);
    const closeRef = useRef<HTMLDivElement>(null);
    const userIsAuthenticated = true; // useAuthStore((state) => state.isAuthenticated);
    const authLogout = useAuthStore((state) => state.logout);
    const router = useRouter();
    const params = useParams();
    const { name } = params;
    const pathname = usePathname();
    const { t: tMenu } = useTranslation('common', {
        keyPrefix: 'SideMenu'
    });
    const { t: tLogoutModal } = useTranslation('common', {
        keyPrefix: 'LogoutModal'
    });
    const { t: tShareModal } = useTranslation('common', {
        keyPrefix: 'ShareModal'
    });

    const variants: Variants = {
        hidden: { x: '100%', transition: { duration: 0.1, ease: 'easeInOut' } },
        visible: { x: 0, transition: { delay: 0.075, duration: 0.1, ease: 'easeInOut' } }
    };

    const onDrag = (_event: MouseEvent | TouchEvent | PointerEvent, info: PanInfo) => {
        if (info.offset.x > 20 && closeRef.current) {
            closeRef.current.click();
        }
    };

    const toggleLogoutModalVisiblity = (e?: React.MouseEvent) => {
        e?.preventDefault();
        e?.stopPropagation();
        setLogoutModalVisible((state) => !state);
    };

    const toggleShareModalVisiblity = (e?: React.MouseEvent) => {
        e?.preventDefault();
        e?.stopPropagation();
        setShareModalVisible((state) => !state);
    };

    const onLogout = (e: React.MouseEvent<HTMLButtonElement> | null) => {
        if (!e) return;
        if (userIsAuthenticated) {
            authLogout();
            router.replace('/');
        }
    };

    const hrefOnClicks = [
        { href: '?logout', handler: toggleLogoutModalVisiblity },
        { href: '?share', handler: toggleShareModalVisiblity }
    ];

    const renderMenu = () => {
        return (
            <section className="flex-1 overflow-y-scroll noscrollbar pt-20 pb-10 flex flex-col justify-between">
                <div>
                    <header className="px-12 pt-6 mt-3">
                        <h6 className="text-start font-bold text-sm text-menu-header mt-2 mb-[19px]">منو</h6>
                    </header>

                    <nav aria-label={tMenu('NavAriaLabel')}>
                        <ul>
                            {menuItems[0]
                                .filter(item => !item.auth || (item.auth && userIsAuthenticated))
                                .map((item, index) => {
                                    const href = `/${name}/${item.href}`;
                                    const isActive = pathname === href;
                                    return (
                                        <li key={index} className="mt-4 h-6">
                                            <SideMenuItem
                                                className={clsx(isActive && 'text-foreground! border-primary!', 'border-r-4!')}
                                                href={href ?? ''}
                                                title={tMenu(item.title)}
                                                onClick={
                                                    typeof item.href === 'string'
                                                        ? hrefOnClicks.find((i) => i.href === item.href)?.handler
                                                        : undefined
                                                }
                                                icon={
                                                    <span className={clsx(isActive ? 'text-foreground!' : 'text-icon-deactive')}>
                                                        {item.icon}
                                                    </span>
                                                }
                                            />
                                        </li>
                                    );
                                })}
                        </ul>
                    </nav>
                </div>

                <section aria-label={tMenu('ControlsAriaLabel')}>
                    <ul className="flex flex-col pt-16">
                        {menuItems[2]
                            .filter(item => !item.auth || (item.auth && userIsAuthenticated))
                            .map((item, index) => {
                                const href = `/${name}/${item.href}`;
                                const isActive = pathname === href;
                                return (
                                    <li key={index} className="mt-4 h-6 w-full">
                                        <SideMenuItem
                                            key={index}
                                            href={item.href ?? ''}
                                            className={clsx(isActive && 'text-foreground! border-primary!', 'border-r-4!')}
                                            onClick={
                                                typeof item.href === 'string'
                                                    ? hrefOnClicks.find((i) => i.href === item.href)?.handler
                                                    : undefined
                                            }
                                            title={tMenu(item.title)}
                                            icon={
                                                <span className={clsx(isActive ? 'text-foreground!' : 'text-icon-deactive')}>
                                                    {item.icon}
                                                </span>
                                            } />
                                    </li>
                                )
                            })}
                        <li className="mt-4 h-6">
                            <SideMenuItem href={''} title={''} icon={<></>}>
                                <NightModeSwitch checked={nightModeState} onClick={togglenightModeState} />
                            </SideMenuItem>
                        </li>
                    </ul>
                </section>
            </section>
        )
    }

    return (
        <>
            <div className='w-full' ref={closeRef} onClick={toggleMenuState}>
                <aside aria-label={tMenu('AriaLabel')}>
                    <BlurredOverlayContainer className='md:hidden!' bgOpacity={40} visible={menuStateMemo} outDelay={150} inDuration={200}>
                        <motion.nav
                            drag='x'
                            dragConstraints={{ left: 0, right: 20 }}
                            transition={{ type: "spring", stiffness: 200, damping: 20 }}
                            dragTransition={{ bounceDamping: 10, bounceStiffness: 600 }}
                            dragElastic={0.05}
                            onDragEnd={onDrag}
                            initial="hidden"
                            animate={menuState ? 'visible' : 'hidden'}
                            variants={variants}
                            data-visible={menuState}
                            data-isvisible={menuStateMemo}
                            onClick={(e) => { e.stopPropagation(); }}
                            className="fixed top-0 bottom-0 right-0 bg-white w-[200px] h-dvh flex flex-col z-40 overflow-clip not-xl:!rounded-s-none"
                        >
                            {renderMenu()}
                        </motion.nav>
                    </BlurredOverlayContainer>
                    <div className="hidden fixed top-4 bottom-4 right-4 bg-white xl:w-[250px] md:flex flex-col z-40 overflow-clip md:rounded-4xl">
                        {renderMenu()}
                    </div>
                </aside>
            </div>

            {/* Logout Modal */}
            <BlurredOverlayContainer visible={logoutModalVisible} onClick={toggleLogoutModalVisiblity} inDuration={100} outDuration={100} outDelay={75}>
                <div className="absolute top-1/2 left-6 right-6 px-6">
                    <motion.div
                        animate={{ y: logoutModalVisible ? [10, 0] : [0, 10] }}
                        transition={{ duration: 0.1, ease: 'easeInOut' }}
                        className="top-1/2 absolute left-1/2 min-w-xs w-full max-w-sm text-center -translate-1/2 px-6 pt-8 pb-9 drop-shadow-container bg-white/63 rounded-4xl"
                    >
                        <h2 className="text-base font-medium">
                            {tLogoutModal('Heading')}
                        </h2>
                        <p className="text-xs font-medium mt-6">
                            {tLogoutModal('Description')}
                        </p>
                        <div className="grid grid-cols-2 gap-5.5 mt-8">
                            <Button onClick={onLogout} className="text-sm font-normal">
                                {tLogoutModal('ButtonOk')}
                            </Button>
                            <Button onClick={toggleLogoutModalVisiblity} className="bg-disabled! text-disabled2! text-sm font-normal">
                                {tLogoutModal('ButtonCancel')}
                            </Button>
                        </div>
                    </motion.div>
                </div>
            </BlurredOverlayContainer>

            {/* Share modal */}
            <BlurredOverlayContainer visible={shareModalVisible} onClick={toggleShareModalVisiblity} inDuration={100} outDuration={100} outDelay={75}>
                <div className="absolute top-1/2 left-6 right-6 px-6">
                    <motion.div
                        animate={{ y: shareModalVisible ? [10, 0] : [0, 10] }}
                        transition={{ duration: 0.1, ease: 'easeInOut' }}
                        className="top-1/2 absolute left-1/2 min-w-xs w-full max-w-sm text-center -translate-1/2 px-6 pt-8 pb-9 drop-shadow-container bg-white/63 rounded-4xl"
                    >
                        <h2 className="text-base font-medium">
                            <Share className="inline-block ml-2 mb-1.5 stroke-primary" size={24} />
                            {tShareModal('Heading')}
                        </h2>
                        <p className="text-xs font-medium mt-6">
                            {tShareModal('Description')}
                        </p>

                        <Button onClick={onLogout} className="text-sm mt-8">
                            <DocumentCopy className="inline-block ml-2 mb-0.5 stroke-white" size={20} />
                            <span className="font-light">{tShareModal('ButtonCopy')}</span>
                        </Button>

                        <div className="grid grid-cols-3 gap-5.5 mt-6 px-12">
                            <div className="place-items-center">
                                <TelegramIcon width={24} height={24} className="mb-1.5 stroke-primary" />
                                <span className='text-xs2 font-medium'>Telegram</span>
                            </div>
                            <div className="place-items-center">
                                <Whatsapp size={24} className="mb-1.5 stroke-primary" />
                                <span className='text-xs2 font-medium'>WhatsApp</span>
                            </div>
                            <div className="place-items-center">
                                <Instagram size={24} className="mb-1.5 stroke-primary" />
                                <span className='text-xs2 font-medium'>Instagram</span>
                            </div>
                        </div>
                    </motion.div>
                </div>
            </BlurredOverlayContainer>
        </>
    );
}

export default SideMenu;