"use client";

import * as React from "react";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuLabel,
    DropdownMenuSeparator,
    DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
    NavigationMenu,
    NavigationMenuContent,
    NavigationMenuItem,
    NavigationMenuLink,
    NavigationMenuList,
    NavigationMenuTrigger,
    navigationMenuTriggerStyle,
} from "@/components/ui/navigation-menu";
import { SearchIcon, BellIcon, Menu } from "lucide-react";
import { useParams, usePathname, useSearchParams  } from "next/navigation";
import { cn } from "@/lib/utils";
import Image from "next/image";
import { 
    mainNav, 
    additionalNav, 
    additional2Nav,
    procurementNav,
    salesNav,
    engineeringNav,
    MenuSection, 
    MenuItem, 
    mainNavVendor, 
    additionalNavVendor,
    domainBrandingKeys
} from "@/config/menuConfig";
import { MobileMenu } from "./MobileMenu";
import { CommandMenu } from "./command-menu";
import { useSession, signOut } from "next-auth/react";
import GroupedMenuRenderer from "./GroupedMenuRender";
import { useActiveMenus, filterActiveMenus, filterActiveAdditionalMenus } from "@/hooks/use-active-menus";
import { NotificationDropdown } from "./NotificationDropdown";
import { useTranslation } from '@/i18n/client'

