'use client';
import React, { useEffect, useState } from 'react';
import { cn } from '@/lib/utils';
import Image from 'next/image';
import { Button } from '../components/ui/button';
import { useCurrentUser } from '@/hooks/auth';
import { Avatar, AvatarFallback, AvatarImage } from '../components/ui/avatar';
import Link from 'next/link';
import { usePathname, useSearchParams, useRouter } from 'next/navigation';

function Topbar() {
  const [isBlur, setIsBlur] = useState(false);
  const { data: user } = useCurrentUser();
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  const searchParamsString = searchParams.toString();
  const redirectURL = `${pathname}${searchParamsString ? `?${searchParamsString}` : ''}`;
  const loginHref = `/login?redirect=${encodeURIComponent(redirectURL)}`;

  useEffect(() => {
    function handleScroll(event: Event) {
      const dom = event.target as HTMLElement;
      setIsBlur(dom.scrollTop > 0);
    }
    const dom = document.getElementById('main-content');
    if (dom) {
      dom.addEventListener('scroll', handleScroll, { passive: true });
    }
    return () => {
      if (dom) {
        dom.removeEventListener('scroll', handleScroll);
      }
    };
  }, []);

  useEffect(() => {
    if (!user) {
      router.prefetch(loginHref);
    } else {
      router.prefetch('/profile');
      if (user.cpUserInfo) {
        router.push('/login/fields?redirect=' + encodeURIComponent(redirectURL));
      }
    }
  }, [user]);

  return (
    <header
      className={cn(
        'absolute z-40 flex h-16 w-full items-center justify-between px-8 transition-all',
        {
          'backdrop-blur-[10px]': isBlur,
        }
      )}
    >
      {isBlur && <div className="bg-background-default absolute inset-0 opacity-85" />}
      <div className="relative inset-0 flex w-full items-center justify-between">
        <div className="h-8 w-[103.6px]">
          <Link href="/">
            <Image src="/logo.svg" alt="logo" width={103.6} height={32} />
          </Link>
        </div>
        {user ? (
          <Link href="/profile" prefetch>
            <Avatar className="size-8 cursor-pointer">
              <AvatarImage
                className="object-cover"
                src={user.headImage}
                alt={user.nickname}
                width={32}
                height={32}
              />
              <AvatarFallback>{user.nickname?.slice(0, 1)}</AvatarFallback>
            </Avatar>
          </Link>
        ) : (
          <Link href={loginHref} prefetch>
            <Button size="small">Login in / Sign up</Button>
          </Link>
        )}
      </div>
    </header>
  );
}

export default Topbar;
