import { useCallback, useEffect, useRef, useState } from 'react';

const CONFIG_ENDPOINT = '/api/config';

const useConfigManager = ({ sessionToken, authorizedFetch, setStatus, setError, setLoading }) => {
  const [config, setConfig] = useState([]);
  const [isDirty, setIsDirty] = useState(false);
  const configRef = useRef(config);

  useEffect(() => {
    configRef.current = config;
  }, [config]);

  const persistConfigUpdate = useCallback(
    async (updater, successMessage, { autoCommit = false } = {}) => {
      const baseConfig = configRef.current;
      const nextConfigState = typeof updater === 'function' ? updater(baseConfig) : updater;
      if (!nextConfigState) {
        return;
      }
      setConfig(nextConfigState);
      if (!sessionToken) {
        setIsDirty(true);
        return;
      }
      if (!autoCommit) {
        setIsDirty(true);
      }
      setStatus('Speichere...');
      setError('');
      try {
        const response = await authorizedFetch(CONFIG_ENDPOINT, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(nextConfigState)
        });
        if (!response.ok) {
          throw new Error(`HTTP ${response.status}`);
        }
        const result = await response.json();
        if (!result.success) {
          throw new Error(result.error || 'Unbekannter Fehler beim Speichern');
        }
        setStatus(successMessage || 'Konfiguration gespeichert.');
        setTimeout(() => setStatus(''), 3000);
        setIsDirty(false);
      } catch (error) {
        setError(`Fehler beim Speichern: ${error.message}`);
        if (autoCommit) {
          setIsDirty(true);
        }
      }
    },
    [authorizedFetch, sessionToken, setError, setStatus]
  );

  const triggerImmediateCheck = useCallback(async () => {
    if (!sessionToken) {
      return;
    }
    try {
      const response = await authorizedFetch('/api/config/check', { method: 'POST' });
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}`);
      }
      const result = await response.json();
      if (!result.success) {
        throw new Error(result.error || 'Unbekannter Fehler bei der Sofortprüfung');
      }
    } catch (error) {
      setError(`Sofortprüfung fehlgeschlagen: ${error.message}`);
    }
  }, [authorizedFetch, sessionToken, setError]);

  const saveConfig = useCallback(async () => {
    if (!sessionToken) {
      return false;
    }
    setStatus('Speichere...');
    setError('');
    setLoading(true);
    try {
      const response = await authorizedFetch(CONFIG_ENDPOINT, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(configRef.current)
      });
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}`);
      }
      const result = await response.json();
      if (!result.success) {
        throw new Error(result.error || 'Unbekannter Fehler beim Speichern');
      }
      setStatus('Konfiguration gespeichert. Sofortprüfung gestartet.');
      setTimeout(() => setStatus(''), 3000);
      setIsDirty(false);
      triggerImmediateCheck();
      return true;
    } catch (error) {
      setError(`Fehler beim Speichern: ${error.message}`);
      setStatus('');
      return false;
    } finally {
      setLoading(false);
    }
  }, [authorizedFetch, sessionToken, setError, setLoading, setStatus, triggerImmediateCheck]);

  return {
    config,
    setConfig,
    isDirty,
    setIsDirty,
    persistConfigUpdate,
    saveConfig
  };
};

export default useConfigManager;
