'use client';
import Image from 'next/image';
import Link from 'next/link';
import { useEffect, useRef, useState } from 'react';
import { FiSearch, FiUser } from 'react-icons/fi';
import { HiShoppingBag } from 'react-icons/hi2';

// import logoWhite from '/public/images/logo-white.svg';
import logoBlack from '/public/images/logo-black.svg';

import styles from './navbar.module.css';

import { useCustomer } from '@/providers/customer';

// components/Navbar.tsx
export function Navbar() {
  const { customer, logout } = useCustomer();

  const prevScrollY = useRef(0);
  const [navBarStyle, setNavBarStyle] = useState('initial');
  const [isVisible, setIsVisible] = useState('false');
  const [isExpanded, setIsExpanded] = useState<boolean>(false);

  // New piece of state for the profile dropdown
  const [isProfileDropdownOpen, setIsProfileDropdownOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleScroll = () => {
      const currentScrollY = window.scrollY;
      if (currentScrollY > prevScrollY.current && currentScrollY > 100) {
        // Scrolling down and scrolled past 100px
        setNavBarStyle('initial');
      } else if (currentScrollY < prevScrollY.current && currentScrollY > 100) {
        // Scrolling up and scrolled past 100px
        setNavBarStyle('scrolledUp');
      } else if (currentScrollY <= 100) {
        setNavBarStyle('initial');
      }
      prevScrollY.current = currentScrollY;
    };
    window.addEventListener('scroll', handleScroll);

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

  // Close dropdown if you click outside of it
  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsProfileDropdownOpen(false);
      }
    }
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  // const navClasses = `${styles.navBar} ${
  //   navBarStyle === 'scrolledUp'
  //     ? styles.navBarScrolledUp
  //     : styles.navBarInitial
  // }`;

  //Hack for now
  const navClasses = `${styles.navBar} ${
    navBarStyle === 'scrolledUp' ? styles.navBarScrolledUp : styles.navBarScrolledUp
  }`;

  function toggleMenu() {
    if (isVisible === 'true') {
      setIsVisible('false');
      setIsExpanded(false);
    } else {
      setIsVisible('true');
      setIsExpanded(true);
    }
  }

  // You can define your logout function here or in the customer provider
  const handleLogout = () => {
    logout();
    console.log('User logged out');
    // Optionally redirect or handle client-side state cleanup
  };

  return (
    <div>
      <button
        className={styles.mobileNavToggle}
        aria-controls='primary-navigation'
        aria-expanded={isExpanded}
        onClick={toggleMenu}
      >
        <span className='sr-only'>Menu</span>
      </button>
      <nav data-visible={isVisible} className={navClasses}>
        {/* Left side */}
        <div>
          <Link href='/about-us' className='font-light animated-underline'>
            About Us
          </Link>
          <Link href='https://shop.mozimo.in' className='font-light animated-underline'>
            Shop
          </Link>
        </div>
        {/* Middle */}
        <div className='flex-shrink'>
          <Link href='/' className='text-lg font-bold'>
            <Image
              src={logoBlack}
              // src={navBarStyle === 'scrolledUp' ? logoWhite : logoBlack}
              alt='Logo'
              className='h-full logo'
              width={100}
              height={100}
            />
          </Link>
        </div>
        {/* Right side */}
        <div className=''>
          <button aria-label='Search' className='rounded-full hover:shadow-md'>
            <FiSearch size={20} className='m-2.5' />
          </button>

          {/* Show dropdown if user is logged in */}
          {customer && customer.id ? (
            <div ref={dropdownRef} className='relative'>
              <button
                onClick={() => setIsProfileDropdownOpen((prev) => !prev)}
                className='rounded-full hover:shadow-md'
              >
                <FiUser size={20} className='m-2.5' />
              </button>

              {isProfileDropdownOpen && (
                <div className='absolute right-0 mt-2 w-44 bg-white border rounded-md shadow-md p-2 text-sm z-50'>
                  <Link href='/account/profile' className='block px-2 py-1 hover:bg-gray-100'>
                    Profile
                  </Link>
                  <button onClick={handleLogout} className='block w-full text-left px-2 py-1 hover:bg-gray-100'>
                    Logout
                  </button>
                </div>
              )}
            </div>
          ) : (
            /* If user is not logged in, show the link to login */
            <Link href='/login' className='rounded-full hover:shadow-md'>
              <FiUser size={20} className='m-2.5' />
            </Link>
          )}
          <a aria-label='Shopping Cart' href='https://shop.mozimo.in' className='rounded-full hover:shadow-md'>
            <HiShoppingBag size={20} className='m-2.5' />
          </a>
        </div>
      </nav>
    </div>
  );
}
