import { useProductContext } from '@/contexts/ProductContext';
import useAuth from '@/core/hooks/useAuth';
import { getCountCart } from '@/core/utils/cart';
import { createSlug } from '@/core/utils/slug';
import whatsappUrl from '@/core/utils/whatsappUrl';
import IndoteknikLogo from '@/images/logo.png';
import Cardheader from '@/lib/cart/components/Cartheader';
import Category from '@/lib/category/components/Category';
import {
  ChevronDownIcon,
  DocumentCheckIcon,
  HeartIcon,
  ArrowUpRightIcon,
} from '@heroicons/react/24/outline';
import dynamic from 'next/dynamic';
import Image from 'next/image';
import { useRouter } from 'next/router';
import { useCallback, useEffect, useState } from 'react';
import DesktopView from '../../views/DesktopView';
import Link from '../Link/Link';
import NavbarUserDropdown from './NavbarUserDropdown';
import NextImage from 'next/image';
import {
  Button,
  Menu,
  MenuButton,
  MenuItem,
  MenuList,
  useDisclosure,
} from '@chakra-ui/react';
import style from "./style/NavbarDesktop.module.css";

const Search = dynamic(() => import('./Search'), { ssr: false });
const TopBanner = dynamic(() => import('./TopBanner'), { ssr: false });

