import Styles from "@/constants/Styles";
import { apiSendOtp } from "@/lib/api";
import { useAuthSession } from "@/providers/AuthProvider";
import CryptoES from "crypto-es";
import { useState } from "react";
import { Image, Text, ToastAndroid, View } from "react-native";
import { CodeField, Cursor, useBlurOnFulfill, useClearByFocusCell } from "react-native-confirmation-code-field";
import { ButtonForm } from "../buttonForm";

type Props = {
   phone: string
   otp: number
}

export default function ViewVerification({ phone, otp }: Props) {
   const [value, setValue] = useState('');
   const [otpFix, setOtpFix] = useState(otp)
   const ref = useBlurOnFulfill({ value, cellCount: 4 });
   const [props, getCellOnLayoutHandler] = useClearByFocusCell({
      value,
      setValue,
   });
   const { signIn } = useAuthSession();



   const login = (): void => {
      var mytexttoEncryption = "contohLoginMobileDarmasaba"
      const encrypted = CryptoES.AES.encrypt(mytexttoEncryption, "your password").toString();
      signIn(encrypted);
   }

   const onCheckOtp = () => {
      if (value === otpFix.toString()) {
         login()
      } else {
         return ToastAndroid.show('Kode OTP tidak sesuai', ToastAndroid.SHORT)
      }
   }

   const resendOtp = async () => {
      try {
         const otpNew = Math.floor(1000 + Math.random() * 9000)
         setOtpFix(otpNew)
         const responseOtp = await apiSendOtp({ phone, otp: otpNew })
         if (responseOtp == 200) {
            return ToastAndroid.show('Kode OTP berhasil dikirim ulang', ToastAndroid.SHORT)
         }
         return ToastAndroid.show('Terjadi kesalahan dalam mengirim kode OTP', ToastAndroid.SHORT)
      } catch (error) {
         console.error('Error fetching data:', error);
         return ToastAndroid.show('Terjadi kesalahan', ToastAndroid.SHORT)
      }
   }

   return (
      <>
         <View style={Styles.wrapLogin} >
            <View style={{ alignItems: "center", marginVertical: 50 }}>
               <Image
                  source={require("../../assets/images/splash-icon.png")}
                  style={{ width: 130, height: 130 }}
               />
               <Text style={[Styles.textSubtitle]}>PERBEKEL DARMASABA</Text>
            </View>
            <View style={[Styles.mb30]}>
               <Text style={[Styles.textDefaultSemiBold]}>Verifikasi Nomor Telepon</Text>
               <Text style={[Styles.textMediumNormal]}>Masukkan kode yang kami kirimkan melalui WhatsApp</Text>
               <Text style={[Styles.textMediumSemiBold]}>+{phone}</Text>
            </View>
            <CodeField
               ref={ref}
               {...props}
               value={value}
               rootStyle={{ width: '80%', alignSelf: 'center' }}
               onChangeText={setValue}
               cellCount={4}
               keyboardType="number-pad"
               renderCell={({ index, symbol, isFocused }) => (
                  <Text
                     key={index}
                     style={[Styles.verificationCell, isFocused && Styles.verificationFocusCell]}
                     onLayout={getCellOnLayoutHandler(index)}>
                     {symbol || (isFocused ? <Cursor /> : null)}
                  </Text>
               )}
            />
            <ButtonForm
               text="SUBMIT"
               onPress={() => { onCheckOtp() }}
            />
            <Text style={[Styles.textInformation, Styles.mt05, Styles.cDefault, { textAlign: 'center' }]}>
               Tidak Menerima kode verifikasi?  <Text onPress={() => { resendOtp() }}>Kirim Ulang</Text>
            </Text>
         </View>
      </>
   )
}