import { useCallback, useEffect, useState } from "react";

import type { RuleEngineResourceSlug } from "@/types/rule-engine";

export type RuleEngineViewMode = "table" | "cards";

const STORAGE_PREFIX = "edr-freight-rule-engine-view:";

const readStored = (slug: RuleEngineResourceSlug): RuleEngineViewMode => {
  try {
    const raw = localStorage.getItem(`${STORAGE_PREFIX}${slug}`);
    return raw === "cards" ? "cards" : "table";
  } catch {
    return "table";
  }
};

export const useRuleEngineViewMode = (slug: RuleEngineResourceSlug) => {
  const [viewMode, setViewModeState] = useState<RuleEngineViewMode>(() => readStored(slug));

  useEffect(() => {
    setViewModeState(readStored(slug));
  }, [slug]);

  const setViewMode = useCallback(
    (mode: RuleEngineViewMode) => {
      setViewModeState(mode);
      try {
        localStorage.setItem(`${STORAGE_PREFIX}${slug}`, mode);
      } catch {
        /* ignore quota / private mode */
      }
    },
    [slug],
  );

  return { viewMode, setViewMode };
};
