import { useEffect, useState } from "react";
import type { Dispatch, SetStateAction } from "react";
import type { APIGraphCreationContext } from "../../services/medical";
import type { GraphDataset } from "../../types/medical";

type GraphItem = {
  id: string;
  datasets: GraphDataset[];
  creation: APIGraphCreationContext;
  normalizeByReference?: boolean;
};

const parseSessionGraphs = (raw: string | null): GraphItem[] => {
  if (!raw) return [];

  try {
    const parsed: unknown = JSON.parse(raw);
    if (!Array.isArray(parsed)) return [];

    return parsed.filter((item): item is GraphItem => {
      if (!item || typeof item !== "object") return false;
      const candidate = item as Partial<GraphItem>;
      return (
        typeof candidate.id === "string" &&
        Array.isArray(candidate.datasets) &&
        typeof candidate.creation === "object" &&
        candidate.creation !== null
      );
    });
  } catch {
    return [];
  }
};

export function useGraphSessionStorage(
  graphSessionKey: string | null,
  graphs: GraphItem[],
  setGraphs: Dispatch<SetStateAction<GraphItem[]>>
) {
  const [hydratedSessionKey, setHydratedSessionKey] = useState<string | null>(null);

  useEffect(() => {
    if (!graphSessionKey || hydratedSessionKey === graphSessionKey || typeof window === "undefined") return;

    const restoredGraphs = parseSessionGraphs(window.sessionStorage.getItem(graphSessionKey));
    setGraphs(restoredGraphs);
    setHydratedSessionKey(graphSessionKey);
  }, [graphSessionKey, hydratedSessionKey, setGraphs]);

  useEffect(() => {
    if (!graphSessionKey || hydratedSessionKey !== graphSessionKey || typeof window === "undefined") return;

    if (graphs.length === 0) {
      window.sessionStorage.removeItem(graphSessionKey);
      return;
    }

    window.sessionStorage.setItem(graphSessionKey, JSON.stringify(graphs));
  }, [graphSessionKey, hydratedSessionKey, graphs]);
}