export function Header() {
    const params = useParams();
    const lng = params?.lng as string;
    const pathname = usePathname();
    const { data: session } = useSession();
    const { activeMenus, isLoading } = useActiveMenus();
    const { t } = useTranslation(lng, 'menu');


    const userName = session?.user?.name || ""; 
    const domain = session?.user?.domain || ""; 
    const initials = userName
        .split(" ")
        .map((word) => word[0]?.toUpperCase())
        .join("");

    const [isMobileMenuOpen, setIsMobileMenuOpen] = React.useState(false);

    const toggleMobileMenu = () => {
        setIsMobileMenuOpen(!isMobileMenuOpen);
    };

    // 도메인별 메뉴 및 브랜딩 정보 가져오기
    const getDomainConfig = (pathname: string) => {
        if (pathname?.includes("/partners")) {
            return {
                main: mainNavVendor,
                additional: additionalNavVendor,
                logoHref: `/${lng}/partners`,
                brandNameKey: domainBrandingKeys.partners,
                basePath: `/${lng}/partners`
            };
        }
        
        if (pathname?.includes("/procurement")) {
            return {
                main: procurementNav,
                additional: additional2Nav,
                logoHref: `/${lng}/procurement`,
                brandNameKey: domainBrandingKeys.procurement,
                basePath: `/${lng}/procurement`
            };
        }
        
        if (pathname?.includes("/sales")) {
            return {
                main: salesNav,
                additional: additional2Nav,
                logoHref: `/${lng}/sales`,
                brandNameKey: domainBrandingKeys.sales,
                basePath: `/${lng}/sales`
            };
        }
        
        if (pathname?.includes("/engineering")) {
            return {
                main: engineeringNav,
                additional: additional2Nav,
                logoHref: `/${lng}/engineering`,
                brandNameKey: domainBrandingKeys.engineering,
                basePath: `/${lng}/engineering`
            };
        }
        
        // 기본값: /evcp (전체 메뉴)
        return {
            main: mainNav,
            additional: additionalNav,
            logoHref: `/${lng}/evcp`,
            brandNameKey: domainBrandingKeys.evcp,
            basePath: `/${lng}/evcp`
        };
    };

    const { main: originalMain, additional: originalAdditional, logoHref, brandNameKey, basePath } = getDomainConfig(pathname);

    // 활성 메뉴만 필터링 (로딩 중이거나 에러 시에는 모든 메뉴 표시)
    const main = isLoading ? originalMain : filterActiveMenus(originalMain, activeMenus);
    const additional = isLoading ? originalAdditional : filterActiveAdditionalMenus(originalAdditional, activeMenus);


    return (
        <>
            <header className="border-grid sticky top-0 z-40 w-full border-b bg-slate-100 backdrop-blur supports-[backdrop-filter]:bg-background/60">
                <div className="container-wrapper">
                    <div className="container flex h-14 items-center">
                        {/* 햄버거 메뉴 버튼 (모바일) */}
                        <Button
                            onClick={toggleMobileMenu}
                            variant="ghost"
                            className="-ml-2 mr-2 h-8 w-8 px-0 text-base hover:bg-transparent focus-visible:bg-transparent focus-visible:ring-0 focus-visible:ring-offset-0 md:hidden"
                        >
                            <svg
                                xmlns="http://www.w3.org/2000/svg"
                                fill="none"
                                viewBox="0 0 24 24"
                                strokeWidth="1.5"
                                stroke="currentColor"
                                className="!size-6"
                            >
                                <path
                                    strokeLinecap="round"
                                    strokeLinejoin="round"
                                    d="M3.75 9h16.5m-16.5 6.75h16.5"
                                />
                            </svg>
                            <span className="sr-only">{t('menu.toggle_menu')}</span>
                        </Button>

                        {/* 로고 영역 - 도메인별 브랜딩 (번역된) */}
                        <div className="mr-4 flex-shrink-0 flex items-center gap-2 lg:mr-6">
                            <Link href={logoHref} className="flex items-center gap-2">
                                <Image
                                    className="dark:invert"
                                    src="/images/vercel.svg"
                                    alt="EVCP Logo"
                                    width={20}
                                    height={20}
                                />
                                <span className="hidden font-bold lg:inline-block">
                                    {t(brandNameKey)}
                                </span>
                            </Link>
                        </div>
                            
                        {/* 네비게이션 메뉴 - 도메인별 활성화된 메뉴만 표시 (번역된) */}
                        <div className="hidden md:block flex-1 min-w-0">
                            <NavigationMenu className="relative z-50">
                                <div className="w-full overflow-x-auto pb-1">
                                    <NavigationMenuList className="flex-nowrap w-max">
                                        {main.map((section: MenuSection) => (
                                            <NavigationMenuItem key={section.titleKey}>
                                                <NavigationMenuTrigger className="px-2 xl:px-3 text-sm whitespace-nowrap">
                                                    {t(section.titleKey)}
                                                </NavigationMenuTrigger>
                                                
                                                {/* 그룹핑이 필요한 메뉴의 경우 GroupedMenuRenderer 사용 */}
                                                {section.useGrouping ? (
                                                    <NavigationMenuContent className="max-h-[80vh] overflow-y-auto">
                                                        <GroupedMenuRenderer
                                                            items={section.items}
                                                            lng={lng}
                                                            activeMenus={activeMenus}
                                                            t={t}
                                                        />
                                                    </NavigationMenuContent>
                                                ) : (
                                                    <NavigationMenuContent className="max-h-[70vh] overflow-y-auto">
                                                        <ul className="grid w-[400px] gap-3 p-4 md:w-[500px] md:grid-cols-2 lg:w-[600px] ">
                                                            {section.items.map((item) => (
                                                                <ListItem
                                                                    key={item.titleKey}
                                                                    title={t(item.titleKey)}
                                                                    href={`/${lng}${item.href}`}
                                                                >
                                                                    {item.descriptionKey && t(item.descriptionKey)}
                                                                </ListItem>
                                                            ))}
                                                        </ul>
                                                    </NavigationMenuContent>
                                                )}
                                            </NavigationMenuItem>
                                        ))}

                                        {/* 추가 네비게이션 항목 - 도메인별 활성화된 것만 (번역된) */}
                                        {additional.map((item) => (
                                            <NavigationMenuItem key={item.titleKey}>
                                                <Link href={`/${lng}${item.href}`} legacyBehavior passHref>
                                                    <NavigationMenuLink 
                                                        className={cn(
                                                            navigationMenuTriggerStyle(), 
                                                            "px-2 xl:px-3 text-sm whitespace-nowrap"
                                                        )}
                                                    >
                                                        {t(item.titleKey)}
                                                    </NavigationMenuLink>
                                                </Link>
                                            </NavigationMenuItem>
                                        ))}
                                    </NavigationMenuList>
                                </div>
                            </NavigationMenu>
                        </div>

                        {/* 우측 영역 */}
                        <div className="ml-auto flex flex-shrink-0 items-center space-x-2">
                            {/* 데스크탑에서는 CommandMenu, 모바일에서는 검색 아이콘만 */}
                            <div className="hidden md:block md:w-auto">
                                <CommandMenu />
                            </div>
                            <Button variant="ghost" size="icon" className="md:hidden" aria-label={t('common.search')}>
                                <SearchIcon className="h-5 w-5" />
                            </Button>

                            {/* 알림 버튼 */}
                            <NotificationDropdown />

                            {/* 사용자 메뉴 (번역된) */}
                            <DropdownMenu>
                                <DropdownMenuTrigger asChild>
                                    <Avatar className="cursor-pointer h-8 w-8">
                                        <AvatarImage src={`${session?.user?.image}`||"/user-avatar.jpg"} alt="User Avatar" />
                                        <AvatarFallback>
                                            {initials || "?"}
                                        </AvatarFallback>
                                    </Avatar>
                                </DropdownMenuTrigger>
                                <DropdownMenuContent className="w-48" align="end">
                                    <DropdownMenuLabel>{t('user.my_account')}</DropdownMenuLabel>
                                    <DropdownMenuSeparator />
                                    <DropdownMenuItem asChild>
                                        <Link href={`${basePath}/settings`}>{t('user.settings')}</Link>
                                    </DropdownMenuItem>
                                    <DropdownMenuSeparator />
                                    <DropdownMenuItem onSelect={() => signOut({ callbackUrl: `/${lng}/${domain}` })}>
                                        {t('user.logout')}
                                    </DropdownMenuItem>
                                </DropdownMenuContent>
                            </DropdownMenu>
                        </div>
                    </div>
                </div>

                {/* 모바일 메뉴 - 도메인별 활성화된 메뉴만 전달 */}
                {isMobileMenuOpen && (
                    <MobileMenu 
                        lng={lng} 
                        onClose={toggleMobileMenu}
                        activeMenus={activeMenus}
                        domainMain={originalMain}
                        domainAdditional={originalAdditional}
                        t={t}
                    />
                )}
            </header>
        </>
    );
}

const ListItem = React.forwardRef<
    React.ElementRef<"a">,
    React.ComponentPropsWithoutRef<"a">
>(({ className, title, children, ...props }, ref) => {
    return (
        <li>
            <NavigationMenuLink asChild>
                <a
                    ref={ref}
                    className={cn(
                        "block select-none space-y-1 rounded-md p-3 leading-none no-underline outline-none transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground",
                        className
                    )}
                    {...props}
                >
                    <div className="text-sm font-medium leading-none">{title}</div>
                    {children && (
                        <p className="line-clamp-2 text-sm leading-snug text-muted-foreground">
                            {children}
                        </p>
                    )}
                </a>
            </NavigationMenuLink>
        </li>
    );
});
ListItem.displayName = "ListItem";

export function RouteLogger() {
    const path = usePathname();
    const qs   = useSearchParams().toString();
    React.useEffect(() => {
      console.log("[URL]", path + (qs ? "?" + qs : ""));
    }, [path, qs]);
    return null;
  }
