import { useEffect, useState } from "react";
import {
  SCHEDULED_CONDITION_REFRESH_INTERVAL_MS,
  createOperationalScheduledConditions
} from "../data/scheduled-conditions";
import type { ScheduledConditionItem } from "../types";

const HEADER_DATA_TIME_STEP_MINUTES = 5;
const INITIAL_HEADER_DATA_TIME = "同步中";

export function formatHeaderDataTime(date: Date) {
  const snappedMinutes =
    Math.floor(date.getMinutes() / HEADER_DATA_TIME_STEP_MINUTES) * HEADER_DATA_TIME_STEP_MINUTES;
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(snappedMinutes).padStart(2, "0");

  return `${year}-${month}-${day} ${hours}:${minutes}`;
}

export function getMsUntilNextHeaderDataTimeTick(date: Date) {
  const nextTick = new Date(date);
  const nextMinutes =
    Math.floor(date.getMinutes() / HEADER_DATA_TIME_STEP_MINUTES) * HEADER_DATA_TIME_STEP_MINUTES +
    HEADER_DATA_TIME_STEP_MINUTES;

  nextTick.setMinutes(nextMinutes, 0, 0);
  return Math.max(nextTick.getTime() - date.getTime(), 1_000);
}

export function useWorkbenchRuntimeData() {
  const [headerDataTime, setHeaderDataTime] = useState(INITIAL_HEADER_DATA_TIME);
  const [scheduledConditions, setScheduledConditions] = useState<ScheduledConditionItem[]>([]);
  const [scheduledConditionsLoading, setScheduledConditionsLoading] = useState(true);

  useEffect(() => {
    let timeoutId: number;

    const refreshHeaderDataTime = () => {
      const now = new Date();
      setHeaderDataTime(formatHeaderDataTime(now));
      timeoutId = window.setTimeout(refreshHeaderDataTime, getMsUntilNextHeaderDataTimeTick(now));
    };

    refreshHeaderDataTime();
    return () => window.clearTimeout(timeoutId);
  }, []);

  useEffect(() => {
    const refreshScheduledConditions = () => {
      setScheduledConditions(createOperationalScheduledConditions(new Date()));
      setScheduledConditionsLoading(false);
    };

    refreshScheduledConditions();
    const intervalId = window.setInterval(
      refreshScheduledConditions,
      SCHEDULED_CONDITION_REFRESH_INTERVAL_MS
    );

    return () => window.clearInterval(intervalId);
  }, []);

  return {
    headerDataTime,
    scheduledConditions,
    scheduledConditionsLoading
  };
}
