// imports
import clsx from 'clsx';
import Link from 'next/link';
import { Float } from '@headlessui-float/react';
import setLanguage from 'next-translate/setLanguage';
import { useSignal } from '@chirper/react/src/signal';
import useTranslation from 'next-translate/useTranslation';
import { usePathname } from 'next/navigation';
import { Listbox, Transition } from '@headlessui/react';
import React, { useMemo, useState } from 'react';

// icons
import IconSun from '@chirper/react/src/icons/Sun';
import IconMoon from '@chirper/react/src/icons/Moon';
import IconLogout from '@chirper/react/src/icons/Logout';
import IconLanguage from '@chirper/react/src/icons/Language';
import IconArrowRight from '@chirper/react/src/icons/ArrowRight';

// locals
import useTeam from '../../../hooks/useTeam';
import Language from '../../Language';
import ButtonIcon from '../../Button/Icon';
import UserSignal from '../../../signals/User';
import ThemeSignal from '../../../signals/Theme';

/**
 * team selector
 */
const ComponentLayoutLeftbarMenu = (props = {}) => {
  // signals
  const [sUser] = useSignal(UserSignal);
  const [sTheme, setTheme] = useSignal(ThemeSignal);
  
  // translation
  const { t : tCommon, lang } = useTranslation('common');
  
  // is open
  const [open, setOpen] = useState(false);

  // path
  const team = useTeam();
  const path = usePathname();
  
  // state
  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 [
      ...(props.navigation || []),
      'divider',
      {
        id      : 'lang',
        name    : tCommon('menu.language'),
        icon    : IconLanguage,
        onClick : () => setLangOpen(true),
        current : false,
      },
      /*
      ...(props.noThemeMode ? [] : [{
        id   : 'sTheme',
        name : sTheme === 'dark' ? tCommon('menu.light') : tCommon('menu.dark'),
        icon : sTheme === 'dark' ? IconSun : IconMoon,
        onClick : () => setTheme(sTheme === 'dark' ? 'light' : 'dark'),
        current : false,
      }]),
      */

      'divider',

      ...(sUser?.id ? [{
        id      : 'logout',
        name    : tCommon('menu.logout'),
        icon    : IconLogout,
        onClick : props.onLogout,
        current : false,
      }] : []),
    ];
  }, [path, sUser?.id, team?.id, sTheme, props.navigation]);

  // return jsx
  return (
    <>
      <Listbox>
        <Float
          onShow={() => setOpen(true)}
          onHide={() => setOpen(false)}
          placement="bottom-start"
          offset={5}
          flip
          shift
          portal
          adaptiveWidth
        >
          <Listbox.Button
            as="div"
            className="flex items-center px-4 space-x-3 w-full h-16 border-b border-gray-400 transition-all duration-300 dark:border-gray-600 wrap shrink-0 lg:mb-4 group"
          >
            <span className="flex flex-1 font-semibold truncate">
              {team?.name}
            </span>
            <ButtonIcon className="hidden lg:flex">
              <IconArrowRight className={clsx(
                'w-4 h-4 transition-all duration-300',
                open && 'transform rotate-90',
              )} />
            </ButtonIcon>
          </Listbox.Button>

          <Transition
            as="div"
            leave="transition ease-in duration-100"
            leaveFrom="opacity-100"
            leaveTo="opacity-0"
          >
            <Listbox.Options className="absolute left-0 z-10 px-3 mt-1 w-full origin-top-left !outline-none">
              <div className="card shadow-xl !ring-gray-200/20 dark:!ring-gray-400">
                <div className="overflow-hidden rounded-xl">
                  {navigation.map((item, i) => {
                    // get icon
                    const ItemIcon = item.icon; 

                    // return jsx
                    return (
                      item === 'divider' ? (
                        <hr key={`divider-${i}`} className="my-1" /> 
                      ) : (
                        <Listbox.Option
                          as={item.href && Link}
                          key={item.id || item.name}
                          href={item.href}
                          value={item.id}
                          onClick={!item.href && item.onClick}
                          className={({ active }) => clsx(
                            'flex flex-row items-center p-4 text-sm cursor-pointer select-none hover:text-white hover:bg-primary-600',
                            active
                              ? 'bg-primary-500 text-white'
                              : ''
                          )}
                        >
                          <ItemIcon className="mr-2 w-5 h-5" />
                          {item.name} 
                        </Listbox.Option>
                      )
                    );
                  })}
                </div>
              </div>
            </Listbox.Options>
          </Transition>
        </Float>
      </Listbox>
      
      <Language
        open={!!langOpen}
        onClose={() => setLangOpen(false)}
        onChange={onLanguage}
        language={lang}
      />
    </>
  );
};

/**
 * teams selector
 */
export default ComponentLayoutLeftbarMenu;