import { useCallback, useEffect, useState } from 'react';
import { GraphQlConfigValues, useGraphQLClient } from 'src/contexts/graphqlContext/graphqlContext';

export const useColorsAndFrontendConfig = () => {
  const { getColorsAndFrontendConfig, isReady } = useGraphQLClient();
  const [data, setData] = useState<GraphQlConfigValues>({});
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<Error | null>(null);

  const fetchConfig = useCallback(async () => {
    if (!isReady) return;

    setLoading(true);
    setError(null);

    try {
      const result = await getColorsAndFrontendConfig();
      setData(result);
    } catch (err) {
      setError(err instanceof Error ? err : new Error('Unknown error'));
    } finally {
      setLoading(false);
    }
  }, [getColorsAndFrontendConfig, isReady]);

  useEffect(() => {
    fetchConfig();
  }, [fetchConfig]);

  return { data, loading, error, refetch: fetchConfig };
};

export const useUIConfig = () => {
  const { getConfig, isReady } = useGraphQLClient();
  const [data, setData] = useState<GraphQlConfigValues>({});
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<Error | null>(null);

  const fetchConfig = useCallback(async () => {
    if (!isReady) return;
    if (loading) return;
    if (Object.keys(data).length > 0) return;

    setLoading(true);
    setError(null);

    try {
      const result = await getConfig();
      setData(result);
    } catch (err) {
      setError(err instanceof Error ? err : new Error('Unknown error'));
    } finally {
      setLoading(false);
    }
  }, [data, getConfig, isReady, loading]);

  useEffect(() => {
    fetchConfig();
  }, [fetchConfig]);

  return { data, loading, error, refetch: fetchConfig };
};
