'use client';

import { useRef, useEffect, useCallback, useState } from 'react';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import { cn } from '@/lib/utils';
import type { SectionSummary, SummaryStatus } from './useSectionSummary';
import type { SectionKey } from './types';

/** 상태별 점(dot) 색상 */
const STATUS_DOT: Record<SummaryStatus, string> = {
  normal: 'bg-green-500',
  warning: 'bg-yellow-500',
  danger: 'bg-red-500',
};

/** 상태별 칩 배경색 (비활성) */
const STATUS_BG: Record<SummaryStatus, string> = {
  normal: 'bg-background border-border',
  warning: 'bg-yellow-50 border-yellow-300 dark:bg-yellow-950/30 dark:border-yellow-700',
  danger: 'bg-red-50 border-red-300 dark:bg-red-950/30 dark:border-red-700',
};

/** 상태별 칩 배경색 (활성) */
const STATUS_BG_ACTIVE: Record<SummaryStatus, string> = {
  normal: 'bg-accent border-primary/40',
  warning: 'bg-yellow-100 border-yellow-400 dark:bg-yellow-900/40 dark:border-yellow-600',
  danger: 'bg-red-100 border-red-400 dark:bg-red-900/40 dark:border-red-600',
};

interface SummaryChipProps {
  summary: SectionSummary;
  isActive: boolean;
  onClick: () => void;
}

function SummaryChip({ summary, isActive, onClick }: SummaryChipProps) {
  return (
    <button
      type="button"
      onClick={onClick}
      className={cn(
        'relative flex items-center gap-2 px-4 py-2.5 rounded-full text-sm font-medium whitespace-nowrap',
        'border transition-all duration-200 shrink-0',
        'hover:brightness-95 active:scale-[0.97]',
        isActive
          ? cn(STATUS_BG_ACTIVE[summary.status], 'text-foreground shadow-sm')
          : cn(STATUS_BG[summary.status], 'text-muted-foreground'),
      )}
    >
      {/* 상태 점 (확대) */}
      <span className={cn('w-2.5 h-2.5 rounded-full shrink-0', STATUS_DOT[summary.status])} />
      {/* 라벨 */}
      <span className="truncate max-w-[6rem]">{summary.label}</span>
      {/* 값 */}
      <span className={cn(
        'font-bold',
        summary.status === 'danger' && 'text-red-600 dark:text-red-400',
        summary.status === 'warning' && 'text-yellow-600 dark:text-yellow-400',
      )}>
        {summary.value}
      </span>
      {/* 활성 하단 바 */}
      {isActive && (
        <span className="absolute bottom-0 left-3 right-3 h-[3px] rounded-full bg-primary" />
      )}
    </button>
  );
}

const HEADER_BOTTOM = 100; // 헤더 하단 고정 위치 (px)
const BAR_HEIGHT = 56; // 요약바 높이 (px) — 고령 친화 확대
const SCROLL_STEP = 200; // 화살표 버튼 클릭 시 스크롤 이동량 (px)

interface SummaryNavBarProps {
  summaries: SectionSummary[];
  activeSectionKey: SectionKey | null;
  onChipClick: (key: SectionKey) => void;
}

