'use client';
import { Button } from '@/components/ui/button';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { signOut, useSession } from 'next-auth/react';
import Image from 'next/image';
import { usePathname, useRouter } from 'next/navigation';
import { CgWebsite } from 'react-icons/cg';
import { MdOutlineLogout } from 'react-icons/md';
import { PiSignInBold } from 'react-icons/pi';
import { RxAvatar } from 'react-icons/rx';
import { IoLogoVercel } from "react-icons/io5";
import { useApiWithToast } from '@/src/hooks/useApiWithToast';
import { UserService } from '@/src/services/UserService';

export function Header() {
  const { data: session, status, update } = useSession();
  const router = useRouter();
  const currentPath = usePathname();
  const { handle } = useApiWithToast();

  const handleVercelLink = async () => {
    if (!session?.user.vercelAccessToken) {
      await UserService.connectToVercel();
    } else {
      await handle(UserService.unlinkVercel(session.user.id), {
        messageOnSuccess: 'Successfully unlinked Vercel account',
        messageOnError: 'Failed to unlink Vercel account',
      });
    }
    await update({ ...session, vercelAccessToken: null });
  };

  return (
    <div className='bg-neutral-900 w-auto flex flex-row justify-between items-center p-4 text-white fixed top-0 left-0 right-0 border-b-[1px] border-neutral-300 z-[200]'>
      <button className='font-bold text-xl cursor-pointer' onClick={() => router.push('/')}>
        Portfolio Builder
      </button>

      {(() => {
        if (currentPath === '/login' || currentPath.startsWith('/register')) {
          return null;
        }

        if (status === 'loading') {
          return <div className='w-10 h-10 bg-neutral-700 rounded-full animate-pulse' />;
        }

        if (status === 'authenticated') {
          return (
            <DropdownMenu modal={false}>
              <DropdownMenuTrigger className='relative'>
                {session.user?.image ? (
                  <Image
                    src={session.user.image}
                    alt={session.user.name || 'User'}
                    className='w-10 h-10 rounded-full'
                    width={40}
                    height={40}
                  />
                ) : (
                  <RxAvatar className='w-10 h-10 text-white' />
                )}
              </DropdownMenuTrigger>
              <DropdownMenuContent className='bg-neutral-900 border-[1px] border-neutral-300 text-white mr-2 z-[250]'>
                <DropdownMenuLabel className='flex flex-col items-end'><p>{session.user?.email || 'My Account'}</p>{session.user?.username ?? ''}</DropdownMenuLabel>
                <DropdownMenuSeparator />
                <DropdownMenuItem
                  className='flex flex-row gap-2 items-center'
                  onClick={() => router.push('/dashboard')}
                >
                  <CgWebsite />
                  Dashboard
                </DropdownMenuItem>
                {process.env.NODE_ENV === 'production' && (
                <DropdownMenuItem
                  className='flex flex-row gap-2 items-center'
                  onClick={handleVercelLink}
                >
                  <IoLogoVercel />
                  {session.user.vercelAccessToken ? 'Unlink Vercel Account' : 'Link Vercel Account'}
                </DropdownMenuItem>
                )}
                <DropdownMenuItem
                  className='flex flex-row gap-2 items-center'
                  onClick={() => {
                    signOut({ redirect: true, callbackUrl: '/' });
                  }}
                >
                  <MdOutlineLogout />
                  Logout
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          );
        }

        return (
          <div className='flex gap-2'>
            <Button variant='light' onClick={() => router.push('/login')}>
              <PiSignInBold />
              Sign In
            </Button>
          </div>
        );
      })()}
    </div>
  );
}
