export const useDmsSettings = () => {
  // Global DMS settings state
  const dmsSettings = useState('dmsSettings', () => ({
    // User & Access Management
    access: {
      userRoles: ['Admin', 'Editor', 'Viewer', 'Uploader'],
      rbacEnabled: true,
      userGroups: ['HR Department', 'Finance', 'IT', 'Legal'],
      permissions: {
        view: true,
        edit: true,
        delete: false,
        download: true,
        share: true
      },
      authentication: {
        ssoEnabled: false,
        mfaRequired: false,
        ldapIntegration: false,
        sessionTimeout: 8
      }
    },
    
    // Document & Folder Settings
    documents: {
      folderHierarchy: {
        maxDepth: 5,
        defaultStructure: ['Department', 'Project', 'Category', 'Year'],
        folderTemplates: ['Standard', 'Project-based', 'Department-based']
      },
      namingConventions: {
        autoGenerate: true,
        mandatoryFields: ['title', 'department', 'date'],
        pattern: '{department}_{title}_{date}'
      },
      retention: {
        enabled: true,
        defaultDays: 2555, // 7 years
        archiveBeforeDelete: true
      },
      versionControl: {
        enabled: true,
        maxVersions: 10,
        autoVersioning: true
      }
    },
    
    // Metadata & Tagging
    metadata: {
      customFields: [
        { name: 'Department', type: 'dropdown', required: true },
        { name: 'Priority', type: 'select', required: false },
        { name: 'Project Code', type: 'text', required: true },
        { name: 'Review Date', type: 'date', required: false }
      ],
      tagging: {
        predefinedTags: ['urgent', 'confidential', 'public', 'draft', 'final'],
        userGeneratedTags: true,
        tagSuggestions: true
      },
      classification: {
        autoClassification: true,
        rules: ['confidential-keywords', 'department-based', 'file-type']
      }
    },
    
    // Workflow & Automation
    workflow: {
      approvalFlows: {
        enabled: true,
        defaultFlow: 'department-head-approval',
        customFlows: ['legal-review', 'finance-approval', 'director-sign-off']
      },
      notifications: {
        emailNotifications: true,
        inAppNotifications: true,
        uploadAlerts: true,
        deadlineReminders: true
      },
      automation: {
        triggers: ['document-uploaded', 'approval-completed', 'deadline-reached'],
        actions: ['move-to-folder', 'send-notification', 'create-task']
      }
    },
    
    // Upload & Storage Settings
    upload: {
      fileTypes: {
        allowed: ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'jpg', 'png'],
        blocked: ['exe', 'bat', 'cmd']
      },
      fileSizeLimit: 100, // MB
      quotas: {
        perUser: 5000, // MB
        perGroup: 50000, // MB
        perProject: 100000 // MB
      },
      storage: {
        type: 'local', // local, s3, azure, google
        path: '/var/uploads/edms',
        backupEnabled: true,
        compressionEnabled: false
      }
    },
    
    // System Settings
    system: {
      timezone: 'Asia/Kuala_Lumpur',
      backupSchedule: 'daily',
      logLevel: 'info',
      maintenanceMode: false,
      autoUpdates: false,
      systemMonitoring: true,
      performanceMetrics: true
    }
  }));

  // Loading state
  const loading = useState('dmsSettingsLoading', () => false);
  const saving = useState('dmsSettingsSaving', () => false);

  // Load DMS settings from API
  const loadDmsSettings = async () => {
    loading.value = true;
    try {
      const response = await $fetch("/api/dms/settings", {
        method: "GET",
      });
      
      if (response && response.data) {
        dmsSettings.value = { ...dmsSettings.value, ...response.data };
        console.log('[useDmsSettings] Settings loaded successfully:', response.data);
      }
    } catch (error) {
      console.error("Error loading DMS settings:", error);
      throw error;
    } finally {
      loading.value = false;
    }
  };

  // Update DMS settings
  const updateDmsSettings = async (newSettings) => {
    console.log("[useDmsSettings] updateDmsSettings called with:", JSON.parse(JSON.stringify(newSettings)));
    saving.value = true;
    try {
      const response = await $fetch("/api/dms/settings", {
        method: "POST",
        body: newSettings,
      });
      console.log("[useDmsSettings] API response received:", JSON.parse(JSON.stringify(response)));
      
      if (response && response.statusCode === 200) {
        // Reload settings after successful update
        await loadDmsSettings();
        console.log("[useDmsSettings] Returning success from updateDmsSettings.");
        return { success: true, data: response.data };
      }
      
      let errorMessage = "Update operation failed: No data returned from server.";
      if (response && typeof response === 'object' && response !== null && 'message' in response) {
        errorMessage = response.message;
      }
      
      console.log("[useDmsSettings] Returning failure from updateDmsSettings:", errorMessage);
      return { success: false, error: { message: errorMessage, details: response } };
    } catch (error) {
      console.error("[useDmsSettings] Error in updateDmsSettings catch block:", error);
      let detailedMessage = "An unexpected error occurred during update.";
      if (error.data && error.data.message) {
        detailedMessage = error.data.message;
      } else if (error.message) {
        detailedMessage = error.message;
      }
      console.log("[useDmsSettings] Returning failure (catch block) from updateDmsSettings:", detailedMessage);
      return { success: false, error: { message: detailedMessage, details: error } };
    } finally {
      saving.value = false;
    }
  };

  // Reset settings to defaults
  const resetToDefaults = async () => {
    const defaultSettings = {
      access: {
        userRoles: ['Admin', 'Editor', 'Viewer', 'Uploader'],
        rbacEnabled: true,
        userGroups: ['HR Department', 'Finance', 'IT', 'Legal'],
        permissions: {
          view: true,
          edit: true,
          delete: false,
          download: true,
          share: true
        },
        authentication: {
          ssoEnabled: false,
          mfaRequired: false,
          ldapIntegration: false,
          sessionTimeout: 8
        }
      },
      documents: {
        folderHierarchy: {
          maxDepth: 5,
          defaultStructure: ['Department', 'Project', 'Category', 'Year'],
          folderTemplates: ['Standard', 'Project-based', 'Department-based']
        },
        namingConventions: {
          autoGenerate: true,
          mandatoryFields: ['title', 'department', 'date'],
          pattern: '{department}_{title}_{date}'
        },
        retention: {
          enabled: true,
          defaultDays: 2555,
          archiveBeforeDelete: true
        },
        versionControl: {
          enabled: true,
          maxVersions: 10,
          autoVersioning: true
        }
      },
      metadata: {
        customFields: [
          { name: 'Department', type: 'dropdown', required: true },
          { name: 'Priority', type: 'select', required: false },
          { name: 'Project Code', type: 'text', required: true },
          { name: 'Review Date', type: 'date', required: false }
        ],
        tagging: {
          predefinedTags: ['urgent', 'confidential', 'public', 'draft', 'final'],
          userGeneratedTags: true,
          tagSuggestions: true
        },
        classification: {
          autoClassification: true,
          rules: ['confidential-keywords', 'department-based', 'file-type']
        }
      },
      workflow: {
        approvalFlows: {
          enabled: true,
          defaultFlow: 'department-head-approval',
          customFlows: ['legal-review', 'finance-approval', 'director-sign-off']
        },
        notifications: {
          emailNotifications: true,
          inAppNotifications: true,
          uploadAlerts: true,
          deadlineReminders: true
        },
        automation: {
          triggers: ['document-uploaded', 'approval-completed', 'deadline-reached'],
          actions: ['move-to-folder', 'send-notification', 'create-task']
        }
      },
      upload: {
        fileTypes: {
          allowed: ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'jpg', 'png'],
          blocked: ['exe', 'bat', 'cmd']
        },
        fileSizeLimit: 100,
        quotas: {
          perUser: 5000,
          perGroup: 50000,
          perProject: 100000
        },
        storage: {
          type: 'local',
          path: '/var/uploads/edms',
          backupEnabled: true,
          compressionEnabled: false
        }
      },
      system: {
        timezone: 'Asia/Kuala_Lumpur',
        backupSchedule: 'daily',
        logLevel: 'info',
        maintenanceMode: false,
        autoUpdates: false,
        systemMonitoring: true,
        performanceMetrics: true
      }
    };
    
    return await updateDmsSettings(defaultSettings);
  };

  // Export settings to JSON
  const exportSettings = () => {
    const dataStr = JSON.stringify(dmsSettings.value, null, 2);
    const dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(dataStr);
    
    const exportFileDefaultName = 'dms-settings.json';
    
    const linkElement = document.createElement('a');
    linkElement.setAttribute('href', dataUri);
    linkElement.setAttribute('download', exportFileDefaultName);
    linkElement.click();
  };

  // Import settings from JSON
  const importSettings = (jsonData) => {
    try {
      const importedSettings = JSON.parse(jsonData);
      dmsSettings.value = { ...dmsSettings.value, ...importedSettings };
      return { success: true };
    } catch (error) {
      console.error('Error importing settings:', error);
      return { success: false, error: 'Invalid JSON format' };
    }
  };

  // Get setting by category and key
  const getSetting = (category, key) => {
    if (dmsSettings.value[category]) {
      return dmsSettings.value[category][key];
    }
    return null;
  };

  // Update specific setting
  const updateSetting = async (category, key, value) => {
    if (dmsSettings.value[category]) {
      dmsSettings.value[category][key] = value;
      // Save to backend
      return await updateDmsSettings(dmsSettings.value);
    }
    return { success: false, error: 'Category not found' };
  };

  return {
    dmsSettings: readonly(dmsSettings),
    loading: readonly(loading),
    saving: readonly(saving),
    loadDmsSettings,
    updateDmsSettings,
    resetToDefaults,
    exportSettings,
    importSettings,
    getSetting,
    updateSetting
  };
}; 