// src/hooks/useStorageColors.js
import { useCallback, useEffect, useRef, useState } from "react";

export function useStorageColors({ Axiosinstance, toast }) {
  const initRef = useRef(false);
  const inFlightRef = useRef(false);

  const [colorsCfg, setColorsCfg] = useState(null);
  const [colorOptions, setColorOptions] = useState([]);
  const [colorsLoading, setColorsLoading] = useState(false);

  const fetchColors = useCallback(async () => {
    if (inFlightRef.current) return;
    inFlightRef.current = true;
    setColorsLoading(true);
    try {
      const res = await Axiosinstance.get("storage/colors/");
      const data = res?.data || {};
      setColorsCfg(data?.config || null);
      setColorOptions(Array.isArray(data?.colors) ? data.colors : []);
    } catch (e) {
      toast?.error?.("دریافت رنگ‌ها ناموفق بود.");
    } finally {
      setColorsLoading(false);
      inFlightRef.current = false;
    }
  }, [Axiosinstance, toast]);

  useEffect(() => {
    if (initRef.current) return;
    initRef.current = true;
    fetchColors();
  }, [fetchColors]);

  return { colorsCfg, colorOptions, colorsLoading, refetchColors: fetchColors };
}
