'use client';

import { useCallback, useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { Star } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from '@/components/ui/tooltip';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { useFavoritesStore } from '@/stores/favoritesStore';
import { iconMap } from '@/lib/utils/menuTransform';
import type { FavoriteItem } from '@/stores/favoritesStore';

interface HeaderFavoritesBarProps {
  isMobile: boolean;
}

export default function HeaderFavoritesBar({ isMobile }: HeaderFavoritesBarProps) {
  const router = useRouter();
  const { favorites } = useFavoritesStore();
  const [isTablet, setIsTablet] = useState(false);

  // 태블릿 감지 (768~1024)
  useEffect(() => {
    const check = () => {
      const w = window.innerWidth;
      setIsTablet(w >= 768 && w < 1024);
    };
    check();
    window.addEventListener('resize', check);
    return () => window.removeEventListener('resize', check);
  }, []);

  const handleClick = useCallback(
    (item: FavoriteItem) => {
      router.push(item.path);
    },
    [router]
  );

  if (favorites.length === 0) return null;

  const getIcon = (iconName: string) => {
    return iconMap[iconName] || null;
  };

  // 모바일 & 태블릿: 별 아이콘 드롭다운
  if (isMobile || isTablet) {
    return (
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button
            variant="default"
            size="sm"
            className={`p-0 rounded-lg min-[320px]:rounded-xl bg-blue-600 hover:bg-blue-700 text-white flex items-center justify-center ${
              isMobile
                ? 'min-w-[28px] min-h-[28px] min-[320px]:min-w-[36px] min-[320px]:min-h-[36px] sm:min-w-[44px] sm:min-h-[44px]'
                : 'w-10 h-10'
            }`}
            title="즐겨찾기"
          >
            <Star className="h-4 w-4 fill-white" />
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end" className="w-48">
          {favorites.map((item) => {
            const Icon = getIcon(item.iconName);
            return (
              <DropdownMenuItem
                key={item.id}
                onClick={() => handleClick(item)}
                className="flex items-center gap-2 cursor-pointer"
              >
                {Icon && <Icon className="h-4 w-4" />}
                <span>{item.label}</span>
              </DropdownMenuItem>
            );
          })}
        </DropdownMenuContent>
      </DropdownMenu>
    );
  }

  // 데스크톱: 8개 이하 → 아이콘 버튼, 9개 이상 → 별 드롭다운
  const DESKTOP_ICON_LIMIT = 8;

  if (favorites.length > DESKTOP_ICON_LIMIT) {
    return (
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button
            variant="default"
            size="sm"
            className="w-10 h-10 p-0 rounded-xl bg-blue-600 hover:bg-blue-700 text-white flex items-center justify-center"
            title="즐겨찾기"
          >
            <Star className="h-4 w-4 fill-white" />
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end" className="w-48">
          {favorites.map((item) => {
            const Icon = getIcon(item.iconName);
            return (
              <DropdownMenuItem
                key={item.id}
                onClick={() => handleClick(item)}
                className="flex items-center gap-2 cursor-pointer"
              >
                {Icon && <Icon className="h-4 w-4" />}
                <span>{item.label}</span>
              </DropdownMenuItem>
            );
          })}
        </DropdownMenuContent>
      </DropdownMenu>
    );
  }

  return (
    <TooltipProvider delayDuration={300}>
      <div className="flex items-center gap-2">
        {favorites.map((item) => {
          const Icon = getIcon(item.iconName);
          if (!Icon) return null;
          return (
            <Tooltip key={item.id}>
              <TooltipTrigger asChild>
                <Button
                  variant="default"
                  size="sm"
                  onClick={() => handleClick(item)}
                  className="rounded-xl bg-blue-600 hover:bg-blue-700 text-white w-10 h-10 p-0 flex items-center justify-center transition-all duration-200"
                >
                  <Icon className="h-4 w-4" />
                </Button>
              </TooltipTrigger>
              <TooltipContent side="bottom">
                <p>{item.label}</p>
              </TooltipContent>
            </Tooltip>
          );
        })}
      </div>
    </TooltipProvider>
  );
}
