import Styles from "@/constants/Styles"
import { apiCheckPhoneLogin, 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, Platform, SafeAreaView, View } from "react-native"
import Toast from "react-native-toast-message"
import { ButtonForm } from "../buttonForm"
import { InputForm } from "../inputForm"
import ModalLoading from "../modalLoading"
import Text from "../Text"
import ToastCustom from "../toastCustom"

type Props = {
   onValidate: ({ phone, otp }: { phone: string, otp: number }) => void
}

export default function ViewLogin({ onValidate }: Props) {
   const [loadingLogin, setLoadingLogin] = useState(false)
   const [disableLogin, setDisableLogin] = useState(true)
   const [phone, setPhone] = useState('')
   const { signIn, encryptToken } = useAuthSession();
   const { colors, activeTheme } = useTheme();

   const handleCheckPhone = async () => {
      try {
         setLoadingLogin(true)
         const response = await apiCheckPhoneLogin({ phone: `62${phone}` })
         if (response.success) {
            if (response.isWithoutOTP) {
               const encrypted = await encryptToken(response.id)
               signIn(encrypted)
            } else {
               const otp = Math.floor(1000 + Math.random() * 9000)
               const responseOtp = await apiSendOtp({ phone: `62${phone}`, otp })
               if (responseOtp == 200) {
                  await AsyncStorage.setItem('user', response.id)
                  return onValidate({ phone: `62${phone}`, otp })
               } else {
                  return Toast.show({ type: 'small', text1: 'Gagal mengirim kode verifikasi', position: 'bottom' })
               }
            }
         } else {
            return Toast.show({ type: 'small', text1: response.message, position: 'bottom' })
         }
      } catch (error: any) {
         console.error(error);
         const message = error?.response?.data?.message || "Gagal login"

         Toast.show({ type: 'small', text1: message })
      } finally {
         setLoadingLogin(false)
      }
   };

   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.textSubtitle2]}>Digitalisasi Desa Transparansi Kerja</Text> */}
            </View>
            <InputForm
               onChange={(val) => {
                  val == "" ? setDisableLogin(true) : setDisableLogin(false)
                  setPhone(val)
               }}
               type="numeric"
               placeholder="XXX-XXX-XXXX"
               itemLeft={<Text style={[Platform.OS === 'ios' && Styles.mt02]}>+62</Text>}
               info="Kami akan mengirim kode verifikasi melalui WhatsApp, guna mengonfirmasikan nomor Anda." />
            <View style={[{ width: '50%', alignSelf: 'center' }]}>
               <ButtonForm
                  text="MASUK"
                  onPress={() => { handleCheckPhone() }}
                  disabled={disableLogin}
               />
            </View>
            <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>
         {
            loadingLogin && <ModalLoading isVisible={true} setVisible={setLoadingLogin} />
         }
         <ToastCustom position="bottom" />
      </SafeAreaView>

   )
}