import {
  StyleSheet,
  Text,
  ScrollView,
  TouchableWithoutFeedback,
  SafeAreaView,
  FlatList,
  TextInput,
  ActivityIndicator,
} from 'react-native';
import React, { useCallback, useEffect, useState, useContext } from 'react';
import { Provider as ProviderComponent } from 'react-native-paper';
import Contacts from 'react-native-contacts';
import { useNavigation } from '@react-navigation/native';
import { View, Pressable, Alert } from 'react-native';
import { PermissionsAndroid } from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import { getUserDeUna } from '../hooks/getUserDeUna';
import { AuthContext } from '../context/Auth/AuthContext';
import type { PhoneNumbers } from '../interface/IGetUserDeUna';

export interface DatosContactos {
  displayName?: string;
  phoneNumbers?: PhoneNumbers[];
  isNumberRegistered?: boolean;
}
export interface DatosNumberContactos {
  Phone: string;
}

export const ContactosPagar = () => {
  const [ContactosUsuario, setContactosUsuario] = useState<any>();
  const [isLoading,setisLoading]=useState<boolean>(false);
  const [searchList, setSearchList] = useState<any[]>();
  const navigate = useNavigation<any>();
  const {token} = useContext(AuthContext);  
  useEffect(() => {
    
    inicializarDatos();
    
  }, []);
  async function inicializarDatos() {
    setisLoading(true)
    try {
      if(token!=null){
        const datos = await getUserDeUna(token);
        PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.READ_CONTACTS!, {
        title: 'Contacts',
        message: 'This app would like to view your contacts.',
        buttonPositive: 'Please accept bare mortal',
      })
        .then(() => {
          Contacts.getAll().then((contacts) => {
            const contactos: DatosContactos[] = contacts.map(
              (item: DatosContactos) => ({
                displayName: item.displayName,
                phoneNumbers: item.phoneNumbers,
                isNumberRegistered: datos.some(
                  (dato: DatosNumberContactos) =>
                    dato.Phone.replace(/\s+/g, '') ==
                    item.phoneNumbers![0]?.number?.replace(/\s+/g, '')
                ),
              })
            );
            setisLoading(false)
            setContactosUsuario(contactos);
            setSearchList(contactos);
          });
        })
        .catch((e) => {
          setisLoading(false)
          Alert.alert('Error', 'No se puede acceder a los contactos' + e);
        });
      }
      else{
        console.log(token+ "es nulo")
        setisLoading(false)
      }
    }
    catch (error) {
      console.log(error)
    }
  }
  const render = useCallback(({ item }: any) => {
    if (item.isNumberRegistered == 1) {
      return (
        <TouchableWithoutFeedback
          onPress={() =>{
            console.log(item.phoneNumbers![0]?.number)
            navigate.navigate('PayRecibe', {
              name: item.displayName,
              number: item.phoneNumbers![0]?.number,
            })
          }
          }
        >
          <View style={styles.container}>
            <View style={styles.contacto}>
              <Text style={{ fontWeight: "bold", paddingBottom: 2 }}>{item.displayName}</Text>
              <Text style={{ fontSize: 12 }}>Pagar Deuna!- {item.phoneNumbers![0]?.number}</Text>
            </View>
          </View>
        </TouchableWithoutFeedback>
      );
    } else {
      return (
        <View style={{ ...styles.container }}>
          <View style={styles.contacto}>
            <Text style={{ fontWeight: "bold", opacity: 0.7, paddingBottom: 2 }}>{item.displayName}</Text>
            <Text style={{ fontSize: 12 }}>{item.phoneNumbers![0]?.number}</Text>
          </View>
          <View style={styles.containerInvitar}>
            <Pressable
              onPress={() =>
                Alert.alert(
                  'Se envio la invitacion al usuario satisfactoriamente '
                )
              }
            >
              <Text style={styles.textoInvitar}>Invitar</Text>
            </Pressable>
          </View>
        </View>
      );
    }
  }, [])

  const findContact = useCallback(
    (text: string) => {
      if (text) {
        const newData = ContactosUsuario.filter((item: DatosContactos) => {
          const itemData = item.displayName
            ? item.displayName.toUpperCase()
            : ''.toUpperCase();
          const textData = text.toUpperCase();
          return itemData.indexOf(textData) > -1;
        });
        setSearchList(newData);
      } else {
        setSearchList(ContactosUsuario);
      }
    },
    [ContactosUsuario]
  );
  const renderLoader = () => (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <ActivityIndicator size="large" color="#0000ff" />
    </View>
  );
  return (
    <ProviderComponent>
      <ScrollView style={styles.container1}>
        <SafeAreaView style={styles.containerFinder}>
          <Text style={{ color: 'white', margin: 10, textAlign: "center", fontWeight: "bold", fontSize: 17 }}>¿A quien quieres Pagar?</Text>
          <TextInput style={styles.input} onChangeText={findContact} placeholder={"Escribe un nombre, telefono o cuenta...."} />
        </SafeAreaView>
        <View style={styles.section}>
          <Text style={{ fontWeight: "bold" }}>Sugerencias</Text>
        </View>
        <Pressable onPress={() => navigate.navigate("CamaraQrNavigate")} style={styles.sectionQR}>
          <View style={styles.containerIcono}><Icon name={"qrcode"} size={25} color={"white"}></Icon></View>
          <Text style={styles.textoQR}>Escanear un código QR</Text>
        </Pressable>
        <View style={styles.section}>
          <Text style={{ fontWeight: "bold" }}>Mis Contactos</Text>
        </View>

        {!isLoading?<FlatList
          data={searchList?.sort(
            (a: DatosContactos, b: DatosContactos) =>
              Number(b.isNumberRegistered) - Number(a.isNumberRegistered)
          ).slice(0,15)}
          renderItem={render}
          disableScrollViewPanResponder={true}
          
        />:renderLoader()}
      </ScrollView>
    </ProviderComponent>
  );
};
const styles = StyleSheet.create({
  sectionQR: {
    backgroundColor: 'white',
    height: 60,
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
    paddingLeft: 15,
  },
  containerIcono: {
    backgroundColor: '#572364',
    marginRight: 10,
    width: 40,
    height: 40,
    borderRadius: 40,
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
  },
  textoQR: {
    fontWeight: 'bold',
    fontSize: 15,
  },
  section: {
    padding: 5,
    paddingLeft: 15,
  },
  containerInvitar: {
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',

  },
  textoInvitar: {
    fontWeight: 'bold',
    padding: 5,
    paddingLeft: 20,
    paddingRight: 20,
    borderRadius: 20,
    backgroundColor: '#e8d1e7',
  },
  container1: {
    flex: 1,
    height: '100%',
  },
  contacto: {
    display: 'flex',
  },
  container: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'space-between',
    backgroundColor: 'white',
    width: '100%',
    padding: 10,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 3.84,
    elevation: 5,
  },
  input: {
    flexBasis: '30%',
    alignContent: 'center',
    height: 40,
    margin: 12,
    borderColor: '#7a42f4',
    borderWidth: 1,
    backgroundColor: 'white',
  },
  containerFinder: {
    flex: 1,
    backgroundColor: '#572364',
    width: '100%',
    height: '100%',
    padding: 10,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 3.84,
    elevation: 5,
  },
});
