'use client';
import { useEffect, useState } from 'react';
import { cn } from '@/lib/utils';
import { Button, IconButton } 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';
import Notice from './components/Notice';
import LocaleSwitch from './components/LocaleSwitch';
import { items } from './BottomBar';
import { getTopbarConfig } from './config';
import IconFont from '@/components/ui/iconFont';
import { useLayoutStore } from '@/stores';

function Topbar() {
  const [isScrollBlur, setIsScrollBlur] = useState(false);
  const { data: user, isLoading } = useCurrentUser();
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const response = useLayoutStore((s) => s.response);
  const searchParamsString = searchParams.toString();
  const redirectURL = `${pathname}${searchParamsString ? `?${searchParamsString}` : ''}`;
  const loginHref = `/login?redirect=${encodeURIComponent(redirectURL)}`;

  // 获取当前路由的 Topbar 配置
  const routeConfig = getTopbarConfig(pathname);

  useEffect(() => {
    function handleScroll(event: Event) {
      const dom = event.target as HTMLElement;
      setIsScrollBlur(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('/login');
    } else {
      router.prefetch('/profile');
    }
  }, [user]);

  const leftDomRender = () => {
    if (!response) return null;
    if (response.sm || items.some((item) => item.path === pathname)) {
      return (
        <Link href="/">
          <IconFont
            size={response.sm ? 150 : 100}
            className="text-white cursor-pointer"
            type="icon-Logo"
          />
        </Link>
      );
    }
    return (
      <IconButton
        variant="ghost"
        size="large"
        onClick={() => router.back()}
        iconfont="icon-arrow-left"
      />
    );
  };

  const rightDomRender = () => {
    if (!response || isLoading) return null;

    const items = [
      {
        dom: <LocaleSwitch key="locale-switch" />,
      },
      {
        hide: !user,
        dom: <Notice key="notice" />,
      },
      {
        hide: !user,
        dom: (
          <Link href="/profile" prefetch key="profile">
            <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>
        ),
      },
      {
        hide: user,
        dom: (
          <Link href={loginHref} prefetch key="login">
            <Button size="small">Login in</Button>
          </Link>
        ),
      },
    ].filter((item) => !item.hide);

    return <div className="flex items-center">{items.map((item) => item.dom)}</div>;
  };

  // 移动端根据配置决定是否隐藏 Topbar
  const isMobile = response && !response.sm;
  if (isMobile && routeConfig.hideOnMobile) {
    return null;
  }

  // 计算最终是否需要模糊效果（滚动模糊 或 路由配置模糊）
  const shouldBlur = isScrollBlur || routeConfig.enableBlur;

  return (
    <header
      className={cn('flex h-16 w-full items-center justify-between px-4 sm:px-8 transition-all', {
        'backdrop-blur-[10px]': shouldBlur,
      })}
    >
      {shouldBlur && <div className="bg-background-default absolute inset-0 opacity-85" />}
      <div className="relative inset-0 flex w-full items-center justify-between">
        {leftDomRender()}
        {rightDomRender()}
      </div>
    </header>
  );
}

export default Topbar;
