import { useCallback, useMemo, useState } from "react";
import dayjs from "dayjs";
import { dayjsToDateString } from "@/app/utils/formatUtil";
import {
  JoCreatePlanStartPrefs,
  loadJoCreatePlanStartPrefs,
  saveJoCreatePlanStartPrefs,
} from "@/utils/joCreatePlanStartPrefs";

export function useJoCreatePlanStartPrefs() {
  const [prefs, setPrefs] = useState<JoCreatePlanStartPrefs>(loadJoCreatePlanStartPrefs);

  const defaultPlanStartForCreate = useMemo(
    () => prefs.planStart ?? dayjsToDateString(dayjs(), "input"),
    [prefs.planStart],
  );

  const handleRememberPlanStartChange = useCallback((checked: boolean, selectedDate: string | null) => {
    const next: JoCreatePlanStartPrefs = {
      enabled: checked,
      planStart: checked && selectedDate ? selectedDate : null,
    };
    setPrefs(next);
    saveJoCreatePlanStartPrefs(next);
  }, []);

  return {
    rememberPlanStart: prefs.enabled,
    defaultPlanStartForCreate,
    handleRememberPlanStartChange,
  };
}
