/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 */

import React, { useState } from 'react';
import { Platform } from 'react-native';
import type {PropsWithChildren} from 'react';
import {
  ScrollView,
  StatusBar,
  StyleSheet,
  Text,
  useColorScheme,
  View,

  SafeAreaView,
  TextInput,
  Button,
  TouchableOpacity,
  NativeModules,
} from 'react-native';
import { Picker } from '@react-native-picker/picker'; // npm install @react-native-picker/picker
import CheckBox from '@react-native-community/checkbox'; // npm install @react-native-community/checkbox

import {
  Colors,
  DebugInstructions,
  Header,
  LearnMoreLinks,
  ReloadInstructions,
  
} from 'react-native/Libraries/NewAppScreen';

type SectionProps = PropsWithChildren<{
  title: string;
}>;

const styles2 = StyleSheet.create({
  sectionContainer: {
    marginTop: 32,
    paddingHorizontal: 24,
  },
  sectionTitle: {
    fontSize: 24,
    fontWeight: '600',
  },
  sectionDescription: {
    marginTop: 8,
    fontSize: 18,
    fontWeight: '400',
  },
  highlight: {
    fontWeight: '700',
  },
});

const { IzipayModule } = NativeModules;

function App() {
  const [modo, setModo] = useState('FULLSCREEND');
  const [valor, setValor] = useState('');
  const [tarjeta, setTarjeta] = useState(false);
  const [yape, setYape] = useState(false);

  const handleLaunch = async () => {
  
    try {
      const metodosSeleccionados = [];
      if (tarjeta) metodosSeleccionados.push('Tarjeta');
      if (yape) metodosSeleccionados.push('Yape');

      console.log(IzipayModule == null)
      console.log('Aqui invocamos el modulo nativo!');
      if (Platform.OS === 'ios') {
        var tranxId = (Date.now() * 1000).toString()
        var datetime = tranxId
        var nroOrden = Date.now().toString()
        const metodosSeleccionadosString: string = metodosSeleccionados.join(',');
        console.log(metodosSeleccionadosString)
        console.log(modo)
        const data = await IzipayModule.launchSdkActivity (
          'TEST',
          'pay',
          'VErethUtraQuxas57wuMuquprADrAHAb',//
          tranxId,
          '4324734',//'4001834',
          '',
          nroOrden,
          'PEN',
          '1.00',
          metodosSeleccionadosString,//el sdk acepta un enum, pero esa conversion se puede hacer en la clase nativa .swift //'card,yape,apple_pay',
          'mobile',
          'autorize',
          'pruebemerchantId',
          datetime,
          '',
          'Enrrique',
          'Pariasca',
          'epc@gmail.com',
          '999666999',
          'av prueba 123',
          'Lima',
          'Lima',
          'PE',
          '00001',
          'DNI',
          '12345621',
          'ESP',
          true,
          true,
          true,
          'red',
          '',//'#2D2C58',
          '',//'#2D2C58',
          '',//'#2D2C58',
          'https://logowik.com/content/uploads/images/shopping-cart5929.jpg',
          'https://www.google.com',
          modo,
        );
        console.log(data)
        setValor(data);
      } else if (Platform.OS === 'android') {
        const result = await IzipayModule.launch(valor, modo, metodosSeleccionados);
        const { status, signature, payload } = result;
        const responseText = `Success: ${status === 'success'}\n\nSignature: ${signature}\n\nPayload: ${JSON.stringify(payload, null, 2)}`;
        setValor(responseText);
      }      
    } catch (e) {
      setValor(`Error al iniciar el pago: ${e}`);
    }

  };

  const picker = Platform.OS === 'ios' ? (
    <Picker
      selectedValue={modo}
      onValueChange={(itemValue) => setModo(itemValue)}
      style={[styles.picker, { height: 200 }]} // Altura mínima para que no se corte
    >
      <Picker.Item label="FULLSCREEN" value="FULLSCREEN" />
      <Picker.Item label="EMBEBIDO" value="EMBEBIDO" />
    </Picker>
  ) : (
    <Picker
      selectedValue={modo}
      onValueChange={(itemValue) => setModo(itemValue)}
      style={styles.picker}
      mode="dropdown" // en Android: dropdown vs dialog
    >
      <Picker.Item label="FULLSCREEN" value="FULLSCREEN" />
      <Picker.Item label="EMBEBIDO" value="EMBEBIDO" />
    </Picker>
  );


  return (
    <SafeAreaView style={styles.container}>
      <Text style={styles.label}>Modo de Visualización</Text>
      {picker}
      <Text style={styles.label}>Método(s) de Pago</Text>
      <View style={styles.checkboxContainer}>
        <CheckBox value={tarjeta} onValueChange={setTarjeta} />
        <Text style={styles.checkboxLabel}>Tarjeta</Text>
      </View>
      <View style={styles.checkboxContainer}>
        <CheckBox value={yape} onValueChange={setYape} />
        <Text style={styles.checkboxLabel}>Yape</Text>
      </View>

      <Text style={styles.label}>Respuesta</Text>
      <TextInput
        style={[styles.input, { height: 200, textAlignVertical: 'top' }]}
        placeholder="Ingrese un valor"
        value={valor}
        onChangeText={setValor}
        keyboardType="default"
        multiline
      />

      <Button title="Lanzar Izipay" onPress={handleLaunch} />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, padding: 20 },
  label: { fontSize: 16, fontWeight: 'bold', marginTop: 20 },
  picker: { height: 50, width: '100%' },
  input: {
    borderWidth: 1, borderColor: '#ccc', padding: 10, borderRadius: 5, marginVertical: 10,
  },
  checkboxContainer: {
    flexDirection: 'row', alignItems: 'center', marginBottom: 10,
  },
  checkboxLabel: {
    marginLeft: 8,
  },
});

export default App;