const NavbarDesktop = () => {
  const [isOpenCategory, setIsOpenCategory] = useState(false);
  const auth = useAuth();

  const [cartCount, setCartCount] = useState(0);

  const [templateWA, setTemplateWA] = useState(null);
  const [payloadWA, setPayloadWa] = useState(null);
  const [urlPath, setUrlPath] = useState(null);

  const router = useRouter();

  const { product } = useProductContext();
  const { isOpen, onOpen, onClose } = useDisclosure();

  const [showPopup, setShowPopup] = useState(false);
  const [isTop, setIsTop] = useState(true);

  const handleTopBannerLoad = useCallback(() => {
    const showTimer = setTimeout(() => {
      setShowPopup(true);
    }, 500);

    const hideTimer = setTimeout(() => {
      // setShowPopup(false);
    }, 9500);

    return () => {
      clearTimeout(showTimer);
      clearTimeout(hideTimer);
    };
  }, []);

  useEffect(() => {
    const handleScroll = () => {
      setIsTop(window.scrollY < 100);
    };

    window.addEventListener('scroll', handleScroll);
    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, []);

  useEffect(() => {
    const handleScroll = () => {
      setIsTop(window.scrollY < 100);
    };

    window.addEventListener('scroll', handleScroll);
    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, []);

  useEffect(() => {
    if (router.pathname === '/shop/product/[slug]') {
      setPayloadWa({
        name: product?.name,
        manufacture: product?.manufacture.name,
        url: createSlug('/shop/product/', product?.name, product?.id, true),
      });
      setTemplateWA('product');

      setUrlPath(router.asPath);
    }
  }, [product, router]);

  useEffect(() => {
    const handleCartChange = () => {
      const cart = async () => {
        const listCart = await getCountCart();
        setCartCount(listCart);
      };
      cart();
    };
    handleCartChange();

    window.addEventListener('localStorageChange', handleCartChange);

    return () => {
      window.removeEventListener('localStorageChange', handleCartChange);
    };
  }, []);

  return (
    <DesktopView>
      <TopBanner onLoad={handleTopBannerLoad} />
      <div className='py-2 bg-warning-400' id='desktop-nav-top'>
        <div className='container mx-auto flex justify-between'>
          <div className='flex items-start gap-5'>
            <div>
              <SocialMedias />
            </div>
          </div>
          <div className='flex gap-x-6'>
            <Menu isOpen={isOpen}>
              <MenuButton
                rightIcon={<ChevronDownIcon />}
                onMouseEnter={onOpen}
                onMouseLeave={onClose}
              >
                <div className='flex gap-x-1'>
                  <div>Fitur Layanan </div>
                  <ChevronDownIcon className='w-5'/>
                </div>
              </MenuButton>
              <MenuList
                zIndex={100}
                onMouseEnter={onOpen}
                onMouseLeave={onClose}
              >
                <MenuItem as='a' href='/tentang-kami'>
                  Tentang Indoteknik
                </MenuItem>
                <MenuItem as='a' href='/my/pembayaran-tempo'>
                  Pembayaran Tempo
                </MenuItem>
              </MenuList>
            </Menu>
            {/* <Link href='/tentang-kami' className='!text-gray_r-12'>
              Tentang Indoteknik.com
            </Link>
            <Link href='/my/pembayaran-tempo' className='!text-gray_r-12'>
              Pembayaran Tempo
            </Link>
            <Link href='/' className='!text-gray_r-12'>
              Fitur Layanan
            </Link> */}
          </div>
        </div>
      </div>

      <nav className='pt-6 sticky top-0 z-50 bg-white border-b-2 border-danger-500'>
        <div className='container mx-auto flex gap-x-6'>
          <Link href='/'>
            <Image
              src={IndoteknikLogo}
              alt='Indoteknik Logo'
              width={210}
              height={210 / 3}
            />
          </Link>
          <div className='flex-1 flex items-center'>
            <Search />
          </div>
          <div className='flex gap-x-4 items-center'>
            <Link
              href='/my/transactions'
              target='_blank'
              rel='noreferrer'
              className='flex items-center gap-x-2 !text-gray_r-12/80'
            >
              <DocumentCheckIcon className='w-7' />
              Daftar
              <br />
              Quotation
            </Link>

            <Cardheader cartCount={cartCount} />

            <Link
              target='_blank'
              rel='noreferrer'
              href='/my/wishlist'
              className='flex items-center gap-x-2 !text-gray_r-12/80'
            >
              <HeartIcon className='w-7' />
              Wishlist
            </Link>
            <a
              href={whatsappUrl(templateWA, payloadWA, urlPath)}
              target='_blank'
              rel='noreferrer'
              className='flex items-center gap-x-1 !text-gray_r-12/80'
            >
              <Image
                src='/images/socials/Whatsapp-2.png'
                alt='Whatsapp'
                width={48}
                height={48}
              />
              <div>
                <div className='font-semibold'>Whatsapp</div>
                0817 1718 1922 (Chat)
              </div>
            </a>
          </div>
        </div>

        <div className='container mx-auto mt-6'>
          <div className='flex'>
            <button
              type='button'
              onClick={() => setIsOpenCategory((isOpen) => !isOpen)}
              onBlur={() => setIsOpenCategory(false)}
              className='w-3/12 p-4 font-semibold border border-gray_r-6 rounded-t-xl flex items-center relative'
            >
              <div>Kategori Produk</div>
              <ChevronDownIcon
                className={`ml-auto w-6 ${isOpenCategory ? 'rotate-180' : ''}`}
              />

              <div
                className={`category-mega-box-wrapper ${
                  isOpenCategory ? 'show' : ''
                }`}
              >
                <Category />
              </div>
            </button>
            <div className='w-6/12 flex px-1 divide-x divide-gray_r-6'>
            
            <Link
                href="/shop/promo"
                className={`${
                  router.asPath === '/shop/promo' && 'bg-gray_r-3'
                }  flex-1 flex justify-center items-center !text-gray_r-12/80 hover:bg-gray_r-3 idt-transition group relative`} // Added relative position
                target="_blank"
                rel="noreferrer"
              >
                <p className="absolute inset-0 flex justify-center items-center group-hover:scale-105 group-hover:text-red-500 transition-transform duration-200 z-10">Semua Promo</p>
              </Link>
              {/* {showPopup && router.pathname === '/' && (
                <div className={`fixed ${isTop ? 'top-[170px]' : 'top-[90px]'} rounded-3xl left-[700px] w-fit object-center bg-green-50 text-xs font-medium text-green-700 ring-1 ring-inset ring-green-600/20 text-center p-2 z-50 transition-all duration-300`}>
                  <p className='w-36 h-3'>
                    Penawaran Terbatas
                    </p>
                </div>
              )} */}
              {showPopup && router.pathname === '/' && (
                <Image
                src='/images/penawaran-terbatas.svg'
                alt='penawaran terbatas'
                width={144}
                height={3}
                className={`fixed ${isTop ? 'top-[-275px]' : 'top-[-345px]'} rounded-3xl left-[680px] w-48 h-full  p-2 z-50 transition-all duration-300`}
              />
              )}
              

              <Link
                href='/shop/brands'
                className={`${  
                  router.asPath === '/shop/brands' && 'bg-gray_r-3'
                } p-4 flex-1 flex justify-center items-center !text-gray_r-12/80 hover:bg-gray_r-3 idt-transition group`}
                target='_blank'
                rel='noreferrer'
              >
               <p className="group-hover:scale-105 group-hover:text-red-500 transition-transform duration-200">Semua Brand</p>
              </Link>
              <Link
                href='/shop/search?orderBy=stock'
                className={`${
                  router.asPath === '/shop/search?orderBy=stock' &&
                  'bg-gray_r-3'
                } p-4 flex-1 flex justify-center items-center !text-gray_r-12/80 hover:bg-gray_r-3 idt-transition group`}
                target='_blank'
                rel='noreferrer'
              >
                <p className="group-hover:scale-105 group-hover:text-red-500 transition-transform duration-200">Ready Stock</p>
              </Link>
              <Link
                href='https://blog.indoteknik.com/'
                className='p-4 flex-1 flex justify-center items-center !text-gray_r-12/80 hover:bg-gray_r-3 idt-transition group'
                target='_blank'
                rel='noreferrer noopener'
              >
                <p className="group-hover:scale-105 group-hover:text-red-500 transition-transform duration-200">Blog Indoteknik</p>
              </Link>
              {/* <Link
                href='/video'
                className='p-4 flex-1 flex justify-center items-center !text-gray_r-12/80 hover:bg-gray_r-3 idt-transition'
                target='_blank'
                rel='noreferrer'
              >
                Indoteknik TV
              </Link> */}
            </div>

            <div className='w-3/12 flex gap-x-1 relative'>
              {!auth && (
                <>
                  <Link
                    href='/login'
                    className='flex-1 flex justify-center items-center bg-danger-500 !text-gray_r-1 rounded-none rounded-t-xl'
                  >
                    Masuk
                  </Link>
                  <Link
                    href='/register'
                    className='flex-1 flex justify-center items-center bg-danger-500 !text-gray_r-1 rounded-none rounded-t-xl'
                  >
                    Daftar
                  </Link>
                </>
              )}
              {auth && (
                <>
                  <div href='/' className='navbar-user-dropdown-button'>
                    <span>Halo, {auth?.name}</span>
                    <div className='ml-auto'>
                      <ChevronDownIcon className='w-6' />
                    </div>
                  </div>
                  <NavbarUserDropdown />
                </>
              )}
            </div>
          </div>
        </div>
      </nav>
    </DesktopView>
  );
};

const SocialMedias = () => (
  <div>
    {/* <div className={headerClassName + 'block md:hidden'}>Temukan Kami</div> */}
    <div className='flex flex-wrap gap-3 items-start'>
      <a
        target='_blank'
        rel='noreferrer'
        href='https://www.youtube.com/@indoteknikcom'
      >
        <NextImage
          src='/images/socials/youtube.webp'
          alt='Youtube - Indoteknik.com'
          width={24}
          height={24}
        />
      </a>
      <a
        target='_blank'
        rel='noreferrer'
        href='https://www.tiktok.com/@indoteknikcom'
      >
        <NextImage
          src='/images/socials/tiktok.png'
          alt='TikTok - Indoteknik.com'
          width={24}
          height={24}
        />
      </a>
      {/* <a target='_blank' rel='noreferrer' href={whatsappUrl(null)}>
        <NextImage
          src='/images/socials/Whatsapp.png'
          alt='Whatsapp - Indoteknik.com'
          width={24}
          height={24}
        />
      </a> */}
      <a
        target='_blank'
        rel='noreferrer'
        href='https://www.facebook.com/indoteknikcom'
      >
        <NextImage
          src='/images/socials/Facebook.png'
          alt='Facebook - Indoteknik.com'
          width={24}
          height={24}
        />
      </a>
      <a
        target='_blank'
        rel='noreferrer'
        href='https://www.instagram.com/indoteknikcom/'
      >
        <NextImage
          src='/images/socials/Instagram.png'
          alt='Instagram - Indoteknik.com'
          width={24}
          height={24}
        />
      </a>
      <a
        target='_blank'
        rel='noreferrer'
        href='https://www.linkedin.com/company/pt-indoteknik-dotcom-gemilang/'
      >
        <NextImage
          src='/images/socials/Linkedin.png'
          alt='Linkedin - Indoteknik.com'
          width={24}
          height={24}
        />
      </a>
      <a
        target='_blank'
        rel='noreferrer'
        href='https://goo.gl/maps/GF8EmDjpQTHZPsJ1A'
      >
        <NextImage
          src='/images/socials/g_maps.png'
          alt='Maps - Indoteknik.com'
          width={24}
          height={24}
        />
      </a>
    </div>
  </div>
);

export default NavbarDesktop;
