import { ScrollView, Text, View, Image, Alert, } from "react-native";
import tw from "twrnc";
import InputField from "@/components/InputField";
import { images, icons } from "@/constants";
import { useState } from "react";
import CustomButton from "@/components/CustomButton";
import { Link, router } from "expo-router";
import OAuth from "@/components/OAuth";
import { useSignUp } from "@clerk/clerk-expo";
import { ReactNativeModal } from "react-native-modal";
import { fetchAPI } from "@/lib/fetch";
import { TokenCache } from "@/lib/auth";
const SignUp = () => {
  const { isLoaded, signUp, setActive } = useSignUp();
  const [showSuccessModal,setShowSuccessModal]= useState(false);
  const [form, setForm] = useState({
    name: "",
    email: "",
    password: "",
  });
  const [verification, setVerification] = useState({
    state: "default",
    error: "",
    code: "",
  })

  const onSignUpPress = async () => {
    if (!isLoaded){ return;}
    try {
      await signUp.create({
        emailAddress: form.email,
        password: form.password,
      })
      await signUp.prepareEmailAddressVerification({ strategy: "email_code" })
      setVerification({
        ...verification,
        state: "pending"
      })
    } catch (err:any) {
      Alert.alert("Error",err.errors[0].longMessage)
    }
  }
  const onVerifyPress = async () => {
    if (!isLoaded) return;

    try {
      const CompleteSignUp = await signUp.attemptEmailAddressVerification({
        code: verification.code,
      })
      if (CompleteSignUp.status === "complete") {
        const clerkId=signUp.createdUserId;
        const response= await fetchAPI("http://192.168.29.1:3000/api/users",{
          method:"POST",
          headers:{"Content-Type":"application/json"},
          body:JSON.stringify({
            name:form.name,
            email:form.email,
            clerkId,
          }),
        });
        console.log("User API Response:", response);
        await setActive({ session: CompleteSignUp.createdSessionId });
        setVerification({ ...verification, state: "success" })
      } else {
        setVerification({ ...verification, error: "Verification failed.", state: "failed" })
      }
    } catch (err: any) {
      setVerification({ ...verification, error: err.errors[0].longMessage, state: "success" })
    }
  }
  return (
    <ScrollView style={tw`flex-1 bg-white `}>
      <View style={tw`flex-1 bg-white`}>
        <View style={tw`relative w-full h-[250px]`}>
          <Image
            source={images.signUpCar}
            style={tw`z-0 w-full h-[250px]`}
          />
          <Text style={tw`text-2xl text-black font-JakartaSemiBold  absolute bottom-5 left-5`}>Create Your Account</Text>
        </View>
        <View style={tw`p-5`}>
          <InputField
            label="Name"
            placeholder="Enter your Name"
            icon={icons.person}
            value={form.name}
            onChangeText={(value) => setForm({ ...form, name: value })}
          />
          <InputField
            label="Email"
            placeholder="Enter your Email"
            icon={icons.email}
            value={form.email}
            onChangeText={(value) => setForm({ ...form, email: value })}
          />
          <InputField
            label="Password"
            placeholder="Enter your Password"
            icon={icons.lock}
            secureTextEntry={true}
            value={form.password}
            onChangeText={(value) => setForm({ ...form, password: value })}
          />
          <CustomButton title="Sign Up" onPress={onSignUpPress} style={tw`mt-6`} />
          <OAuth />
          <Link href="/sign-in" style={tw.style("text-lg text-center text-general-200  mt-10")}>
            <Text style={tw.style("text-black")}>Already Have an Account? </Text>
            <Text style={tw.style("text-primary-500")}>Log In</Text>
          </Link>
          <ReactNativeModal isVisible={verification.state === "pending"} onModalHide={()=> {if(verification.state==="success") setShowSuccessModal(true)} } >
          <View style={tw`bg-white px-7 py-9 rounded-2xl min-h-[300px]`}>
          <Text style={tw`text-2xl font-JakartaExtraBold mb-2`}>Verification</Text>
            <Text style={tw`font-Jakarta mb-5`}> We've sent a verification code to {form.email}</Text>
            <InputField label="Code"  icon={icons.lock} placeholder="12345" value={verification.code} keyboardType="numeric" onChangeText={(code)=>setVerification ({... verification,code}) }
            />
            {verification.error && (
              <Text style={tw`text-red-500 text-sm mt-1`}>{verification.error}</Text>
            )}
            <CustomButton title="Verify Email" onPress={onVerifyPress} style={[tw.style("mt-5 "),{ backgroundColor: "#38A169" }]} />
          </View>
          </ReactNativeModal>
          <ReactNativeModal isVisible={showSuccessModal}>
            <View style={tw`bg-white px-7 py-9 rounded-2xl min-h-[300px]`}>
              <Image source={images.check} style={tw`w-[110px] h-[110px] mx-auto my-5 `} />
              <Text style={tw`text-3xl font-JakartaBold text-center`}>Verified</Text>
              <Text style={tw`text-[14px] text-gray-400 font-Jakarta text-center mt-2`}>You have successfully verified your account.</Text>
              <CustomButton title="Browse Home" onPress={()=>{setShowSuccessModal(false); router.push("/(root)/(tabs)/home")}} style={tw`mt-5`} />
            </View>
          </ReactNativeModal>
        </View>
      </View>
    </ScrollView>
  );
};
export default SignUp;