import { useEffect, useMemo, useRef, useState } from 'react';

import type { RoutineFocusMilestone } from '../../hooks/useRoutineCategoryMilestones';

const PAGE_SIZE = 3;

function chunkItems<T>(items: T[], size: number): T[][] {
  const pages: T[][] = [];
  for (let i = 0; i < items.length; i += size) {
    pages.push(items.slice(i, i + size));
  }
  return pages;
}

type HubFocusTaskListProps = {
  milestones: RoutineFocusMilestone[];
  isLoading: boolean;
  categoryKey: string;
  onSelectMilestone?: (milestoneId: string) => void;
};

export function HubFocusTaskList({
  milestones,
  isLoading,
  categoryKey,
  onSelectMilestone,
}: HubFocusTaskListProps) {
  const rootRef = useRef<HTMLDivElement | null>(null);
  const pages = useMemo(() => chunkItems(milestones, PAGE_SIZE), [milestones]);
  const pageCount = pages.length;
  const paged = pageCount > 1;
  const [pageIndex, setPageIndex] = useState(0);

  useEffect(() => {
    setPageIndex(0);
  }, [categoryKey]);

  useEffect(() => {
    setPageIndex((prev) => Math.min(prev, Math.max(0, pageCount - 1)));
  }, [pageCount]);

  useEffect(() => {
    const root = rootRef.current;
    if (!root || !paged) return;

    const onWheel = (event: WheelEvent) => {
      if (Math.abs(event.deltaY) < 1) return;
      event.preventDefault();
      const direction = event.deltaY > 0 ? 1 : -1;
      setPageIndex((prev) => Math.min(pageCount - 1, Math.max(0, prev + direction)));
    };

    root.addEventListener('wheel', onWheel, { passive: false });
    return () => root.removeEventListener('wheel', onWheel);
  }, [paged, pageCount]);

  if (isLoading) {
    return (
      <div className="hub-focus-task-list">
        <div className="hub-focus-task-viewport">
          <ul className="hub-focus-task-page">
            <li className="hub-focus-task-slot hub-focus-task-slot--message">
              <span className="hub-focus-task-empty board-project-desc">불러오는 중…</span>
            </li>
          </ul>
        </div>
      </div>
    );
  }

  if (milestones.length === 0) {
    return (
      <div className="hub-focus-task-list">
        <div className="hub-focus-task-viewport">
          <ul className="hub-focus-task-page">
            <li className="hub-focus-task-slot hub-focus-task-slot--message">
              <span className="hub-focus-task-empty board-project-desc">등록된 업무명 없음</span>
            </li>
          </ul>
        </div>
      </div>
    );
  }

  const pageItems = pages[pageIndex] ?? [];

  return (
    <div
      ref={rootRef}
      className={`hub-focus-task-list${paged ? ' is-paged' : ''}`}
    >
      <div className="hub-focus-task-viewport">
        <ul className="hub-focus-task-page" aria-live="polite">
          {pageItems.map((milestone) => (
            <li key={milestone.id} className="hub-focus-task-slot">
              <button
                type="button"
                className="hub-focus-task-item board-project-desc"
                onClick={() => onSelectMilestone?.(milestone.id)}
              >
                {milestone.title}
              </button>
            </li>
          ))}
          {pageItems.length < PAGE_SIZE &&
            Array.from({ length: PAGE_SIZE - pageItems.length }, (_, slot) => (
              <li
                key={`empty-${pageIndex}-${slot}`}
                className="hub-focus-task-slot hub-focus-task-slot--empty"
                aria-hidden="true"
              />
            ))}
        </ul>
      </div>
    </div>
  );
}
