import Styles from "@/constants/Styles";
import { apiSendOtp } from "@/lib/api";
import { useAuthSession } from "@/providers/AuthProvider";
import { useTheme } from "@/providers/ThemeProvider";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { StatusBar } from "expo-status-bar";
import { useState } from "react";
import { Image, SafeAreaView, View } from "react-native";
import { OtpInput } from "react-native-otp-entry";
import Toast from 'react-native-toast-message';
import { ButtonForm } from "../buttonForm";
import Text from "../Text";
import ToastCustom from "../toastCustom";

type Props = {
   phone: string
   otp: number
}

export default function ViewVerification({ phone, otp }: Props) {
   const [value, setValue] = useState('');
   const [otpFix, setOtpFix] = useState(otp)
   const { signIn, encryptToken } = useAuthSession();
   const { colors, activeTheme } = useTheme();

   const login = async () => {
      const valueUser = await AsyncStorage.getItem('user');
      if (valueUser != null) {
         await AsyncStorage.removeItem('user');
         const encrypted = await encryptToken(valueUser);
         signIn(encrypted);
      } else {
         return Toast.show({ type: 'small', text1: 'Terjadi kesalahan', position: 'bottom' })
      }
   }

   const onCheckOtp = () => {
      if (value === otpFix.toString()) {
         login()
      } else {
         return Toast.show({ type: 'small', text1: 'Kode OTP tidak sesuai', position: 'bottom' });
      }
   }

   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 Toast.show({ type: 'small', text1: 'Kode OTP berhasil dikirim ulang', })
         }
         return Toast.show({ type: 'small', text1: 'Terjadi kesalahan dalam mengirim kode OTP', })
      } catch (error) {
         console.error('Error fetching data:', error);
         return Toast.show({ type: 'small', text1: 'Terjadi kesalahan', })
      }
   }

   return (
      <SafeAreaView style={{ flex: 1, backgroundColor: colors.background }}>
         <StatusBar style={activeTheme === 'dark' ? 'light' : 'dark'} translucent={false} backgroundColor={colors.background} />
         <View style={[Styles.p20, Styles.h100]} >
            <View style={{ alignItems: "center", marginTop: 70, marginBottom: 50 }}>
               <Image
                  source={activeTheme === 'dark' ? require("../../assets/images/logo-dark.png") : require("../../assets/images/logo.png")}
                  style={[{ width: 300, height: 150 }]}
                  width={270}
                  height={110}
               />
               {/* <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>
            <OtpInput
               numberOfDigits={4}
               onTextChange={(text) => setValue(text)}
               focusColor={colors.tint}
               type="numeric"
               theme={{
                  containerStyle: {
                     width: '80%',
                     alignSelf: 'center'
                  },
                  pinCodeContainerStyle: { ...Styles.verificationCell, borderColor: colors.icon },
                  pinCodeTextStyle: { color: colors.text }
               }}
            />
            <View style={[{ width: '50%', alignSelf: 'center' }]}>
               <ButtonForm
                  text="SUBMIT"
                  onPress={() => { onCheckOtp() }}
               />
            </View>
            <Text style={[Styles.textInformation, Styles.mt05, { textAlign: 'center', color: colors.dimmed }]}>
               Tidak Menerima kode verifikasi?  <Text onPress={() => { resendOtp() }} style={[{ color: colors.tint }]}>Kirim Ulang</Text>
            </Text>
            <View style={{ flex: 1 }} />
            <View style={[{ alignItems: 'center' }]}>
               <Image
                  source={activeTheme === 'dark' ? require("../../assets/images/cogniti-dark.png") : require("../../assets/images/cogniti-light.png")}
                  style={{ width: 86, height: 27 }}
                  resizeMode="contain"
               />
            </View>
         </View>
         <ToastCustom position="bottom" />
      </SafeAreaView>
   )
}