import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api/apiClient';
import { showSuccess, handleError } from '@/lib/services/errorHandler';

// Query Keys
export const adminSettingsKeys = {
  all: ['admin', 'settings'] as const,
};

// Backend setting item format (after camelCase conversion)
interface BackendSettingItem {
  key: string;
  value: any;
  description?: string;
  category: string;
  isEditable: boolean;
  updatedAt?: string;
}

// Frontend flat settings format
export interface SystemSettings {
  site_name?: string;
  site_description?: string;
  allow_registration?: boolean;
  require_email_verification?: boolean;
  max_projects_per_user?: number;
  max_storage_per_user_mb?: number;
  default_generation_timeout?: number;
  maintenance_mode?: boolean;
  maintenance_message?: string;
  email_notifications_enabled?: boolean;
  auto_cleanup_enabled?: boolean;
  auto_cleanup_days?: number;
  created_at?: string;
  updated_at?: string;
}

// Backend response format
interface SystemSettingsResponse {
  settings: BackendSettingItem[];
  categories: string[];
}

// Helper function to convert backend settings array to frontend flat object
function transformSettingsResponse(data: SystemSettingsResponse): SystemSettings {
  const settings: Record<string, any> = {};

  if (Array.isArray(data?.settings)) {
    for (const setting of data.settings) {
      // Map backend keys to frontend keys
      switch (setting.key) {
        case 'site_name':
          settings.site_name = setting.value;
          break;
        case 'site_description':
          settings.site_description = setting.value;
          break;
        case 'allow_registration':
          settings.allow_registration = setting.value;
          break;
        case 'require_email_verification':
          settings.require_email_verification = setting.value;
          break;
        case 'max_projects_per_user':
          settings.max_projects_per_user = setting.value;
          break;
        case 'max_storage_per_user_mb':
          settings.max_storage_per_user_mb = setting.value;
          break;
        case 'default_generation_timeout':
          settings.default_generation_timeout = setting.value;
          break;
        case 'maintenance_mode':
          settings.maintenance_mode = setting.value;
          break;
        case 'maintenance_message':
          settings.maintenance_message = setting.value;
          break;
        case 'email_notifications_enabled':
          settings.email_notifications_enabled = setting.value;
          break;
        case 'auto_cleanup_enabled':
          settings.auto_cleanup_enabled = setting.value;
          break;
        case 'auto_cleanup_days':
          settings.auto_cleanup_days = setting.value;
          break;
        default:
          // Store any unknown settings with their key
          settings[setting.key] = setting.value;
      }
    }
  }

  return settings as SystemSettings;
}

// Hooks
export function useAdminSettings() {
  return useQuery({
    queryKey: adminSettingsKeys.all,
    queryFn: async () => {
      const response = await api.get('/api/v1/admin/settings');
      // Backend returns { code, data: { settings: [...], categories: [...] } }
      const data = response.data?.data ?? response.data;
      return transformSettingsResponse(data as SystemSettingsResponse);
    },
    staleTime: 60 * 1000,
  });
}

// Helper function to convert frontend flat object to backend settings array
function transformSettingsToBackend(settings: Partial<SystemSettings>): BackendSettingItem[] {
  const backendSettings: BackendSettingItem[] = [];

  const keyMapping: Record<string, { key: string; description: string; category: string }> = {
    site_name: { key: 'site_name', description: 'Site name', category: 'general' },
    site_description: { key: 'site_description', description: 'Site description', category: 'general' },
    allow_registration: { key: 'allow_registration', description: 'Allow user registration', category: 'users' },
    require_email_verification: { key: 'require_email_verification', description: 'Require email verification', category: 'users' },
    max_projects_per_user: { key: 'max_projects_per_user', description: 'Max projects per user', category: 'users' },
    max_storage_per_user_mb: { key: 'max_storage_per_user_mb', description: 'Max storage per user (MB)', category: 'users' },
    default_generation_timeout: { key: 'default_generation_timeout', description: 'Default generation timeout (seconds)', category: 'tasks' },
    maintenance_mode: { key: 'maintenance_mode', description: 'Maintenance mode', category: 'system' },
    maintenance_message: { key: 'maintenance_message', description: 'Maintenance message', category: 'system' },
    email_notifications_enabled: { key: 'email_notifications_enabled', description: 'Email notifications enabled', category: 'email' },
    auto_cleanup_enabled: { key: 'auto_cleanup_enabled', description: 'Auto cleanup enabled', category: 'system' },
    auto_cleanup_days: { key: 'auto_cleanup_days', description: 'Auto cleanup days', category: 'system' },
  };

  for (const [frontendKey, value] of Object.entries(settings)) {
    if (value === undefined || value === null) continue;

    const mapping = keyMapping[frontendKey];
    if (mapping) {
      backendSettings.push({
        key: mapping.key,
        value,
        description: mapping.description,
        category: mapping.category,
        isEditable: true,
        updatedAt: undefined,
      });
    }
  }

  return backendSettings;
}

export function useUpdateAdminSettings() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (settings: Partial<SystemSettings>) => {
      // Convert frontend flat object to backend array format
      const backendSettings = transformSettingsToBackend(settings);

      // Update each setting individually
      const results = await Promise.all(
        backendSettings.map(async (setting) => {
          const response = await api.put(`/api/v1/admin/settings/${setting.key}`, {
            value: setting.value,
          });
          return response.data?.data ?? response.data;
        })
      );

      return results[results.length - 1] as SystemSettings;
    },
    onSuccess: () => {
      showSuccess('保存成功', '系统设置已更新');
      queryClient.invalidateQueries({ queryKey: adminSettingsKeys.all });
    },
    onError: (error) => {
      handleError(error, 'UpdateAdminSettings', {
        customMessage: '保存设置失败，请重试',
      });
    },
  });
}
