import {
  ChevronDownIcon,
  HeartIcon,
  ShoppingCartIcon,
  DocumentCheckIcon
} from '@heroicons/react/24/outline'
import Link from '../Link/Link'
import Image from 'next/image'
import DesktopView from '../../views/DesktopView'
import dynamic from 'next/dynamic'
import IndoteknikLogo from '@/images/logo.png'
import Category from '@/lib/category/components/Category'
import { useContext, useEffect, useState } from 'react'
import useAuth from '@/core/hooks/useAuth'
import NavbarUserDropdown from './NavbarUserDropdown'
import { getCountCart } from '@/core/utils/cart'
import TopBanner from './TopBanner'
import whatsappUrl from '@/core/utils/whatsappUrl'
import { useRouter } from 'next/router'
import { getAuth, setAuth } from '@/core/utils/auth'
import { createSlug, getIdFromSlug } from '@/core/utils/slug'
import productApi from '@/lib/product/api/productApi'
import { useSession } from 'next-auth/react'
import { AuthContext } from '@/pages/_app'

const Search = dynamic(() => import('./Search'))

const NavbarDesktop = () => {
  const [isOpenCategory, setIsOpenCategory] = useState(false)
  const {authenticated} = useContext(AuthContext)
  const auth = useAuth()

  const [cartCount, setCartCount] = useState(0)

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

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

    window.addEventListener('localStorageChange', handleCartChange)
    if (router.pathname === '/shop/product/[slug]') {
      const authToken = getAuth().token

      const { slug } = router.query
      const getProduct = async () => {
        let product = await productApi({ id: getIdFromSlug(slug), headers: { Token: authToken } })
        setPayloadWa({
          name: product[0]?.name,
          manufacture: product[0]?.manufacture.name,
          url: createSlug('/shop/product/', product[0]?.name, product[0]?.id, true)
        })
      }
      getProduct()
      setTemplateWA('product')
    }

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

  return (
    <DesktopView>
      <TopBanner />
      <div className='py-3 bg-warning-400' id='desktop-nav-top'>
        <div className='container mx-auto flex justify-between'>
          <Link href='/tentang-kami' className='!text-gray_r-12'>
            Tentang Indoteknik.com
          </Link>
          <div className='flex gap-x-6'>
            <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'>
            <Link href='/my/transactions' className='flex items-center gap-x-2 !text-gray_r-12/80'>
              <DocumentCheckIcon className='w-7' />
              Daftar
              <br />
              Quotation
            </Link>
            <Link href='/shop/cart' className='flex items-center gap-x-2 !text-gray_r-12/80'>
              <div className={`relative ${cartCount > 0 && 'mr-2'}`}>
                <ShoppingCartIcon className='w-7' />
                {cartCount > 0 && (
                  <span className='absolute -top-2 -right-2 badge-solid-red rounded-full w-5 h-5 flex items-center justify-center'>
                    {cartCount}
                  </span>
                )}
              </div>
              <span>
                Keranjang
                <br />
                Belanja
              </span>
            </Link>
            <Link 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)}
              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>
                0812 8080 622 (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/brands'
                className='p-4 flex-1 flex justify-center items-center !text-gray_r-12/80 hover:bg-gray_r-3 idt-transition'
              >
                Semua Brand
              </Link>
              <Link
                href='/shop/search?orderBy=stock'
                className='p-4 flex-1 flex justify-center items-center !text-gray_r-12/80 hover:bg-gray_r-3 idt-transition'
              >
                Ready Stock
              </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'
                target='_blank'
                rel='noreferrer noopener'
              >
                Blog Indoteknik
              </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'
              >
                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>
  )
}

export default NavbarDesktop
