import React, { useEffect, useState, useContext } from 'react';
import { View, Text, Pressable, StyleSheet, Alert } from 'react-native';
import { useNavigation, useRoute } from '@react-navigation/native';
import { getUsuariotoPay } from '../hooks/getUserDeUna';
import { AuthContext } from '../context/Auth/AuthContext';
import { Loader } from './Loader';
export const ValorPagar = () => {
  const [valorPagar, setvalorPagar] = useState<number>(0.0);
  const route = useRoute<any>();
  interface InfoPerson {
    name: string;
    number: number;
  }
  const [InformacionUsuario] = useState<InfoPerson>();
  const { cargarUserCredit, dataUserCreditor, token } = useContext(AuthContext);
  const [isLoading, setisLoading] = useState(false);
  const navigate = useNavigation<any>();
  async function cargarDatos(token: string) {
    setisLoading(true);
    try {
      console.log(token)
      const phone = route.params.number.replace(/\s+/g, '');
      const data = await getUsuariotoPay(token, phone);
      cargarUserCredit(data);
      setisLoading(false);
     
    } catch (error) {
      Alert.alert('Error', 'No se pudo cargar el usuario');
      cargarUserCredit(null);
      navigate.navigate('PantallaInicial');
      setisLoading(false);
    }
  }
  useEffect(() => {
    async function loadData() {
      await cargarDatos(token!);
      if (!dataUserCreditor) {
        navigate.goBack(); 
        console.log("Aqui ")
      }
    }
    loadData()
   
  }, [route.params.number]);
  function touchNumber(num: number) {
    if (valorPagar < 1000) {
      if (num >= 0 && num <= 0.09) {
        setvalorPagar(valorPagar * 10 + num);
      } else {
        if (num === 10) {
          setvalorPagar(valorPagar * 100);
        }
      }
    }
    if (num === 11) {
      let aux: RegExpMatchArray | null = (valorPagar / 10)
        .toString()
        .match(/^\d+(?:\.\d{0,2})?/);
      if (aux != null) {
        setvalorPagar(Number.parseFloat(aux.toString()));
      }
    }
  }
  if (isLoading) {
    return (
      <View style={styles.container}>
       <Loader testID={''} />
      </View>
    );
  }
  return (
    <View style={styles.container}>
      <Text>Para:</Text>
      {dataUserCreditor ? (
        <Text>{dataUserCreditor.customer.fullName}</Text>
      ) : null}
      <Text style={styles.textoSecundario}> {} </Text>
      <Text>{}</Text>
      <Text style={styles.valor}>$ {valorPagar.toFixed(2)}</Text>
      <Text style={[styles.alerta, valorPagar > 299.99 && styles.disableAlert]}>
        Valor máximo por cada pago $ 299.99
      </Text>

      <View>
        <View style={styles.filasNumeros}>
          <Pressable
            onPress={() => {
              touchNumber(0.01);
            }}
          >
            <Text style={styles.numeros}>1</Text>
          </Pressable>
          <Pressable
            onPress={() => {
              touchNumber(0.02);
            }}
          >
            <Text style={styles.numeros}>2</Text>
          </Pressable>
          <Pressable
            onPress={() => {
              touchNumber(0.03);
            }}
          >
            <Text style={styles.numeros}>3</Text>
          </Pressable>
        </View>
        <View style={styles.filasNumeros}>
          <Pressable
            onPress={() => {
              touchNumber(0.04);
            }}
          >
            <Text style={styles.numeros}>4</Text>
          </Pressable>
          <Pressable
            onPress={() => {
              touchNumber(0.05);
            }}
          >
            <Text style={styles.numeros}>5</Text>
          </Pressable>
          <Pressable
            onPress={() => {
              touchNumber(0.06);
            }}
          >
            <Text style={styles.numeros}>6</Text>
          </Pressable>
        </View>
        <View style={styles.filasNumeros}>
          <Pressable
            onPress={() => {
              touchNumber(0.07);
            }}
          >
            <Text style={styles.numeros}>7</Text>
          </Pressable>
          <Pressable
            onPress={() => {
              touchNumber(0.08);
            }}
          >
            <Text style={styles.numeros}>8</Text>
          </Pressable>
          <Pressable
            onPress={() => {
              touchNumber(0.09);
            }}
          >
            <Text style={styles.numeros}>9</Text>
          </Pressable>
        </View>
        <View style={styles.filasNumeros}>
          <Pressable
            onPress={() => {
              touchNumber(10);
            }}
          >
            <Text style={styles.numeros}>00</Text>
          </Pressable>
          <Pressable
            onPress={() => {
              touchNumber(0);
            }}
          >
            <Text style={styles.numeros}>0</Text>
          </Pressable>
          <Pressable
            onPress={() => {
              touchNumber(11);
            }}
          >
            <Text style={styles.numeros}>Borrar</Text>
          </Pressable>
        </View>
      </View>
      {valorPagar < 299 && valorPagar > 0 ? (
        <Pressable
          onPress={() =>
            navigate.navigate('Confirmacion', {
              number: InformacionUsuario?.number,
              valorPagar: valorPagar,
            })
          }
          style={styles.Btncontinuar}
        >
          <Text>Continuar</Text>
        </Pressable>
      ) : (
        <Pressable
          disabled
          onPress={() => Alert.alert('holi')}
          style={styles.BtncontinuarDisabled}
        >
          <Text>Continuar</Text>
        </Pressable>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  textoSecundario: {
    fontSize: 18,
    fontWeight: 'bold',
  },
  container: {
    display: 'flex',
    width: '100%',
    height: '100%',
    alignItems: 'center',
    backgroundColor: 'white',
    paddingTop: 30,
  },
  valor: {
    fontSize: 50,
    fontWeight: 'bold',
    paddingTop: 40,
    paddingBottom: 40,
  },
  filasNumeros: {
    display: 'flex',
    flexDirection: 'row',
  },
  numeros: {
    width: 120,
    height: 90,
    textAlign: 'center',
    fontSize: 25,
    fontWeight: 'bold',
  },
  Btncontinuar: {
    width: '90%',
    backgroundColor: '#FFDD00',
    padding: 15,
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
  },
  BtncontinuarDisabled: {
    width: '90%',
    backgroundColor: '#FFDD00',
    padding: 15,
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    opacity: 0.5,
  },
  alerta: {
    color: '#FF0000',
    opacity: 0,
    paddingBottom: 45,
    margin: -30,
  },
  disableAlert: {
    opacity: 1,
  },
});
