"use client";

import { useEffect, useMemo, useState } from "react";
import { config, NETWORK_NAME } from "@/config/config";
import { useProject } from "@/contexts/ProjectContext";
import { apiFetch } from "@/lib/apiFetch";
import {
  coerceTimelineDurationMinutes,
  TIMELINE_MINUTES_PER_DAY,
  TIMELINE_STEP_MINUTES,
} from "./timelineTime";

export interface TimelineTimeConfig {
  durationMinutes: number;
  stepMinutes: number;
  properties: Record<string, unknown>;
}

const DEFAULT_TIMELINE_TIME_CONFIG: TimelineTimeConfig = {
  durationMinutes: TIMELINE_MINUTES_PER_DAY,
  stepMinutes: TIMELINE_STEP_MINUTES,
  properties: {},
};

const resolveTimeProperties = (data: unknown): Record<string, unknown> => {
  if (!data || typeof data !== "object") {
    return {};
  }

  const record = data as Record<string, unknown>;
  if (record.times && typeof record.times === "object") {
    return record.times as Record<string, unknown>;
  }

  return record;
};

export const toTimelineTimeConfig = (data: unknown): TimelineTimeConfig => {
  const properties = resolveTimeProperties(data);

  return {
    durationMinutes: coerceTimelineDurationMinutes(
      properties.DURATION,
      TIMELINE_MINUTES_PER_DAY,
    ),
    stepMinutes: coerceTimelineDurationMinutes(
      properties["HYDRAULIC TIMESTEP"],
      TIMELINE_STEP_MINUTES,
    ),
    properties,
  };
};

export const useTimelineTimeConfig = (): TimelineTimeConfig => {
  const project = useProject();
  const networkName = project?.networkName || NETWORK_NAME;
  const [timeConfig, setTimeConfig] = useState<TimelineTimeConfig>(
    DEFAULT_TIMELINE_TIME_CONFIG,
  );

  useEffect(() => {
    if (!networkName) {
      setTimeConfig(DEFAULT_TIMELINE_TIME_CONFIG);
      return;
    }

    let isMounted = true;
    const fetchTimeProperties = async () => {
      try {
        const response = await apiFetch(
          `${config.BACKEND_URL}/api/v1/network-options/time`,
        );
        if (!response.ok) {
          throw new Error(`Failed to fetch time properties: ${response.status}`);
        }
        const data = await response.json();
        if (isMounted) {
          setTimeConfig(toTimelineTimeConfig(data));
        }
      } catch (error) {
        console.warn("Failed to load timeline time properties:", error);
        if (isMounted) {
          setTimeConfig(DEFAULT_TIMELINE_TIME_CONFIG);
        }
      }
    };

    fetchTimeProperties();

    return () => {
      isMounted = false;
    };
  }, [networkName]);

  return useMemo(
    () => ({
      durationMinutes: timeConfig.durationMinutes,
      stepMinutes: timeConfig.stepMinutes,
      properties: timeConfig.properties,
    }),
    [timeConfig],
  );
};