export function SummaryNavBar({ summaries, activeSectionKey, onChipClick }: SummaryNavBarProps) {
  const scrollRef = useRef<HTMLDivElement>(null);
  const sentinelRef = useRef<HTMLDivElement>(null);
  const [isFixed, setIsFixed] = useState(false);
  const [barRect, setBarRect] = useState({ left: 0, width: 0 });
  const [canScrollLeft, setCanScrollLeft] = useState(false);
  const [canScrollRight, setCanScrollRight] = useState(false);

  // 스크롤 가능 여부 체크
  const updateScrollButtons = useCallback(() => {
    const el = scrollRef.current;
    if (!el) return;
    setCanScrollLeft(el.scrollLeft > 4);
    setCanScrollRight(el.scrollLeft + el.clientWidth < el.scrollWidth - 4);
  }, []);

  // sentinel 위치 감시: sentinel이 헤더 뒤로 지나가면 fixed 모드
  useEffect(() => {
    const handleScroll = () => {
      if (!sentinelRef.current) return;
      const rect = sentinelRef.current.getBoundingClientRect();
      const shouldFix = rect.top < HEADER_BOTTOM;
      setIsFixed(shouldFix);

      if (shouldFix) {
        const main = document.querySelector('main');
        if (main) {
          const mainRect = main.getBoundingClientRect();
          const mainStyle = getComputedStyle(main);
          const pl = parseFloat(mainStyle.paddingLeft) || 0;
          const pr = parseFloat(mainStyle.paddingRight) || 0;
          setBarRect({
            left: mainRect.left + pl,
            width: mainRect.width - pl - pr,
          });
        }
      }
    };

    window.addEventListener('scroll', handleScroll, { passive: true });
    window.addEventListener('resize', handleScroll, { passive: true });
    handleScroll();
    return () => {
      window.removeEventListener('scroll', handleScroll);
      window.removeEventListener('resize', handleScroll);
    };
  }, []);

  // 칩 영역 스크롤 상태 감시
  useEffect(() => {
    const el = scrollRef.current;
    if (!el) return;
    updateScrollButtons();
    el.addEventListener('scroll', updateScrollButtons, { passive: true });
    const ro = new ResizeObserver(updateScrollButtons);
    ro.observe(el);
    return () => {
      el.removeEventListener('scroll', updateScrollButtons);
      ro.disconnect();
    };
  }, [updateScrollButtons, summaries]);

  // 활성 칩 자동 스크롤 into view
  useEffect(() => {
    if (!activeSectionKey || !scrollRef.current) return;
    const chipEl = scrollRef.current.querySelector(`[data-chip-key="${activeSectionKey}"]`) as HTMLElement | null;
    if (!chipEl) return;

    const container = scrollRef.current;
    const chipLeft = chipEl.offsetLeft;
    const chipWidth = chipEl.offsetWidth;
    const containerWidth = container.offsetWidth;
    const scrollLeft = container.scrollLeft;

    if (chipLeft < scrollLeft + 50 || chipLeft + chipWidth > scrollLeft + containerWidth - 50) {
      container.scrollTo({
        left: chipLeft - containerWidth / 2 + chipWidth / 2,
        behavior: 'smooth',
      });
    }
  }, [activeSectionKey]);

  const handleChipClick = useCallback(
    (key: SectionKey) => {
      onChipClick(key);
    },
    [onChipClick],
  );

  // 화살표 버튼 핸들러
  const scrollBy = useCallback((direction: 'left' | 'right') => {
    const el = scrollRef.current;
    if (!el) return;
    el.scrollBy({
      left: direction === 'left' ? -SCROLL_STEP : SCROLL_STEP,
      behavior: 'smooth',
    });
  }, []);

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

  const arrowBtnClass = cn(
    'flex items-center justify-center w-8 h-8 rounded-full shrink-0',
    'bg-muted/80 hover:bg-muted text-foreground',
    'border border-border shadow-sm',
    'transition-opacity duration-150',
  );

  const barContent = (
    <div className="flex items-center gap-1.5">
      {/* 좌측 화살표 */}
      <button
        type="button"
        aria-label="이전 항목"
        className={cn(arrowBtnClass, !canScrollLeft && 'opacity-0 pointer-events-none')}
        onClick={() => scrollBy('left')}
      >
        <ChevronLeft className="w-5 h-5" />
      </button>

      {/* 칩 목록 */}
      <div
        ref={scrollRef}
        className="flex items-center gap-2 overflow-x-auto flex-1"
        style={{ scrollbarWidth: 'none', msOverflowStyle: 'none' }}
      >
        {summaries.map((s) => (
          <div key={s.key} data-chip-key={s.key}>
            <SummaryChip
              summary={s}
              isActive={activeSectionKey === s.key}
              onClick={() => handleChipClick(s.key)}
            />
          </div>
        ))}
      </div>

      {/* 우측 화살표 */}
      <button
        type="button"
        aria-label="다음 항목"
        className={cn(arrowBtnClass, !canScrollRight && 'opacity-0 pointer-events-none')}
        onClick={() => scrollBy('right')}
      >
        <ChevronRight className="w-5 h-5" />
      </button>
    </div>
  );

  return (
    <>
      {/* sentinel: 이 div가 헤더 뒤로 사라지면 fixed 모드 활성화 */}
      <div ref={sentinelRef} className="h-0 w-full" />

      {/* fixed일 때 레이아웃 공간 유지용 spacer */}
      {isFixed && <div style={{ height: BAR_HEIGHT }} />}

      {/* 실제 바 */}
      <div
        className="z-40 py-2.5 backdrop-blur-md bg-background/90 border-b border-border/50"
        style={
          isFixed
            ? {
                position: 'fixed',
                top: HEADER_BOTTOM,
                left: barRect.left,
                width: barRect.width,
              }
            : { position: 'relative' }
        }
      >
        {barContent}
      </div>
    </>
  );
}
