import { useState, useEffect, useCallback, useRef } from 'react';
import { dataService } from '../services/dataService';
import { ISystemSettings } from '../types';
import { useUIStore } from '../store/useUIStore';

export const useSettings = (options?: { enabled?: boolean }) => {
  const enabled = options?.enabled !== false;
  const [settings, setSettings] = useState<ISystemSettings | null>(null);
  const [loading, setLoading] = useState(enabled);
  const [saving, setSaving] = useState(false);
  const { addNotification } = useUIStore();
  const enabledRef = useRef(enabled);
  enabledRef.current = enabled;

  const loadSettings = useCallback(async () => {
    if (!enabledRef.current) {
      setLoading(false);
      return;
    }
    try {
      setLoading(true);
      const s = await dataService.getSystemSettings();
      setSettings(s);
    } catch (error: any) {
      addNotification('error', error.message || 'Lỗi khi tải cấu hình hệ thống');
    } finally {
      setLoading(false);
    }
  }, [addNotification]);

  const saveSettings = useCallback(async (updatedSettings: ISystemSettings) => {
    try {
      setSaving(true);
      await dataService.updateSystemSettings(updatedSettings);
      setSettings(updatedSettings);
      addNotification('success', 'Đã lưu cấu hình thành công!');
      return true;
    } catch (error: any) {
      addNotification('error', error.message || 'Lỗi khi lưu cấu hình');
      return false;
    } finally {
      setSaving(false);
    }
  }, [addNotification]);

  useEffect(() => {
    if (!enabled) {
      setSettings(null);
      setLoading(false);
      return;
    }
    loadSettings();
  }, [enabled, loadSettings]);

  return {
    settings,
    loading,
    saving,
    setSettings,
    saveSettings,
    reloadSettings: loadSettings
  };
};
