
// imports
import clsx from 'clsx';
import Link from 'next/link';
import setLanguage from 'next-translate/setLanguage';
import useTranslation from 'next-translate/useTranslation';
import { usePathname } from 'next/navigation';
import React, { useEffect, useMemo, useState } from 'react';

// icons
import IconSun from '../../../icons/Sun';
import IconUser from '../../../icons/User';
import IconMoon from '../../../icons/Moon';
import IconLogin from '../../../icons/Login';
import IconLogout from '../../../icons/Logout';
import IconSettings from '../../../icons/Settings';
import IconLanguage from '../../../icons/Language';
import IconInfluence from '../../../icons/Influence';

// signals
import UserSignal from '../../../signals/User';
import LoginSignal from '../../../signals/Login';
import ThemeSignal from '../../../signals/Theme';
import RegisterSignal from '../../../signals/Register';
import Signal, { useSignal } from '../../../signal';

// locals
import User from './User';
import Language from '../../Language';

// signals
export const openMobile = new Signal.State(false);

// width
export const width = '64';

/**
 * leftbar
 *
 * @param props 
 */
const ComponentLayoutRightbar = (props = {}) => {
  // signals
  const [user] = useSignal(UserSignal);
  const [,setLogin] = useSignal(LoginSignal);
  const [,setRegister] = useSignal(RegisterSignal);
  const [theme, setTheme] = useSignal(ThemeSignal);
  const [sOpenMobile, setOpenMobile] = useSignal(openMobile);
  
  // router
  const path = usePathname();

  // translation
  const { t : tSidebar, lang } = useTranslation('sidebar');

  // state
  const [ready, setReady] = useState(false);
  const [langOpen, setLangOpen] = useState(false);

  /**
   * on language
   *
   * @param code 
   */
  const onLanguage = async (code) => {
    // import cookie
    const Cookie = (await import('js-cookie')).default;

    // set language
    Cookie.set('NEXT_LOCALE', code, {
      expires : 365,
    });
    setLanguage(code);
    setLangOpen(false);
  };

  // items
  const navigation = useMemo(() => {
    // return
    return [
      {
        id      : 'profile',
        icon    : IconUser,
        name    : tSidebar('profile.title'),
        href    : user?.id && '/profile',
        onClick : !user?.id && (() => setLogin(true)),
        current : path.startsWith('/profile')
      },
      ...(user?.id ? [{
        id   : 'mana',
        href : '/mana',
        icon : IconInfluence,
        name : tSidebar('mana.title', {
          value : parseFloat(user?.wallet?.mana || 0).toLocaleString(),
        }),
        current : path.startsWith('/mana'),
      }] : []),
      {
        id      : 'settings',
        href    : user?.id && '/settings',
        icon    : IconSettings,
        name    : tSidebar('settings.title'),
        onClick : !user?.id && (() => setLogin(true)),
        current : path.startsWith('/settings'),
      },

      'divider',
      
      {
        id      : 'lang',
        name    : tSidebar('language.title'),
        icon    : IconLanguage,
        onClick : () => setLangOpen(true),
        current : false,
      },
      ...(props.noThemeMode ? [] : [{
        id   : 'theme',
        name : theme === 'dark' ? tSidebar('light.title') : tSidebar('dark.title'),
        icon : theme === 'dark' ? IconSun : IconMoon,
        onClick : () => setTheme(theme === 'dark' ? 'light' : 'dark'),
        current : false,
      }]),

      'divider',

      ...(user?.id ? [{
        id      : 'logout',
        name    : tSidebar('logout.title'),
        icon    : IconLogout,
        onClick : props.onLogout,
        current : false,
      }] : [
        {
          id      : 'login',
          name    : tSidebar('login.title'),
          icon    : IconLogin,
          onClick : () => setLogin(true),
          current : path.startsWith('/login'),
        },
        {
          id      : 'register',
          name    : tSidebar('register.title'),
          icon    : IconLogin,
          onClick : () => setRegister(true),
          current : path.startsWith('/register'),
        }
      ]),
    ];
  }, [path, user?.id, theme]);

  // use effect
  useEffect(() => {
    // set ready
    setReady(true);
  }, []);

  // return jsx
  return (
    <>
      <div className={clsx(
        'flex fixed top-0 right-0 bottom-0 left-0 z-30 transition-opacity duration-300 lg:hidden bg-gray-BG/20',
        sOpenMobile ? 'opacity-100 translate-x-0' : 'opacity-0 translate-x-full',
      )} onClick={() => setOpenMobile(!sOpenMobile)} />
      
      <div
        className={clsx(
          'flex fixed top-0 right-0 bottom-0 z-40 w-3/4 bg-white transition-all transform lg:w-64 dark:bg-gray-SIDEBAR',
          sOpenMobile ? 'translate-x-0' : 'translate-x-full',
        )}
      >

        {/* Static sidebar for desktop */}
        <div className="flex inset-y-0 flex-col w-full">
          {/* Sidebar component, swap this element with another sidebar if you like */}
          <div className="flex overflow-y-auto flex-col px-4 py-4 grow">
            
            <nav className="flex flex-col flex-1">
              <ul role="list" className="flex flex-col flex-1 gap-y-7">
                <User
                  noThemeMode={props.noThemeMode}
                />
                {props.noContent ? props.children : ready && (
                  <li>
                    <ul role="list" className="space-y-2">
                      {navigation.map((item, i) => {
                        // item icon
                        const ItemIcon = item.icon;

                        // return jsx
                        return (
                          item === 'divider' ? (
                            <li key={`divider-${i}`} className="py-2" />
                          ) : (
                            <li key={item.id || Link.name}>
                              {item.href ? (
                                <Link
                                  href={item.href}
                                  className={clsx(
                                    item.current && 'bg-primary-500 text-white',
                                    'transition-all duration-300 hover:!text-white hover:!bg-primary-600',
                                    'group flex gap-x-3 rounded-xl px-3 py-2 text-sm leading-6 font-semibold'
                                  )}
                                >
                                  <ItemIcon
                                    filled={item.current}
                                    className={clsx(
                                      'w-6 h-6 shrink-0'
                                    )}
                                    aria-hidden="true"
                                  />
                                  {item.name}
                                </Link>
                              ) : (
                                <div
                                  onClick={() => [item.onClick(), setOpenMobile(false)]}
                                  className={clsx(
                                    item.current && 'bg-primary-500 text-white',
                                    'transition-all duration-300 hover:!text-white hover:!bg-primary-600',
                                    'group flex gap-x-3 rounded-xl px-3 py-2 text-sm leading-6 font-semibold'
                                  )}
                                >
                                  <ItemIcon
                                    filled={item.current}
                                    className={clsx(
                                      'w-6 h-6 shrink-0'
                                    )}
                                    aria-hidden="true"
                                  />
                                  {item.name}
                                </div>
                              )}
                            </li>
                          )
                        );
                      })}
                    </ul>
                  </li>
                )}
              </ul>
            </nav>
          </div>
        </div>
        
      </div>

      <Language
        open={!!langOpen}
        onClose={() => setLangOpen(false)}
        onChange={onLanguage}
        language={lang}
      />
    </>
  );
};

/**
 * export default
 */
export default ComponentLayoutRightbar;