import { useEffect, useMemo, useRef, useState } from 'react';
import type { HubScheduleItem } from '../../lib/hubConfig';
import { HubNavChevron } from '../common/HubNavChevron';
import {
  findScheduleIndexForToday,
  formatScheduleDateParts,
  isSchedulePast,
  isScheduleToday,
  scheduleWindowStart,
  sortScheduleItems,
} from '../../lib/hubSchedule';

const VISIBLE_COUNT = 3;

interface HubScheduleCarouselProps {
  items: HubScheduleItem[];
  /** 기준일 — 없으면 오늘 */
  focusDate?: Date;
}

export function HubScheduleCarousel({ items, focusDate }: HubScheduleCarouselProps) {
  const rootRef = useRef<HTMLDivElement | null>(null);
  const focus = focusDate ?? new Date();
  const sorted = useMemo(
    () => sortScheduleItems(items.filter((i) => i.date && i.text.trim())),
    [items],
  );

  const focusIndex = useMemo(() => findScheduleIndexForToday(sorted, focus), [sorted, focus]);
  const initialStart = useMemo(
    () => scheduleWindowStart(sorted.length, focusIndex, VISIBLE_COUNT),
    [sorted.length, focusIndex],
  );
  const [startIndex, setStartIndex] = useState(initialStart);

  useEffect(() => {
    setStartIndex(initialStart);
  }, [initialStart, sorted.length]);

  const maxStart = Math.max(0, sorted.length - VISIBLE_COUNT);
  const paged = sorted.length > VISIBLE_COUNT;
  const canPrev = startIndex > 0;
  const canNext = startIndex < maxStart;

  const stepPrev = () => setStartIndex((i) => Math.max(0, i - VISIBLE_COUNT));
  const stepNext = () => setStartIndex((i) => Math.min(maxStart, i + VISIBLE_COUNT));

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

    const onWheel = (event: WheelEvent) => {
      if (Math.abs(event.deltaY) < 1) return;
      event.preventDefault();
      if (event.deltaY > 0) {
        setStartIndex((i) => Math.min(maxStart, i + VISIBLE_COUNT));
      } else {
        setStartIndex((i) => Math.max(0, i - VISIBLE_COUNT));
      }
    };

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

  if (sorted.length === 0) {
    return (
      <div className="hub-schedule-viewport hub-schedule-viewport--empty">
        <p className="board-project-desc hub-schedule-empty">등록된 일정 없음</p>
      </div>
    );
  }

  const visible = sorted.slice(startIndex, startIndex + VISIBLE_COUNT);

  return (
    <div
      ref={rootRef}
      className={`hub-schedule-carousel${paged ? ' is-paged' : ''}`}
    >
      <div className="hub-schedule-viewport">
        <ul className="hub-schedule-list hub-list">
          {visible.map((item) => {
            const past = isSchedulePast(item.date, focus);
            const today = isScheduleToday(item.date, focus);
            const dateParts = formatScheduleDateParts(item.date);
            return (
              <li
                key={item.id}
                className={`hub-schedule-item${past ? ' hub-schedule-item--past' : ''}${today ? ' hub-schedule-item--today' : ''}`}
              >
                <span className="hub-schedule-date board-project-desc">
                  {dateParts ? (
                    <>
                      <span className="hub-schedule-date-month">{dateParts.month}</span>
                      <span className="hub-schedule-date-day">{dateParts.day}</span>
                    </>
                  ) : (
                    item.date
                  )}
                </span>
                <span className="board-project-desc">{item.text}</span>
              </li>
            );
          })}
        </ul>
      </div>

      {canPrev && (
        <button
          type="button"
          className="hub-schedule-nav hub-schedule-nav--prev"
          onClick={stepPrev}
          onContextMenu={(e) => e.stopPropagation()}
          aria-label="이전 일정"
        >
          <HubNavChevron direction="prev" />
        </button>
      )}

      {canNext && (
        <button
          type="button"
          className="hub-schedule-nav hub-schedule-nav--next"
          onClick={stepNext}
          onContextMenu={(e) => e.stopPropagation()}
          aria-label="다음 일정"
        >
          <HubNavChevron direction="next" />
        </button>
      )}
    </div>
  );
}
