'use client';

import { useRouter, usePathname, useParams } from 'next/navigation';
import { ChevronDown, LayoutDashboard, LayoutGrid, Target, Activity, Columns3 } from 'lucide-react';
import { useState, useRef, useEffect, useCallback } from 'react';

const dashboards = [
  { path: '/dashboard', label: '보고서형', icon: LayoutDashboard },
  { path: '/dashboard_type2', label: '탭형', icon: Columns3 },
  { path: '/dashboard_type3', label: '위젯형', icon: LayoutGrid },
  { path: '/dashboard_type4', label: '드릴다운형', icon: Target },
  { path: '/dashboard_type5', label: '피드형', icon: Activity },
] as const;

export function DashboardSwitcher() {
  const router = useRouter();
  const pathname = usePathname();
  const params = useParams();
  const locale = (params.locale as string) || 'ko';
  const [open, setOpen] = useState(false);
  const [alignRight, setAlignRight] = useState(true);
  const ref = useRef<HTMLDivElement>(null);

  // 현재 활성 대시보드 찾기
  const current = dashboards.find((d) => pathname.endsWith(d.path)) ?? dashboards[0];

  // 드롭다운 열릴 때 버튼 위치 기반으로 정렬 방향 결정
  const updateAlignment = useCallback(() => {
    if (!ref.current) return;
    const rect = ref.current.getBoundingClientRect();
    const viewportWidth = window.innerWidth;
    // 버튼 중심이 화면 오른쪽 절반이면 right 정렬, 아니면 left 정렬
    setAlignRight(rect.left + rect.width / 2 > viewportWidth / 2);
  }, []);

  // 외부 클릭 시 닫기
  useEffect(() => {
    function handleClick(e: MouseEvent) {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
    }
    if (open) document.addEventListener('mousedown', handleClick);
    return () => document.removeEventListener('mousedown', handleClick);
  }, [open]);

  const handleToggle = () => {
    if (!open) updateAlignment();
    setOpen(!open);
  };

  return (
    <div ref={ref} className="relative">
      <button
        onClick={handleToggle}
        className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border bg-background text-sm font-medium hover:bg-muted transition-colors"
      >
        <current.icon className="w-4 h-4 text-primary" />
        <span className="hidden sm:inline">{current.label}</span>
        <ChevronDown className={`w-3.5 h-3.5 text-muted-foreground transition-transform ${open ? 'rotate-180' : ''}`} />
      </button>

      {open && (
        <div className={`absolute top-full mt-1 w-44 rounded-lg border bg-background shadow-lg z-50 py-1 ${alignRight ? 'right-0' : 'left-0'}`}>
          {dashboards.map((d) => {
            const Icon = d.icon;
            const isActive = d.path === current.path;
            return (
              <button
                key={d.path}
                onClick={() => {
                  router.push(`/${locale}${d.path}`);
                  setOpen(false);
                }}
                className={`w-full flex items-center gap-2.5 px-3 py-2 text-sm transition-colors ${
                  isActive
                    ? 'bg-primary/10 text-primary font-medium'
                    : 'text-foreground hover:bg-muted'
                }`}
              >
                <Icon className={`w-4 h-4 ${isActive ? 'text-primary' : 'text-muted-foreground'}`} />
                {d.label}
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}
