import { motion } from 'framer-motion';
import { PropsWithChildren, useRef, useState } from 'react';
import { AnchorLink } from '../../ui/AnchorLink';
import { Link } from 'react-router-dom';
import { useLanguageStore } from '../../store/languageStore';
import { useOnClickOutside } from 'usehooks-ts';
import { useModalStore } from '../../store/modalStore';
import { ModalWithForm } from '../Main/ModalWithForm';
import { Button } from '../../ui/Button';
import { LogoWithTextIcon } from '../icons/LogoWithTextIcon';
import { LogoIcon } from '../icons/LogoIcon';
import { BurgerIcon } from '../icons/BurgerIcon';
import { CloseIcon } from '../icons/CloseIcon';
import { CubeIcon } from '../icons/CubeIcon';
import { useWindowWidth } from '../../hooks/useWindowWidth';

export function Header() {
  const [menuOpen, setMenuOpen] = useState(false);
  const setModal = useModalStore(state => state.setModal);

  const menuRef = useRef<HTMLDivElement>(null);
  const menuBtnRef = useRef<HTMLButtonElement>(null);
  useOnClickOutside<HTMLDivElement | HTMLButtonElement>(
    [menuRef, menuBtnRef],
    () => setMenuOpen(false),
  );

  const width = useWindowWidth();

  return (
    <header className="w-full">
      <nav className="flex justify-between border-b border-[#3D425C] lg:pl-10 pl-4 lg:max-h-[72px] min-h-16">
        <Link to={'/'} className="flex items-center outline-none">
          <LogoIcon className="lg:hidden" />
          {width >= 1024 && <LogoWithTextIcon className="w-[104px]" />}
        </Link>
        <div className="flex mx-auto">
          <AnchorLink route="#products">Типы тренажеров</AnchorLink>
          <AnchorLink route="#trainings">Варианты комплектации</AnchorLink>
          <AnchorLink route="#projects">Проекты</AnchorLink>
        </div>
        <Button
          onClick={() => setModal(<ModalWithForm />)}
          className="px-10 font-semibold rounded-none btn-text max-sm:hidden"
        >
          Оставить заявку
        </Button>
        {/* <LangToggler lang={lang} /> */}
        <button
          ref={menuBtnRef}
          onClick={() => setMenuOpen(prev => !prev)}
          className="px-6 py-5 xl:hidden border-[#3D425C] max-sm:border-l outline-none"
        >
          {!menuOpen ? <BurgerIcon /> : <CloseIcon />}
        </button>
      </nav>
      <motion.div
        initial={{ opacity: 0, visibility: 'hidden' }}
        animate={{
          opacity: +menuOpen,
          visibility: menuOpen ? 'visible' : 'hidden',
        }}
        transition={{ duration: 0.2 }}
        ref={menuRef}
        onClick={() => setMenuOpen(false)}
        className={
          'absolute z-50 w-full min-[1350px]:hidden sm:max-[1350px]:max-w-[340px] right-0' +
          (menuOpen ? ' shadow-[0_0_0_9999px_rgba(0,0,0,.4)]' : '')
        }
      >
        <div>
          <BurgerAnchor route="#products">Типы тренажеров</BurgerAnchor>
          <BurgerAnchor route="#trainings">Варианты комплектации</BurgerAnchor>
          <BurgerAnchor route="#projects">Проекты</BurgerAnchor>
        </div>
        <div className="grid grid-cols-[2fr_1fr_1fr] sm:grid-cols-2">
          <Button
            onClick={() => {
              setMenuOpen(false);
              setModal(<ModalWithForm />);
            }}
            width="full"
            className="font-semibold rounded-none outline-none sm:hidden btn-text"
          >
            Оставить заявку
          </Button>
          <ChooseLang currentLang="RU" />
          <ChooseLang currentLang="EN" />
        </div>
      </motion.div>
    </header>
  );
}

function BurgerAnchor({
  children,
  route,
}: PropsWithChildren<{ route: string }>) {
  return (
    <Link
      to={route}
      className="flex gap-x-1 items-center px-10 py-6 gap-1 btn-text bg-[#14161F] w-full hover:bg-[#3D425C] last:border-b-0 [&:not(:last-child)]:border-b sm:border-l font-semibold border-[#3D425C] lg:hover:bg-[#3D425C] active:bg-[#14161F]"
    >
      <CubeIcon />
      {children}
    </Link>
  );
}

function ChooseLang({ currentLang }: { currentLang: 'RU' | 'EN' }) {
  const { setLang, lang } = useLanguageStore();

  return (
    <button
      onClick={() => setLang(currentLang)}
      className={
        'min-h-[72px] w-full h-full btn-text font-semibold bg-[#14161F] sm:hover:bg-[#3D425C] border active:bg-[#14161F] outline-none ' +
        (lang === currentLang
          ? '[border-image:linear-gradient(to_right,#798FFF,#D375FF)_3]'
          : 'border-[#3D425C]')
      }
    >
      {currentLang}
    </button>
  );
}

// function LangToggler({ lang }: { lang: Lang }) {
//   const [open, setOpen] = useState(false);
//   const langTogglerRef = useRef<HTMLButtonElement>(null);
//   useOnClickOutside(langTogglerRef, () => setOpen(false));
//   const hovered = useHover(langTogglerRef);

//   return (
//     <div
//       className="max-w-[101px]s max-xl:hidden relative"
//       style={{ backgroundColor: hovered ? '#3D425C' : 'transparent' }}
//     >
//       <button
//         ref={langTogglerRef}
//         onClick={() => setOpen(prev => !prev)}
//         className="flex items-center h-full mx-6 font-semibold outline-none gap-x-1 btn-text"
//       >
//         {lang}
//         <ChevronDownIcon />
//       </button>
//       <AnimatePresence>
//         <motion.div
//           className="absolute z-20 grid grid-cols-2 min-w-[101px]s w-full"
//           onClick={() => setOpen(false)}
//           initial={{ visibility: 'hidden', opacity: 0 }}
//           animate={{
//             visibility: open ? 'visible' : 'hidden',
//             opacity: +open,
//           }}
//           exit={{ visibility: 'hidden', opacity: 0 }}
//         >
//           <ChooseLang currentLang={'RU'} />
//           <ChooseLang currentLang={'EN'} />
//         </motion.div>
//       </AnimatePresence>
//     </div>
//   );
// }
