import { useRef } from 'react';
import PerfectScrollbar from 'react-perfect-scrollbar';
import { useTranslations } from 'next-intl';
import { useDispatch } from 'react-redux';
import Link from 'next/link';
import { toggleSidebar } from '@/redux/features/sidebar-slice';
import AnimateHeight from 'react-animate-height';
import { useState, useEffect } from 'react';
import { useAppSelector } from "@/redux/store";
import { usePathname } from 'next/navigation';
import { AppDispatch } from '@/redux/store';
import Cookies from 'universal-cookie';

export default function Sidebar () {

    // init classess
    const cookies = new Cookies({ path: '/' });
    const dispatch = useDispatch<AppDispatch>();
    const t = useTranslations('sidebar');
    const pathname = usePathname()
    const prevPathName = useRef(pathname)
    const local = cookies.get('NEXT_LOCALE');
    // get states
    const sidebarState = useAppSelector((state) => state.sidebarReducer.value.state);
    const sidebarItems = useAppSelector((state) => state.sidebarReducer.value.items);
    const appGeneralSettings = useAppSelector((state) => state.settingsReducer.value.appGeneralSettings) || {
        showLogo: true,
        logo: '',
        appName: '',
        appNameEN: ''
    };
    // handle sidebar menus states
    const [currentMenu, setCurrentMenu] = useState<string>('');
    const toggleMenu = (value: string) => {
        setCurrentMenu((oldValue) => {
            return oldValue === value ? '' : value;
        });
    };
    useEffect(() => {
        if(prevPathName.current == pathname) return
        if(!sidebarState) return
        dispatch(toggleSidebar())
        prevPathName.current == pathname
    }, [pathname])
    // return sidebar ui
    return (
        <>
            <nav className={`fixed top-0 ltr:left-0 rtl:right-0 lg:relative shadow-[5px_0_25px_0_rgba(94,92,154,0.1)] z-[99] h-screen bg-primary-dark dark:bg-primary-dark duration-300 ${sidebarState ? 'min-w-[260px] max-w-[260px] ' : 'ltr:translate-x-[-260px] rtl:translate-x-[260px] w-0'}`}>
                <header className="w-full max-h-[64px] flex justify-between items-center px-[18px] py-[14px] [&_*]:text-text-light bg-secondary-dark">
                    <div className="flex justify-center items-center flex gap-[15px]">
                        {appGeneralSettings?.showLogo && appGeneralSettings?.logo && (
                            <div className="w-12 h-16 flex items-center justify-center relative" 
                                 dangerouslySetInnerHTML={{ __html: appGeneralSettings.logo }} />
                        )}
                        <h1 className="text-[25px] font-light">
                            {local === 'ar' ? (appGeneralSettings?.appName || '') : (appGeneralSettings?.appNameEN || '')}
                        </h1>
                    </div>
                    <button onClick={() => {dispatch(toggleSidebar())}} className="rounded-full rtl:rotate-180 hover:bg-primary/5 p-[6px]">
                        <svg width="23" height="23" viewBox="0 0 34 34" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M18.4166 26.9166L9.91663 17L18.4166 7.08331" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                            <path opacity="0.5" d="M24.083 26.9166L15.583 17L24.083 7.08331" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                        </svg>
                    </button>
                </header>
                <main className="[&_*]:text-text-light dark:[&_*]:text-text-light bg-primary-dark dark:bg-primary-dark">
                    <PerfectScrollbar className="relative h-[calc(100vh-80px)]">
                        <div className="w-full pt-[33px] px-[16px] flex flex-col gap-2 [&_button]:px-[6px] [&_button]:py-[6px]">
                            {
                                sidebarItems.map((v : {
                                    name: string,
                                    icon: string,
                                    link?: string,
                                    items?: {name: string, link: string}[],
                                } , i : number) => {
                                    if(v.items)
                                    {
                                        return (
                                            <div key={i} className="flex flex-col gap-2">
                                                <button onClick={() => toggleMenu(v.name)} className={`h-12 w-12 hover:bg-primary-light/10 w-full rounded-md flex items-center justify-between text-[18px] font-bold`}>
                                                    <div className="flex items-center w-full gap-[12px]">
                                                        <div dangerouslySetInnerHTML={{ __html: v.icon }} />
                                                        {t(v.name)}
                                                    </div>
                                                    <div className={currentMenu === v.name ? 'rotate-90' : 'rtl:rotate-180'}>
                                                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                            <path d="M9 5L15 12L9 19" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                                                        </svg>
                                                    </div>
                                                </button>
                                                <AnimateHeight duration={300} height={currentMenu === v.name ? 'auto' : 0}>
                                                    <ul className="w-full h-auto [&_li]:px-[18px] [&_li]:py-[14px] [&_li]:cursor-pointer [&_li]:cursor-pointer flex flex-col gap-2">
                                                        {
                                                            v.items.map((v2 : {name: string, link: string} , i2 : number) => {
                                                                return (
                                                                    <Link key={i2} href={v2.link}>
                                                                        <li key={i2} className={`h-12 w-full hover:bg-primary-light/10 flex items-center gap-[12px] text-[18px] font-bold rounded-md ${pathname === v2.link || (pathname.match(/^\/(ar|en)/) && pathname.replace(/^\/(ar|en)/, '') === v2.link) ? 'bg-secondary-light' : ''}`}>
                                                                            {t(v2.name)}
                                                                        </li>   
                                                                    </Link>
                                                                )
                                                            })
                                                        }
                                                    </ul>
                                                </AnimateHeight>
                                            </div>
                                        )
                                    }
                                    else
                                    {
                                        return (
                                            <Link key={i} href={v.link || ''}>
                                                <button className={`h-12 w-12 hover:bg-primary-light/10 w-full rounded-md flex items-center text-[18px] font-bold ${pathname === v.link || (pathname.match(/^\/(ar|en)/) && pathname.replace(/^\/(ar|en)/, '') === v.link) ? 'bg-secondary-light' : ''}`}>
                                                    <div className="flex items-center w-full gap-[12px]">
                                                        <div dangerouslySetInnerHTML={{ __html: v.icon }} />
                                                        {t(v.name)}
                                                    </div>
                                                </button>
                                            </Link>
                                        )
                                    }
                                })
                            }
                        </div>
                        <div className="absolute bottom-0 w-full py-[33px] px-[16px] flex flex-col gap-2 [&_button]:px-[6px] [&_button]:py-[6px] border-t-2 border-primary-light/5">
                            <Link href="/dashboard/settings">
                                <button className={`h-12 w-12 hover:bg-primary-light/10 w-full rounded-md flex items-center text-[18px] font-bold ${pathname === "/dashboard/settings" || (pathname.match(/^\/(ar|en)/) && pathname.replace(/^\/(ar|en)/, '') === "/dashboard/settings") ? 'bg-secondary-light' : ''}`}>
                                    <div className="flex items-center w-full gap-[12px]">
                                        <svg className="shrink-0 group-hover:!text-primary" width="28" height="28" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"> <path opacity="0.2" d="M13 15.4C13 13.3258 13 12.2887 13.659 11.6444C14.318 11 15.3787 11 17.5 11C19.6213 11 20.682 11 21.341 11.6444C22 12.2887 22 13.3258 22 15.4V17.6C22 19.6742 22 20.7113 21.341 21.3556C20.682 22 19.6213 22 17.5 22C15.3787 22 14.318 22 13.659 21.3556C13 20.7113 13 19.6742 13 17.6V15.4Z" fill="currentColor"></path> <path d="M2 8.6C2 10.6742 2 11.7113 2.65901 12.3556C3.31802 13 4.37868 13 6.5 13C8.62132 13 9.68198 13 10.341 12.3556C11 11.7113 11 10.6742 11 8.6V6.4C11 4.32582 11 3.28873 10.341 2.64437C9.68198 2 8.62132 2 6.5 2C4.37868 2 3.31802 2 2.65901 2.64437C2 3.28873 2 4.32582 2 6.4V8.6Z" fill="currentColor"></path> <path d="M13 5.5C13 4.4128 13 3.8692 13.1713 3.44041C13.3996 2.86867 13.8376 2.41443 14.389 2.17761C14.8024 2 15.3266 2 16.375 2H18.625C19.6734 2 20.1976 2 20.611 2.17761C21.1624 2.41443 21.6004 2.86867 21.8287 3.44041C22 3.8692 22 4.4128 22 5.5C22 6.5872 22 7.1308 21.8287 7.55959C21.6004 8.13133 21.1624 8.58557 20.611 8.82239C20.1976 9 19.6734 9 18.625 9H16.375C15.3266 9 14.8024 9 14.389 8.82239C13.8376 8.58557 13.3996 8.13133 13.1713 7.55959C13 7.1308 13 6.5872 13 5.5Z" fill="currentColor"></path> <path opacity="0.5" d="M2 18.5C2 19.5872 2 20.1308 2.17127 20.5596C2.39963 21.1313 2.83765 21.5856 3.38896 21.8224C3.80245 22 4.32663 22 5.375 22H7.625C8.67337 22 9.19755 22 9.61104 21.8224C10.1624 21.5856 10.6004 21.1313 10.8287 20.5596C11 20.1308 11 19.5872 11 18.5C11 17.4128 11 16.8692 10.8287 16.4404C10.6004 15.8687 10.1624 15.4144 9.61104 15.1776C9.19755 15 8.67337 15 7.625 15H5.375C4.32663 15 3.80245 15 3.38896 15.1776C2.83765 15.4144 2.39963 15.8687 2.17127 16.4404C2 16.8692 2 17.4128 2 18.5Z" fill="currentColor"></path> </svg>
                                        {t('settings')}
                                    </div>
                                </button>
                            </Link>
                        </div>
                    </PerfectScrollbar>
                </main>
            </nav>
        </>
    );
};