import React, { useState, useMemo } from 'react';
import { Zap, Key, Settings as SettingsIcon, RefreshCw } from 'lucide-react';
import { AddModal, AddModalSection, AddModalField } from '../../ui/AddModal/AddModal';
import { posService } from '../../../api/services/pos';
import { POSProviderConfig, POSSystem, POSEnvironment } from '../../../api/types/pos';
import { showToast } from '../../../utils/toast';
import { statusColors } from '../../../styles/colors';

interface CreatePOSConfigModalProps {
  isOpen: boolean;
  onClose: () => void;
  tenantId: string;
  onSuccess?: () => void;
  existingConfig?: any; // For edit mode
  mode?: 'create' | 'edit';
}

/**
 * CreatePOSConfigModal - Modal for creating/editing POS configurations
 * Uses the standard AddModal component for consistency across the application
 */
export const CreatePOSConfigModal: React.FC<CreatePOSConfigModalProps> = ({
  isOpen,
  onClose,
  tenantId,
  onSuccess,
  existingConfig,
  mode = 'create'
}) => {
  const [loading, setLoading] = useState(false);
  const [selectedProvider, setSelectedProvider] = useState<POSSystem | ''>('');
  

  // Initialize selectedProvider in edit mode
  React.useEffect(() => {
    if (mode === 'edit' && existingConfig) {
      setSelectedProvider(existingConfig.pos_system as POSSystem);
    } else {
      setSelectedProvider('');
    }
  }, [mode, existingConfig]);

  // Supported POS providers configuration
  const supportedProviders: POSProviderConfig[] = [
    {
      id: 'toast',
      name: 'Toast POS',
      logo: '🍞',
      description: 'Sistema POS líder para restaurantes y panaderías. Muy popular en España.',
      features: ['Gestión de pedidos', 'Sincronización de inventario', 'Pagos integrados', 'Reportes en tiempo real'],
      required_fields: [
        { field: 'api_key', label: 'API Key', type: 'password', required: true, help_text: 'Obten tu API key desde Toast Dashboard > Settings > Integrations' },
        { field: 'restaurant_guid', label: 'Restaurant GUID', type: 'text', required: true, help_text: 'ID único del restaurante en Toast' },
        { field: 'location_id', label: 'Location ID', type: 'text', required: true, help_text: 'ID de la ubicación específica' },
        { field: 'environment', label: 'Entorno', type: 'select', required: true, options: [
          { value: 'sandbox', label: 'Sandbox (Pruebas)' },
          { value: 'production', label: 'Producción' }
        ]},
      ],
    },
    {
      id: 'square',
      name: 'Square POS',
      logo: '⬜',
      description: 'Solución POS completa con tarifas transparentes. Ampliamente utilizada por pequeñas empresas.',
      features: ['Procesamiento de pagos', 'Gestión de inventario', 'Análisis de ventas', 'Integración con e-commerce'],
      required_fields: [
        { field: 'application_id', label: 'Application ID', type: 'text', required: true, help_text: 'ID de aplicación de Square Developer Dashboard' },
        { field: 'access_token', label: 'Access Token', type: 'password', required: true, help_text: 'Token de acceso para la API de Square' },
        { field: 'location_id', label: 'Location ID', type: 'text', required: true, help_text: 'ID de la ubicación de Square' },
        { field: 'webhook_signature_key', label: 'Webhook Signature Key', type: 'password', required: false, help_text: 'Clave para verificar webhooks (opcional)' },
        { field: 'environment', label: 'Entorno', type: 'select', required: true, options: [
          { value: 'sandbox', label: 'Sandbox (Pruebas)' },
          { value: 'production', label: 'Producción' }
        ]},
      ],
    },
    {
      id: 'lightspeed',
      name: 'Lightspeed POS',
      logo: '⚡',
      description: 'Sistema POS empresarial con API abierta e integración con múltiples herramientas.',
      features: ['API REST completa', 'Gestión multi-ubicación', 'Reportes avanzados', 'Integración con contabilidad'],
      required_fields: [
        { field: 'api_key', label: 'API Key', type: 'password', required: true, help_text: 'Clave API de Lightspeed Retail' },
        { field: 'api_secret', label: 'API Secret', type: 'password', required: true, help_text: 'Secreto API de Lightspeed Retail' },
        { field: 'account_id', label: 'Account ID', type: 'text', required: true, help_text: 'ID de cuenta de Lightspeed' },
        { field: 'shop_id', label: 'Shop ID', type: 'text', required: true, help_text: 'ID de la tienda específica' },
        { field: 'server_region', label: 'Región del Servidor', type: 'select', required: true, options: [
          { value: 'eu', label: 'Europa' },
          { value: 'us', label: 'Estados Unidos' },
          { value: 'ca', label: 'Canadá' }
        ]},
      ],
    },
  ];

  // Initialize from existing config in edit mode
  const initialData = useMemo(() => {
    if (mode === 'edit' && existingConfig) {
      // Extract credentials from existing config
      const credentials: Record<string, any> = {};
      const provider = supportedProviders.find(p => p.id === existingConfig.pos_system);

      if (provider && existingConfig.provider_settings) {
        provider.required_fields.forEach(field => {
          if (existingConfig.provider_settings[field.field]) {
            credentials[`credential_${field.field}`] = existingConfig.provider_settings[field.field];
          }
        });
      }

      return {
        provider: existingConfig.pos_system || '',
        config_name: existingConfig.provider_name || '',
        auto_sync_enabled: existingConfig.sync_enabled ?? true,
        sync_interval_minutes: existingConfig.sync_interval_minutes || '5',
        sync_sales: existingConfig.auto_sync_transactions ?? true,
        sync_inventory: existingConfig.auto_sync_products ?? true,
        ...credentials
      };
    }
    return {
      provider: '',
      config_name: '',
      auto_sync_enabled: true,
      sync_interval_minutes: '5',
      sync_sales: true,
      sync_inventory: true,
    };
  }, [mode, existingConfig, supportedProviders]);

  // Build dynamic sections based on selected provider
  const sections: AddModalSection[] = useMemo(() => {
    const baseSections: AddModalSection[] = [
      {
        title: 'Información del Proveedor',
        icon: Zap,
        columns: 1,
        fields: [
          {
            label: 'Sistema POS',
            name: 'provider',
            type: 'select',
            required: true,
            placeholder: 'Selecciona un sistema POS',
            options: supportedProviders.map(provider => ({
              value: provider.id,
              label: `${provider.logo} ${provider.name}`
            })),
            span: 2
          },
          {
            label: 'Nombre de la Configuración',
            name: 'config_name',
            type: 'text',
            required: true,
            placeholder: 'Ej: Mi Square POS 2025',
            helpText: 'Un nombre descriptivo para identificar esta configuración',
            span: 2
          }
        ]
      }
    ];

    // Add credentials section if provider is selected
    const provider = supportedProviders.find(p => p.id === selectedProvider);
    if (provider) {
      const credentialFields: AddModalField[] = provider.required_fields.map(field => ({
        label: field.label,
        name: `credential_${field.field}`,
        type: field.type === 'select' ? 'select' : 'text', // Map password/url to text
        required: field.required,
        placeholder: field.placeholder || `Ingresa ${field.label}`,
        helpText: field.help_text,
        options: field.options,
        span: field.type === 'select' ? 2 : 1
      }));

      baseSections.push({
        title: 'Credenciales de API',
        icon: Key,
        columns: 2,
        fields: credentialFields
      });
    }

    // Add sync settings section
    baseSections.push({
      title: 'Configuración de Sincronización',
      icon: RefreshCw,
      columns: 2,
      fields: [
        {
          label: 'Sincronización Automática',
          name: 'auto_sync_enabled',
          type: 'select',
          required: true,
          options: [
            { value: 'true', label: 'Activada' },
            { value: 'false', label: 'Desactivada' }
          ],
          defaultValue: 'true'
        },
        {
          label: 'Intervalo de Sincronización',
          name: 'sync_interval_minutes',
          type: 'select',
          required: true,
          options: [
            { value: '5', label: '5 minutos' },
            { value: '15', label: '15 minutos' },
            { value: '30', label: '30 minutos' },
            { value: '60', label: '1 hora' }
          ],
          defaultValue: '5'
        },
        {
          label: 'Sincronizar Ventas',
          name: 'sync_sales',
          type: 'select',
          required: true,
          options: [
            { value: 'true', label: 'Sí' },
            { value: 'false', label: 'No' }
          ],
          defaultValue: 'true'
        },
        {
          label: 'Sincronizar Inventario',
          name: 'sync_inventory',
          type: 'select',
          required: true,
          options: [
            { value: 'true', label: 'Sí' },
            { value: 'false', label: 'No' }
          ],
          defaultValue: 'true'
        }
      ]
    });

    return baseSections;
  }, [selectedProvider, supportedProviders]);

  const handleSave = async (formData: Record<string, any>) => {
    try {
      setLoading(true);

      // Find selected provider
      const provider = supportedProviders.find(p => p.id === formData.provider);
      if (!provider) {
        showToast.error('Por favor selecciona un sistema POS');
        return;
      }

      // Extract credentials and separate top-level fields
      const credentials: Record<string, any> = {};
      let environment: string | undefined;
      let location_id: string | undefined;

      provider.required_fields.forEach(field => {
        const credKey = `credential_${field.field}`;
        if (formData[credKey]) {
          const value = formData[credKey];

          // Extract environment and location_id to top level, but keep in credentials too
          if (field.field === 'environment') {
            environment = value;
          } else if (field.field === 'location_id') {
            location_id = value;
          }

          credentials[field.field] = value;
        }
      });

      // Build request payload with correct field names
      const payload: any = {
        tenant_id: tenantId,
        pos_system: formData.provider as POSSystem,           // FIXED: was 'provider'
        provider_name: formData.config_name as string,        // FIXED: was 'config_name'
        environment: (environment || 'sandbox') as POSEnvironment, // FIXED: extract from credentials
        credentials,
        sync_settings: {
          auto_sync_enabled: formData.auto_sync_enabled === 'true' || formData.auto_sync_enabled === true,
          sync_interval_minutes: parseInt(formData.sync_interval_minutes),
          sync_sales: formData.sync_sales === 'true' || formData.sync_sales === true,
          sync_inventory: formData.sync_inventory === 'true' || formData.sync_inventory === true,
          sync_customers: false
        },
        ...(location_id && { location_id })     // FIXED: add location_id if present
      };

      // Create or update configuration
      if (mode === 'edit' && existingConfig) {
        await posService.updatePOSConfiguration({
          ...payload,
          config_id: existingConfig.id
        });
        showToast.success('Configuración actualizada correctamente');
      } else {
        await posService.createPOSConfiguration(payload);
        showToast.success('Configuración creada correctamente');
      }

      onSuccess?.();
      onClose();
    } catch (error: any) {
      console.error('Error saving POS configuration:', error);
      showToast.error(error?.message || 'Error al guardar la configuración');
      throw error; // Let AddModal handle error state
    } finally {
      setLoading(false);
    }
  };

  // Handle field changes to update selectedProvider dynamically
  const handleFieldChange = (fieldName: string, value: any) => {
    if (fieldName === 'provider') {
      setSelectedProvider(value as POSSystem | '');
    }
  };

  return (
    <AddModal
      isOpen={isOpen}
      onClose={onClose}
      title="Configuración de Sistema POS"
      subtitle={mode === 'edit' ? 'Actualiza la configuración' : 'Configura un nuevo sistema para sincronizar ventas e inventario'}
      statusIndicator={{
        color: statusColors.inProgress.primary,
        text: mode === 'edit' ? 'Edición' : 'Nueva Configuración',
        icon: Zap,
        isCritical: false,
        isHighlight: true
      }}
      sections={sections}
      onSave={handleSave}
      loading={loading}
      size="xl"
      initialData={initialData}
      validationErrors={{}}
      onValidationError={(errors) => {
        // Custom validation if needed
        if (errors && Object.keys(errors).length > 0) {
          const firstError = Object.values(errors)[0];
          showToast.error(firstError);
        }
      }}
      onFieldChange={handleFieldChange}
    />
  );
};

export default CreatePOSConfigModal;
