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

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

  const searchParamsString = searchParams.toString()
  const redirectURL = `${pathname}${searchParamsString ? `?${searchParamsString}` : ''}`

  const isImageCreatePage = ['/generate/image', '/generate/image-2-image', '/generate/image-edit', '/generate/image-2-background'].includes(pathname);

  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 && user.cpUserInfo) {
      router.push("/login/fields?redirect=" + encodeURIComponent(redirectURL))
    }
  }, [user])

  return (
    <header className={cn("fixed top-0 left-20 right-0 z-40 flex h-16 items-center justify-between px-8 transition-all", {
      "backdrop-blur-[10px]": isBlur,
      "left-80": isSidebarExpanded,
      "left-0": isImageCreatePage,
    })}>
      {isBlur && <div className="absolute inset-0 bg-background-default opacity-85" />}
      <div className="relative inset-0 flex items-center justify-between w-full">
        <div className="w-[103.6px] h-8">
          <Link href="/">
            <Image src="/logo.svg" alt="logo" width={103.6} height={32} />
          </Link>
        </div>
        {user ? (
          <Link href="/profile">
            <Avatar className="cursor-pointer size-8">
              <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={`/login?redirect=${encodeURIComponent(redirectURL)}`}>
            <Button size="small">Login in or Sign up</Button>
          </Link>
        )}
      </div>
    </header>
  )
}

export default Topbar 