import React from 'react';
import Link from 'next/link';
import { NavigationMenuLink } from "@/components/ui/navigation-menu";
import { cn } from "@/lib/utils";
import * as LucideIcons from "lucide-react";
import { MenuItem } from '@/config/menuConfig';
import { filterActiveAdditionalMenus } from "@/hooks/use-active-menus";

type GroupedMenuItems = {
  [key: string]: MenuItem[];
};

interface GroupedMenuRendererProps {
  items: MenuItem[];
  lng: string;
  activeMenus?: Record<string, boolean>;
  t: (key: string) => string; // 번역 함수 추가
}

const GroupedMenuRenderer = ({ items, lng, activeMenus = {}, t }: GroupedMenuRendererProps) => {
  // 활성 메뉴만 필터링 (activeMenus가 빈 객체면 모든 메뉴 표시)
  const filteredItems = Object.keys(activeMenus).length > 0 
    ? filterActiveAdditionalMenus(items, activeMenus)
    : items;

  // 그룹별로 아이템 분류
  const groupItems = (items: MenuItem[]): GroupedMenuItems => {
    return items.reduce((groups, item) => {
      // groupKey가 있으면 번역된 그룹명 사용, 없으면 'default'
      const groupKey = item.groupKey || 'default';
      const groupName = item.groupKey ? t(item.groupKey) : 'default';
      
      if (!groups[groupName]) {
        groups[groupName] = [];
      }
      groups[groupName].push(item);
      return groups;
    }, {} as GroupedMenuItems);
  };

  const groupedItems = groupItems(filteredItems);
  const groups = Object.keys(groupedItems);

  // 활성 메뉴가 없으면 아무것도 렌더링하지 않음
  if (filteredItems.length === 0) {
    return (
      <div className="p-4 w-[600px]">
        <p className="text-sm text-muted-foreground text-center py-8">
          {t('common.no_available_menus')}
        </p>
      </div>
    );
  }

  return (
    <div className="p-4 w-[600px]">
      {groups.map((groupName, index) => {
        // 빈 그룹은 건너뛰기
        if (groupedItems[groupName].length === 0) return null;
                
        return (
          <div key={groupName} className={cn("mb-4", index < groups.length - 1 && "pb-2 border-b border-border/30")}>
            {groupName !== 'default' && (
              <h3 className="text-sm font-semibold mb-2 text-primary">{groupName}</h3>
            )}
            <div className="grid grid-cols-2 gap-3">
              {groupedItems[groupName].map((item) => (
                <MenuListItem key={item.titleKey} item={item} lng={lng} t={t} />
              ))}
            </div>
          </div>
        );
      })}
    </div>
  );
};

const MenuListItem = ({ item, lng, t }: { item: MenuItem; lng: string; t: (key: string) => string }) => {
  return (
    <NavigationMenuLink asChild>
      <Link
        href={`/${lng}${item.href}`}
        className={cn(
          "flex items-start space-x-2 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",
          item.disabled && "pointer-events-none opacity-60"
        )}
      >
        <div className="space-y-1">
          <div className="text-sm font-medium leading-none">{t(item.titleKey)}</div>
          {item.descriptionKey && (
            <p className="line-clamp-2 text-xs leading-snug text-muted-foreground">
              {t(item.descriptionKey)}
            </p>
          )}
        </div>
      </Link>
    </NavigationMenuLink>
  );
};

export default GroupedMenuRenderer;