import { useCallback, useEffect, useState } from 'react';
import { normalizeAdminSettings, serializeAdminSettings } from '../utils/adminSettings';

const useAdminSettings = ({ session, authorizedFetch, setStatus, setError }) => {
  const [adminSettings, setAdminSettings] = useState(null);
  const [adminSettingsLoading, setAdminSettingsLoading] = useState(false);

  const clearAdminSettings = useCallback(() => {
    setAdminSettings(null);
    setAdminSettingsLoading(false);
  }, []);

  const setAdminSettingsSnapshot = useCallback((snapshot) => {
    setAdminSettings(snapshot ? normalizeAdminSettings(snapshot) : null);
  }, []);

  const loadAdminSettings = useCallback(async () => {
    if (!session?.token || !session.isAdmin) {
      clearAdminSettings();
      return;
    }
    setAdminSettingsLoading(true);
    try {
      const response = await authorizedFetch('/api/admin/settings');
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}`);
      }
      const data = await response.json();
      setAdminSettings(normalizeAdminSettings(data));
    } catch (err) {
      setError(`Admin-Einstellungen konnten nicht geladen werden: ${err.message}`);
    } finally {
      setAdminSettingsLoading(false);
    }
  }, [session?.token, session?.isAdmin, authorizedFetch, setError, clearAdminSettings]);

  useEffect(() => {
    if (!session?.token || !session.isAdmin) {
      clearAdminSettings();
      return;
    }
    let cancelled = false;
    setAdminSettingsLoading(true);

    (async () => {
      try {
        const response = await authorizedFetch('/api/admin/settings');
        if (!response.ok) {
          throw new Error(`HTTP ${response.status}`);
        }
        const data = await response.json();
        if (!cancelled) {
          setAdminSettings(normalizeAdminSettings(data));
        }
      } catch (err) {
        if (!cancelled) {
          setError(`Admin-Einstellungen konnten nicht geladen werden: ${err.message}`);
        }
      } finally {
        if (!cancelled) {
          setAdminSettingsLoading(false);
        }
      }
    })();

    return () => {
      cancelled = true;
    };
  }, [session?.token, session?.isAdmin, authorizedFetch, setError, clearAdminSettings]);

  const handleAdminSettingChange = useCallback((field, value, isNumber = false) => {
    setAdminSettings((prev) => {
      if (!prev) {
        return prev;
      }
      let nextValue = value;
      if (isNumber) {
        nextValue = value === '' ? '' : Number(value);
      }
      return {
        ...prev,
        [field]: nextValue
      };
    });
  }, []);

  const handleAdminNotificationChange = useCallback((channel, field, value) => {
    setAdminSettings((prev) => {
      if (!prev) {
        return prev;
      }
      return {
        ...prev,
        notifications: {
          ...(prev.notifications || {}),
          [channel]: {
            ...(prev.notifications?.[channel] || {}),
            [field]: value
          }
        }
      };
    });
  }, []);

  const handleIgnoredSlotChange = useCallback((index, field, value) => {
    setAdminSettings((prev) => {
      if (!prev) {
        return prev;
      }
      const slots = [...(prev.ignoredSlots || [])];
      slots[index] = {
        ...slots[index],
        [field]: value
      };
      return {
        ...prev,
        ignoredSlots: slots
      };
    });
  }, []);

  const addIgnoredSlot = useCallback(() => {
    setAdminSettings((prev) => {
      if (!prev) {
        return prev;
      }
      return {
        ...prev,
        ignoredSlots: [...(prev.ignoredSlots || []), { storeId: '', slotName: '', info: '' }]
      };
    });
  }, []);

  const removeIgnoredSlot = useCallback((index) => {
    setAdminSettings((prev) => {
      if (!prev) {
        return prev;
      }
      const slots = [...(prev.ignoredSlots || [])];
      slots.splice(index, 1);
      return {
        ...prev,
        ignoredSlots: slots
      };
    });
  }, []);

  const saveAdminSettings = useCallback(async () => {
    if (!session?.token || !session.isAdmin || !adminSettings) {
      return;
    }
    const invalidIgnoredSlot = (adminSettings.ignoredSlots || []).find(
      (slot) => !slot?.storeId || !slot?.slotName
    );
    if (invalidIgnoredSlot) {
      setError('Ignorierte Slots: Store-ID und Slotname sind Pflichtfelder.');
      return;
    }
    setStatus('Admin-Einstellungen werden gespeichert...');
    setError('');

    try {
      const payload = serializeAdminSettings(adminSettings);
      const response = await authorizedFetch('/api/admin/settings', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      });
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}`);
      }
      const data = await response.json();
      setAdminSettings(normalizeAdminSettings(data));
      setStatus('Admin-Einstellungen gespeichert.');
      setTimeout(() => setStatus(''), 3000);
    } catch (err) {
      setError(`Speichern der Admin-Einstellungen fehlgeschlagen: ${err.message}`);
    }
  }, [session?.token, session?.isAdmin, adminSettings, authorizedFetch, setStatus, setError]);

  return {
    adminSettings,
    adminSettingsLoading,
    setAdminSettingsSnapshot,
    clearAdminSettings,
    handleAdminSettingChange,
    handleAdminNotificationChange,
    handleIgnoredSlotChange,
    addIgnoredSlot,
    removeIgnoredSlot,
    saveAdminSettings,
    loadAdminSettings
  };
};

export default useAdminSettings;
