import AuthLayout from "@/components/auth/auth-layout";
import InputGroup from "@/components/auth/InputGroup";
import RegistrationDisabled from "@/components/auth/registration-disabled";
import SocialLogin from "@/components/auth/SocialLogin";
import BackButtonTitle from "@/components/ui/BackButtonTitle";
import Button from "@/components/ui/Button";
import { countryCodes } from "@/constants/country-codes";
import { useQueryMutation } from "@/hooks/mutate/useQueryMutation";
import { useAuthHandler } from "@/hooks/useAuthHandler";
import { useColor } from "@/hooks/useColor";
import { useAuthStore } from "@/providers/AuthStoreProviders";
import { AuthStore } from "@/stores/auth";
import { User } from "@/types/user";
import { getUserCountryCode } from "@/utils/geolocation";
import { showToast } from "@/utils/toast";
import { Ionicons } from "@expo/vector-icons";
import { router } from "expo-router";
import { CaretDown, Globe, RocketLaunch } from "phosphor-react-native";
import { useEffect, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { Modal, Platform, Pressable, ScrollView, Text, TextInput, View } from "react-native";

interface RegisterFormData {
  first_name: string;
  last_name: string;
  email: string;
  phone: string;
  password: string;
  password_confirmation: string;
  terms: boolean;
  captcha_token?: string | null;
}

export default function SignUp() {
  const { login } = useAuthStore((state: AuthStore) => state);
  const { appInfo } = useAuthStore((state: any) => state);
  const { primary } = useColor();
  const { redirect } = useAuthHandler();
  const [modalVisible, setModalVisible] = useState(false);
  const [countryCode, setCountryCode] = useState<string | undefined>(undefined);
  const [signUpForm, setSignUpForm] = useState({
    country_code: "BD",
    dial_code: "+880",
    captcha_token: "",
  });

  const {
    control,
    formState: { errors: formErrors },
    handleSubmit,
  } = useForm<RegisterFormData>();

  useEffect(() => {
    (async () => {
      const code = await getUserCountryCode();
      if (code) {
        setCountryCode(code);
      }
    })();
  }, []);

  useEffect(() => {
    (async () => {
      const code = await getUserCountryCode();
      if (code) {
        const filteredCountry = countryCodes.find((country) => country.code.toLowerCase() === countryCode?.toLowerCase());
        setSignUpForm((prev) => ({
          ...prev,
          country_code: code,
          dial_code: filteredCountry?.dial_code ?? "+880",
        }));
      }
    })();
  }, [countryCode]);

  const {
    mutate,
    isLoading,
    backendErrors: errors,
  } = useQueryMutation({
    isPublic: true,
    url: "/register",
  });

  const onSubmit = handleSubmit((data) => {
    mutate(
      { ...signUpForm, ...data, phone: `${signUpForm.dial_code}${data.phone}` },
      {
        onSuccess: async (response: any) => {
          const data = response?.data;
          const user = data?.user as User;

          if (!data?.token || !data?.user) {
            return;
          }

          login(data.token, user);
          showToast({
            type: "success",
            text: "Sign Up Successfull!",
          });
          const redirectURL = await redirect(user);
          router.push(redirectURL as any);
        },
      },
    );
  });

  const isRegistrationEnabled = appInfo?.application_info?.extra_service?.system_config?.user_registration?.is_enabled;

  return (
    <AuthLayout>
      {isRegistrationEnabled ? (
        <View className="pb-10">
          <View className="py-2">
            <BackButtonTitle title="Create Account" />
          </View>

          <View className="mt-8 mb-6 p-6 rounded-3xl" style={{ backgroundColor: primary[5] }}>
            <View className="size-14 rounded-2xl justify-center items-center shadow-sm" style={{ backgroundColor: "white" }}>
              <RocketLaunch size={32} color={primary.base} weight="duotone" />
            </View>
            <Text className="text-3xl font-manrope-extrabold text-slate-900 pt-5">Get Started</Text>
            <Text className="text-slate-500 w-[95%] pt-2 text-lg font-manrope-medium">Join Investra today and start building your real estate portfolio.</Text>
          </View>

          <View className="gap-y-5">
            <View className="flex-row gap-x-4">
              <View className="flex-1">
                <InputGroup control={control} label="First Name" name="first_name" error={formErrors.first_name} backendError={errors?.first_name} />
              </View>
              <View className="flex-1">
                <InputGroup control={control} label="Last Name" name="last_name" error={formErrors.last_name} backendError={errors?.last_name} />
              </View>
            </View>

            <InputGroup control={control} label="Email Address" name="email" error={formErrors.email} backendError={errors?.email} keyboardType="email-address" />

            <View>
              <Text className="text-lg font-manrope-semibold pb-2 text-slate-900">Phone Number</Text>
              <View className="flex-row items-center gap-x-3">
                <Pressable
                  onPress={() => setModalVisible(true)}
                  className={`flex-row items-center justify-between min-w-[100px] rounded-xl border bg-white px-4 py-3.5 ${formErrors?.phone || errors?.phone ? "border-red-500" : "border-slate-200"}`}
                >
                  <Text className="text-lg font-manrope-semibold text-slate-700">{signUpForm.dial_code}</Text>
                  <CaretDown size={14} color="#64748b" weight="bold" />
                </Pressable>

                <Controller
                  control={control}
                  rules={{ required: "Phone number is required" }}
                  render={({ field: { onChange, onBlur, value } }) => (
                    <View
                      className={`flex-1 rounded-xl border bg-white px-5 py-1 ${
                        formErrors?.phone || errors?.phone ? "border-red-500" : "border-slate-200"
                      } ${Platform.OS === "ios" ? "py-3.5" : "py-0.5"}`}
                    >
                      <TextInput placeholder="Phone Number" onBlur={onBlur} onChangeText={onChange} value={value} className="text-lg font-manrope-semibold text-color1" keyboardType="phone-pad" />
                    </View>
                  )}
                  name="phone"
                />
              </View>
              {(formErrors.phone || errors?.phone) && <Text className="text-red-500 text-sm mt-1 font-manrope-medium">{formErrors.phone?.message || errors?.phone}</Text>}
            </View>

            <InputGroup control={control} label="Password" name="password" error={formErrors.password} backendError={errors?.password} secureTextEntry={true} />

            <InputGroup
              control={control}
              label="Confirm Password"
              name="password_confirmation"
              error={formErrors.password_confirmation}
              backendError={errors?.password_confirmation}
              secureTextEntry={true}
            />

            <View>
              <Controller
                control={control}
                name="terms"
                rules={{
                  validate: (value) => value === true || "You must accept the terms",
                }}
                render={({ field: { onChange, value } }) => (
                  <Pressable className="flex-row items-start gap-x-3" onPress={() => onChange(!value)}>
                    <View
                      className={`size-6 rounded-lg border items-center justify-center mt-0.5 shadow-sm transition-all`}
                      style={{
                        backgroundColor: value ? primary.base : "white",
                        borderColor: value ? primary.base : "#cbd5e1",
                      }}
                    >
                      {value && <Ionicons name="checkmark" size={16} color="white" />}
                    </View>
                    <Text className="flex-1 text-slate-600 font-manrope-medium leading-5">
                      I agree to the <Text className="text-slate-900 font-manrope-bold">Terms of Service</Text>, <Text className="text-slate-900 font-manrope-bold">Privacy Policy</Text>, and{" "}
                      <Text className="text-slate-900 font-manrope-bold">Risk Disclosure</Text>.
                    </Text>
                  </Pressable>
                )}
              />
              {formErrors.terms && <Text className="text-red-500 text-sm mt-1 font-manrope-medium">{formErrors.terms.message}</Text>}
            </View>

            <Button onPress={onSubmit} isLoading={isLoading} text="Create Account" className="mt-4" />
          </View>

          <View className="flex-row justify-center items-center my-10 gap-x-4">
            <View className="h-px bg-slate-100 flex-1"></View>
            <Text className="text-slate-400 font-manrope-bold text-xs uppercase tracking-widest">Or Register With</Text>
            <View className="h-px bg-slate-100 flex-1"></View>
          </View>

          <SocialLogin />

          <Pressable onPress={() => router.push("/(auth)/sign-in")} className="mt-8 flex-row justify-center items-center gap-x-1">
            <Text className="text-slate-500 font-manrope-medium text-base">Already have an account?</Text>
            <Text className="font-manrope-bold text-base" style={{ color: primary.base }}>
              Sign In
            </Text>
          </Pressable>
        </View>
      ) : (
        <RegistrationDisabled />
      )}

      <Modal animationType="slide" transparent={true} visible={modalVisible} onRequestClose={() => setModalVisible(false)}>
        <View className="flex-1 justify-end bg-black/60">
          <View className="bg-white rounded-t-[40px] p-6 w-full max-h-[85%] shadow-2xl">
            <View className="flex-row justify-between items-center mb-6 px-1">
              <View>
                <Text className="text-2xl font-manrope-bold text-slate-900">Select Country</Text>
                <Text className="text-slate-500 font-manrope-medium">Choose your primary country</Text>
              </View>
              <Pressable onPress={() => setModalVisible(false)} className="size-10 bg-slate-50 rounded-full items-center justify-center">
                <Ionicons name="close" size={24} color="#64748b" />
              </Pressable>
            </View>

            <View className="h-px bg-slate-100 mb-4" />

            <ScrollView showsVerticalScrollIndicator={false} className="mb-6">
              {countryCodes.map((country) => (
                <Pressable
                  key={country.code}
                  className="flex-row items-center justify-between py-4 px-2 border-b border-slate-50 active:bg-slate-50 rounded-xl"
                  onPress={() => {
                    setSignUpForm((prev) => ({
                      ...prev,
                      country_code: country.code,
                      dial_code: country.dial_code,
                    }));
                    setModalVisible(false);
                  }}
                >
                  <View className="flex-row items-center gap-x-4">
                    <View className="size-10 bg-slate-100 rounded-full items-center justify-center">
                      <Globe size={20} color={primary.base} weight="duotone" />
                    </View>
                    <View>
                      <Text className="text-lg font-manrope-bold text-slate-800">{country.name}</Text>
                      <Text className="text-sm font-manrope-medium text-slate-500">{country.code}</Text>
                    </View>
                  </View>
                  <View className="bg-slate-50 px-3 py-1.5 rounded-lg">
                    <Text className="font-manrope-bold text-slate-700">{country.dial_code}</Text>
                  </View>
                </Pressable>
              ))}
            </ScrollView>
          </View>
        </View>
      </Modal>
    </AuthLayout>
  );
}
