import React, { useContext, useState } from 'react';
import { useEffect } from 'react';
import { View, Text, StyleSheet, Pressable, TextInput, Alert } from 'react-native';
import { useNavigation, useRoute } from '@react-navigation/native';
import { CuentaMin } from './CuentaMin';
import { AuthContext } from '../context/Auth/AuthContext';
import { TransactionDebit } from '../interface/post';
import { sendTransaccion } from '../hooks/sendTransaccion';
import PubSub from 'pubsub-js';
import { Loader } from './Loader';
export const VistaPreviaValoPagar = () => {
  const navigate = useNavigation<any>();
  const [ValorPagar, setValorPagar] = React.useState<number>(0);
  const [transaccionData, setTransaccionData] = useState<TransactionDebit>();
  const [loader, setloader] = useState(false);
  const { dataUserCreditor, dataBank,token } = useContext(AuthContext);
  const route = useRoute<any>();
  useEffect(() => {
    if (dataUserCreditor && dataBank && dataBank.account.accountId!= dataUserCreditor.account.accountId) {
      setValorPagar(route.params.valorPagar);
      const transaccionData: TransactionDebit = {
        data: {
          debtor: {
            customer: {
              customerId: dataBank.customer.customerId,
              documentNumber: dataBank.customer.documentNumber,
              documentType: dataBank.customer.documentType,
              fullName: dataBank.customer.fullName,
            },
            account: {
              accountId: dataBank.account.accountId,
            },
          },
          creditor: {
            customer: {
              fullName: dataUserCreditor.customer.fullName,
              account: {
                accountId: dataUserCreditor.account.accountId,
              },
            },
          },
          transaction: {
            amount: String(route.params.valorPagar.toFixed(2)),
            currency: {
              code: 'USD',
            },
            description: 'TRANSFERENCIA 01',
          },
        },
      };
      setTransaccionData(transaccionData);
    } else {
      Alert.alert("No se puede realizar una transaccion a una misma cuenta bancaria")
      navigate.goBack();
    }
  }, [route]);
  const send = async (data: TransactionDebit) => {
    try {
      console.log("la data es"+JSON.stringify(data));
      const res = await sendTransaccion(token!,data);
      PubSub.publish('transaccion', res.data);
      navigate.navigate('ConfirmarTransaccion', {
        dataTransaccion: {
          datosDebtor: { ...data },
          datosDocument: { ...res.data },
        },  
      }
      
      );
      componentWillMount();
    } catch (err: any) {
      console.log(err.response.data);
      console.log("aqui")
      componentWillMount();
    }
  };
  function componentWillMount() {
    setTimeout(() => {
      setloader(false);
    }, 3000);
  }
  const accountbind = (account: string) => {
    const accountbin =
      account.substring(0, 4) + '*****' + account.substring(8, 11);
    return accountbin;
  };
  if (loader) {
    return (
      <>
        <Loader />
      </>
    );
  }
  return (
    <View style={styles.containerVistaPrevia}>
      <Text style={styles.encabezados}>Para </Text>
      <View style={styles.contenedorSeccion}>
        <Text style={styles.nombre}>{dataUserCreditor?.customer.fullName}</Text>
        <Text>Parar DeUna! -{}</Text>
        {dataUserCreditor && dataUserCreditor.account ? (
          <Text>
            Cuenta de ahorros -{' '}
            {accountbind(dataUserCreditor?.account.accountId)}
          </Text>
        ) : null}
      </View>
      <Text style={styles.encabezados}>Valor</Text>

      <View style={styles.contenedorSeccion}>
        <Text style={styles.ValorPagar}>
          ${ValorPagar ? ValorPagar.toFixed(2) : 0.0}
        </Text>
      </View>

      <Text style={styles.encabezados}>Desde</Text>
      {dataBank && dataBank.account ? (
        <CuentaMin numberAccount={accountbind(dataBank.account.accountId)} />
      ) : null}
      <Text style={styles.encabezados}>Descripcion</Text>

      <TextInput
        style={styles.input}
        placeholder="¿Que estas pagando? (Opcional)"
        maxLength={40}
      />
      <Pressable
        onPress={() => {
          send(transaccionData!);
          setloader(true);
        }}
        style={styles.Btncontinuar}
      >
        <Text>Pagar</Text>
      </Pressable>
    </View>
  );
};

const styles = StyleSheet.create({
  textoEncabezado: {
    fontWeight: 'bold',
    fontSize: 20,
  },
  encabezado: {
    width: '100%',
  },
  input: {
    backgroundColor: '#FFFFFF',
    borderStyle: 'solid',
    borderColor: 'black',
    padding: 10,
  },
  Btncontinuar: {
    width: '100%',
    backgroundColor: '#FFDD00',
    padding: 15,
    marginTop: 35,
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
  },
  nombre: {
    fontSize: 19,
    fontWeight: 'bold',
    color: 'black',
  },
  containerVistaPrevia: {
    flex: 1,
    padding: 35,
    width: '100%',
    backgroundColor: '#FFFFFF',
    // CAMBIAR LA ALTURA LA 100% DE LA PANTALLA
    height: 650,
  },
  encabezados: {
    fontWeight: 'bold',
    fontSize: 16,
    paddingTop: 10,
    paddingBottom: 10,
  },
  contenedorSeccion: {
    padding: 8,
  },
  ValorPagar: {
    fontSize: 36,
    fontWeight: 'bold',
    color: 'black',
  },
});
