'use client';

import toast from 'react-hot-toast';
import { useRouter } from 'next/navigation';

import { Icon } from '@iconify/react';
import Menu from '@/components/menu/Menu';
import MenuItem from '@/components/menu/MenuItem';
import Button from '@/components/Button';
import Dropdown from '@/components/dropdown/Dropdown';

import { useAuth } from '@/services/hooks/useAuth';
import { AuthApi } from '@/services/api/auth';
import { isResponseError } from '@/lib/api-helper';

interface NavbarProps {
  title: string;
  toggleSidebar?: () => void;
}

const Navbar = ({ title, toggleSidebar }: NavbarProps) => {
  const { setUser } = useAuth();
  const router = useRouter();

  const logoutClickHandler = async () => {
    const logoutRes = await AuthApi.logout();

    if (isResponseError(logoutRes)) {
      toast.error('Gagal logout! Coba lagi!');
      return;
    }

    setUser(undefined);
    router.replace(process.env.NEXT_PUBLIC_SSO_LOGIN_URL as string);
  };

  return (
    <div className='navbar px-4 bg-base-100 shadow-sm'>
      <div className='flex-1'>
        <div className='flex flex-row items-center gap-4'>
          {toggleSidebar && (
            <Button onClick={toggleSidebar} className='block lg:hidden'>
              <Icon
                icon='material-symbols:menu-rounded'
                width={24}
                height={24}
              />
            </Button>
          )}

          <span className='font-bold text-xl text-primary'>{title}</span>
        </div>
      </div>

      <div className='flex gap-2'>
        <Dropdown
          position='bottom-end'
          trigger={
            <div className='btn btn-ghost btn-circle avatar'>
              <div className='w-10 rounded-full border flex justify-center items-center'>
                <Icon icon='uil:user' width={40} height={40} />
              </div>
            </div>
          }
          contentClassName='w-52 mt-3'
        >
          <Menu className='p-2 bg-base-100 shadow rounded-box menu-sm'>
            <MenuItem title='Logout' onClick={logoutClickHandler} />
          </Menu>
        </Dropdown>
      </div>
    </div>
  );
};

export default Navbar;
