import { useCallback, useMemo, useState } from 'react';

import {
  BOARD_QUARTER_KEY,
  dateToQuarter,
  parseQuarterKey,
  startOfDay,
  startOfWeekMonday,
} from '../lib/boardCalendar';

function readInitialQuarter(): string {
  const todayQuarter = dateToQuarter(new Date());
  try {
    const stored = localStorage.getItem(BOARD_QUARTER_KEY);
    if (parseQuarterKey(stored)) return stored!;
    localStorage.removeItem('eene-board-reference-date');
  } catch {
    /* ignore */
  }
  return todayQuarter;
}

export function useBoardReferenceDate() {
  const [selectedQuarter, setSelectedQuarterState] = useState(readInitialQuarter);
  const [weekLensActive, setWeekLensActive] = useState(false);
  const [referenceWeekMonday, setReferenceWeekMonday] = useState(() => startOfWeekMonday(new Date()));

  const persistQuarter = useCallback((quarterKey: string) => {
    setSelectedQuarterState(quarterKey);
    try {
      localStorage.setItem(BOARD_QUARTER_KEY, quarterKey);
    } catch {
      /* ignore */
    }
  }, []);

  /** 분기 보기 — 카드 기본(제목·수행기간·개요·이슈) */
  const selectQuarter = useCallback(
    (quarterKey: string) => {
      if (!parseQuarterKey(quarterKey)) return;
      persistQuarter(quarterKey);
      setWeekLensActive(false);
    },
    [persistQuarter],
  );

  /** 오늘이 포함된 분기 + 분기 보기 (첫 화면 복귀) */
  const returnToCurrentQuarter = useCallback(() => {
    persistQuarter(dateToQuarter(new Date()));
    setReferenceWeekMonday(startOfWeekMonday(new Date()));
    setWeekLensActive(false);
  }, [persistQuarter]);

  /** 주차 보기 — 카드에 해당 주 업무 1건 */
  const selectWeek = useCallback(
    (d: Date) => {
      const monday = startOfWeekMonday(startOfDay(d));
      setReferenceWeekMonday(monday);
      setWeekLensActive(true);
      persistQuarter(dateToQuarter(monday));
    },
    [persistQuarter],
  );

  const referenceDate = useMemo(
    () => (weekLensActive ? referenceWeekMonday : startOfWeekMonday(new Date())),
    [weekLensActive, referenceWeekMonday],
  );

  return {
    quarter: selectedQuarter,
    selectedQuarter,
    referenceDate,
    referenceWeekMonday,
    weekLensActive,
    selectWeek,
    selectQuarter,
    returnToCurrentQuarter,
  };
}
