import React, { useState, useEffect } from 'react';
import {
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  Alert,
  ScrollView,
  SafeAreaView,
} from 'react-native';
import { createMercadoPagoSDK, MercadoPagoConfig, PaymentResult } from '../src/ExpoMercadoPagoModule';

const config: MercadoPagoConfig = {
  publicKey: 'TEST-12345678-1234-1234-1234-123456789012', // Reemplaza con tu public key real
  siteId: 'MLA', // Argentina
  language: 'es',
};

const mercadopago = createMercadoPagoSDK(config);

export default function App() {
  const [isInitialized, setIsInitialized] = useState(false);
  const [isMercadoPagoInstalled, setIsMercadoPagoInstalled] = useState(false);
  const [sdkVersion, setSdkVersion] = useState('');
  const [lastPaymentResult, setLastPaymentResult] = useState<PaymentResult | null>(null);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    initializeSDK();
    checkMercadoPagoInstallation();
    getSDKVersion();
  }, []);

  const initializeSDK = async () => {
    try {
      setIsLoading(true);
      await mercadopago.initialize();
      setIsInitialized(true);
      console.log('MercadoPago SDK initialized successfully');
    } catch (error) {
      console.error('Failed to initialize MercadoPago SDK:', error);
      Alert.alert('Error', 'Failed to initialize MercadoPago SDK');
    } finally {
      setIsLoading(false);
    }
  };

  const checkMercadoPagoInstallation = async () => {
    try {
      const installed = await mercadopago.isMercadoPagoInstalled();
      setIsMercadoPagoInstalled(installed);
    } catch (error) {
      console.error('Error checking MercadoPago installation:', error);
    }
  };

  const getSDKVersion = async () => {
    try {
      const version = await mercadopago.getSDKVersion();
      setSdkVersion(version);
    } catch (error) {
      console.error('Error getting SDK version:', error);
    }
  };

  const startPayment = async () => {
    if (!isInitialized) {
      Alert.alert('Error', 'SDK not initialized');
      return;
    }

    // Este preference ID debe ser generado en tu backend
    const preferenceId = '123456789-12345678-12345678-12345678';
    
    try {
      setIsLoading(true);
      
      // Agregar listener para eventos de pago
      const subscription = mercadopago.addPaymentResultListener((result) => {
        console.log('Payment result received:', result);
        setLastPaymentResult(result);
        
        switch (result.status) {
          case 'approved':
            Alert.alert('¡Éxito!', `Pago aprobado. ID: ${result.paymentId}`);
            break;
          case 'rejected':
            Alert.alert('Error', `Pago rechazado: ${result.statusDetail}`);
            break;
          case 'pending':
            Alert.alert('Pendiente', 'El pago está pendiente de confirmación');
            break;
          case 'in_process':
            Alert.alert('En proceso', 'El pago está siendo procesado');
            break;
        }
      });

      const result = await mercadopago.startPayment(preferenceId);
      console.log('Payment completed:', result);
      
      // Remover listener después del pago
      mercadopago.removePaymentResultListener(subscription);
      
    } catch (error) {
      console.error('Payment failed:', error);
      Alert.alert('Error', 'El pago falló. Inténtalo de nuevo.');
    } finally {
      setIsLoading(false);
    }
  };

  const startPaymentWithCustomPreference = async () => {
    if (!isInitialized) {
      Alert.alert('Error', 'SDK not initialized');
      return;
    }

    // Ejemplo con preference ID personalizado
    const customPreferenceId = '987654321-87654321-87654321-87654321';
    
    try {
      setIsLoading(true);
      const result = await mercadopago.startPayment(customPreferenceId);
      console.log('Custom payment completed:', result);
      setLastPaymentResult(result);
      
      if (result.status === 'approved') {
        Alert.alert('¡Éxito!', `Pago aprobado. ID: ${result.paymentId}`);
      } else {
        Alert.alert('Error', `Pago ${result.status}: ${result.statusDetail}`);
      }
      
    } catch (error) {
      console.error('Custom payment failed:', error);
      Alert.alert('Error', 'El pago falló. Inténtalo de nuevo.');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      <ScrollView contentContainerStyle={styles.scrollContainer}>
        <Text style={styles.title}>Expo MercadoPago SDK</Text>
        
        <View style={styles.statusContainer}>
          <Text style={styles.statusText}>
            SDK Status: {isInitialized ? '✅ Initialized' : '❌ Not Initialized'}
          </Text>
          <Text style={styles.statusText}>
            MercadoPago App: {isMercadoPagoInstalled ? '✅ Installed' : '❌ Not Installed'}
          </Text>
          {sdkVersion && (
            <Text style={styles.statusText}>SDK Version: {sdkVersion}</Text>
          )}
        </View>

        <View style={styles.buttonContainer}>
          <TouchableOpacity
            style={[styles.button, styles.primaryButton]}
            onPress={startPayment}
            disabled={!isInitialized || isLoading}
          >
            <Text style={styles.buttonText}>
              {isLoading ? 'Procesando...' : 'Iniciar Pago'}
            </Text>
          </TouchableOpacity>

          <TouchableOpacity
            style={[styles.button, styles.secondaryButton]}
            onPress={startPaymentWithCustomPreference}
            disabled={!isInitialized || isLoading}
          >
            <Text style={styles.buttonText}>
              Pago con Preference ID Personalizado
            </Text>
          </TouchableOpacity>

          <TouchableOpacity
            style={[styles.button, styles.infoButton]}
            onPress={checkMercadoPagoInstallation}
            disabled={isLoading}
          >
            <Text style={styles.buttonText}>Verificar Instalación</Text>
          </TouchableOpacity>
        </View>

        {lastPaymentResult && (
          <View style={styles.resultContainer}>
            <Text style={styles.resultTitle}>Último Resultado:</Text>
            <Text style={styles.resultText}>Status: {lastPaymentResult.status}</Text>
            <Text style={styles.resultText}>ID: {lastPaymentResult.paymentId}</Text>
            <Text style={styles.resultText}>Detail: {lastPaymentResult.statusDetail}</Text>
            {lastPaymentResult.error && (
              <Text style={styles.errorText}>
                Error: {lastPaymentResult.error.message}
              </Text>
            )}
          </View>
        )}

        <View style={styles.infoContainer}>
          <Text style={styles.infoTitle}>Información Importante:</Text>
          <Text style={styles.infoText}>
            • Reemplaza la public key con tu clave real de MercadoPago
          </Text>
          <Text style={styles.infoText}>
            • Los preference IDs deben ser generados en tu backend
          </Text>
          <Text style={styles.infoText}>
            • Para testing, usa las credenciales de prueba de MercadoPago
          </Text>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  scrollContainer: {
    flexGrow: 1,
    padding: 20,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    textAlign: 'center',
    marginBottom: 30,
    color: '#333',
  },
  statusContainer: {
    backgroundColor: 'white',
    padding: 15,
    borderRadius: 10,
    marginBottom: 20,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  statusText: {
    fontSize: 16,
    marginBottom: 5,
    color: '#666',
  },
  buttonContainer: {
    marginBottom: 20,
  },
  button: {
    padding: 15,
    borderRadius: 10,
    marginBottom: 10,
    alignItems: 'center',
  },
  primaryButton: {
    backgroundColor: '#007AFF',
  },
  secondaryButton: {
    backgroundColor: '#34C759',
  },
  infoButton: {
    backgroundColor: '#FF9500',
  },
  buttonText: {
    color: 'white',
    fontSize: 16,
    fontWeight: '600',
  },
  resultContainer: {
    backgroundColor: 'white',
    padding: 15,
    borderRadius: 10,
    marginBottom: 20,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  resultTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 10,
    color: '#333',
  },
  resultText: {
    fontSize: 14,
    marginBottom: 5,
    color: '#666',
  },
  errorText: {
    fontSize: 14,
    marginTop: 5,
    color: '#FF3B30',
    fontWeight: '500',
  },
  infoContainer: {
    backgroundColor: '#E3F2FD',
    padding: 15,
    borderRadius: 10,
    borderLeftWidth: 4,
    borderLeftColor: '#2196F3',
  },
  infoTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    marginBottom: 10,
    color: '#1976D2',
  },
  infoText: {
    fontSize: 14,
    marginBottom: 5,
    color: '#424242',
  },
}); 