import { useState, useEffect } from 'react';
import { useToast } from '@/hooks/use-toast';
import { configApi, ApiConfig, SystemParameter, Integration, SecurityConfig, AuditLog, PaymentConfig } from '@/services/configApi';

export const useSystemConfig = () => {
  const [apiConfigs, setApiConfigs] = useState<ApiConfig[]>([]);
  const [systemParameters, setSystemParameters] = useState<SystemParameter[]>([]);
  const [integrations, setIntegrations] = useState<Integration[]>([]);
  const [securityConfig, setSecurityConfig] = useState<SecurityConfig[]>([]);
  const [auditLogs, setAuditLogs] = useState<AuditLog[]>([]);
  const [paymentConfigs, setPaymentConfigs] = useState<PaymentConfig[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const { toast } = useToast();

  const loadData = async () => {
    setLoading(true);
    setError(null);
    try {
      const [apis, parameters, integs, security, logs, payments] = await Promise.all([
        configApi.getApiConfigs(),
        configApi.getSystemParameters(),
        configApi.getIntegrations(),
        configApi.getSecurityConfig(),
        configApi.getAuditLogs(1, 20).then(result => result.logs),
        configApi.getPaymentConfigs(),
      ]);

      setApiConfigs(apis);
      setSystemParameters(parameters);
      setIntegrations(integs);
      setSecurityConfig(security);
      setAuditLogs(logs);
      setPaymentConfigs(payments);
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Error loading system configuration';
      setError(message);
      console.error('Error loading system config:', err);
    } finally {
      setLoading(false);
    }
  };

  const updateApiConfig = async (config: Partial<ApiConfig>) => {
    try {
      const updated = await configApi.updateApiConfig(config);
      setApiConfigs(prev => prev.map(c => c.id === updated.id ? updated : c));
      toast({
        title: "Configuración Actualizada",
        description: "La configuración de API se actualizó correctamente",
      });
    } catch (err) {
      toast({
        title: "Error",
        description: "No se pudo actualizar la configuración de API",
        variant: "destructive",
      });
    }
  };

  const testApiConnection = async (configId: string) => {
    try {
      const success = await configApi.testApiConnection(configId);
      toast({
        title: success ? "Conexión Exitosa" : "Conexión Fallida",
        description: success ? "La API responde correctamente" : "No se pudo conectar a la API",
        variant: success ? "default" : "destructive",
      });
      return success;
    } catch (err) {
      toast({
        title: "Error",
        description: "Error al probar la conexión",
        variant: "destructive",
      });
      return false;
    }
  };

  const updateSystemParameter = async (parameter: Partial<SystemParameter>) => {
    try {
      const updated = await configApi.updateSystemParameter(parameter);
      setSystemParameters(prev => prev.map(p => p.id === updated.id ? updated : p));
      toast({
        title: "Parámetro Actualizado",
        description: "El parámetro del sistema se actualizó correctamente",
      });
    } catch (err) {
      toast({
        title: "Error",
        description: "No se pudo actualizar el parámetro",
        variant: "destructive",
      });
    }
  };

  const syncIntegration = async (integrationId: string) => {
    try {
      await configApi.syncIntegration(integrationId);
      toast({
        title: "Sincronización Iniciada",
        description: "La integración se está sincronizando",
      });
      // Reload integrations to get updated status
      const updatedIntegrations = await configApi.getIntegrations();
      setIntegrations(updatedIntegrations);
    } catch (err) {
      toast({
        title: "Error",
        description: "No se pudo sincronizar la integración",
        variant: "destructive",
      });
    }
  };

  const updateSecurityConfig = async (config: Partial<SecurityConfig>) => {
    try {
      const updated = await configApi.updateSecurityConfig(config);
      setSecurityConfig(prev => prev.map(c => c.id === updated.id ? updated : c));
      toast({
        title: "Configuración de Seguridad Actualizada",
        description: "Los ajustes de seguridad se actualizaron correctamente",
      });
    } catch (err) {
      toast({
        title: "Error",
        description: "No se pudo actualizar la configuración de seguridad",
        variant: "destructive",
      });
    }
  };

  const updatePaymentConfig = async (config: Partial<PaymentConfig>) => {
    try {
      const updated = await configApi.updatePaymentConfig(config);
      setPaymentConfigs(prev => prev.map(c => c.id === updated.id ? updated : c));
      toast({
        title: "Configuración de Pago Actualizada",
        description: "Las credenciales de pago se actualizaron correctamente",
      });
    } catch (err) {
      toast({
        title: "Error",
        description: "No se pudo actualizar la configuración de pago",
        variant: "destructive",
      });
    }
  };

  const testPaymentConnection = async (configId: string) => {
    try {
      const success = await configApi.testPaymentConnection(configId);
      toast({
        title: success ? "Conexión Exitosa" : "Conexión Fallida",
        description: success ? "Las credenciales son válidas" : "No se pudo verificar las credenciales",
        variant: success ? "default" : "destructive",
      });
      return success;
    } catch (err) {
      toast({
        title: "Error",
        description: "Error al probar la conexión",
        variant: "destructive",
      });
      return false;
    }
  };

  useEffect(() => {
    loadData();
  }, []);

  return {
    apiConfigs,
    systemParameters,
    integrations,
    securityConfig,
    auditLogs,
    paymentConfigs,
    loading,
    error,
    refetch: loadData,
    updateApiConfig,
    testApiConnection,
    updateSystemParameter,
    syncIntegration,
    updateSecurityConfig,
    updatePaymentConfig,
    testPaymentConnection,
  };
};