import InputGroup from "@/components/auth/InputGroup";
import BackButtonTitle from "@/components/ui/BackButtonTitle";
import Button from "@/components/ui/Button";
import ImageLoader from "@/components/ui/ImageLoader";
import { API_BASE_URL } from "@/configs";
import { storage } from "@/configs/storage";
import { useGetQuery } from "@/hooks/mutate/useGetQuery";
import { useQueryMutation } from "@/hooks/mutate/useQueryMutation";
import { useColor } from "@/hooks/useColor";
import { useAuthStore } from "@/providers/AuthStoreProviders";
import { showToast } from "@/utils/toast";
import * as ImagePicker from "expo-image-picker";
import { CameraIcon, CaretDownIcon, Globe, MagnifyingGlassIcon, XIcon } from "phosphor-react-native";
import { useEffect, useMemo, useState } from "react";
import { Controller, useForm, useWatch } from "react-hook-form";
import { ActivityIndicator, KeyboardAvoidingView, Modal, Platform, Pressable, ScrollView, Text, TextInput, TouchableOpacity, View } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";

interface FormData {
  first_name: string;
  last_name: string;
  username: string;
  address: string;
  city: string;
  zip_code: string;
  country_id: string; // Select value is typically string
}

export default function EditProfileSettins() {
  const getUser = useAuthStore((state) => state.getUser);
  const user = useAuthStore((state) => state.user);
  const setUser = useAuthStore((state) => state.setUser);
  const shades = useColor();
  const [modalVisible, setModalVisible] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");

  const { data: countries } = useGetQuery({
    url: "/settings/countries",
  });

  const {
    control,
    formState: { errors: formErrors },
    handleSubmit,
    reset,
  } = useForm<FormData>({
    defaultValues: {
      first_name: user?.first_name,
    },
  });

  useEffect(() => {
    if (user) {
      reset({
        first_name: user?.first_name,
        last_name: user?.last_name,
        username: user?.username,
        address: user?.address,
        city: user?.city,
        zip_code: user?.zip_code,
        country_id: user?.country_id,
      });
    }
  }, [user, reset]);

  const {
    mutate,
    isLoading,
    backendErrors: errors,
  } = useQueryMutation({
    url: "/client/profile/personal-info",
    isUpdateMethod: true,
  });

  const [isUploadingAvatar, setIsUploadingAvatar] = useState(false);
  const [avatarKey, setAvatarKey] = useState(0);

  const pickImage = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      aspect: [1, 1],
      quality: 0.8,
    });

    if (!result.canceled && result.assets && result.assets.length > 0) {
      setIsUploadingAvatar(true);
      const asset = result.assets[0];
      const formData = new FormData();

      let localUri = asset.uri;
      let filename = asset.fileName || localUri.split("/").pop() || "avatar.jpg";
      let type = asset.mimeType || (filename.toLowerCase().endsWith(".png") ? "image/png" : "image/jpeg");

      formData.append("avatar", {
        uri: Platform.OS === "ios" ? localUri.replace("file://", "") : localUri,
        name: filename,
        type: type,
      } as any);
      formData.append("_method", "PUT");

      try {
        const token = storage.getString(process.env.EXPO_PUBLIC_TOKEN_NAME ?? "token");
        const response = await fetch(`${API_BASE_URL}/client/profile/avatar`, {
          method: "POST",
          headers: {
            Authorization: `Bearer ${token}`,
            "mobile-app-key": process.env.EXPO_PUBLIC_MOBILE_APP_KEY || "",
          },
          body: formData,
        });

        const res = await response.json();

        if (!response.ok) {
          throw new Error(res.message || "Failed to upload image");
        }

        showToast({
          type: "success",
          text: res?.message || "Profile picture updated successfully",
        });
        const updatedUser = res?.data;
        if (updatedUser) {
          setUser({ ...user, ...updatedUser });
        } else {
          await getUser();
        }
        setAvatarKey((k) => k + 1);
      } catch (err: any) {
        showToast({
          type: "error",
          text: err?.message || "Failed to upload image",
        });
      } finally {
        setIsUploadingAvatar(false);
      }
    }
  };

  const filteredCountries = useMemo(() => {
    if (!countries) return [];
    return countries.filter((c: any) => c.name.toLowerCase().includes(searchQuery.toLowerCase()) || c.code.toLowerCase().includes(searchQuery.toLowerCase()));
  }, [countries, searchQuery]);

  const country_id = useWatch({ control, name: "country_id" });

  const selectedCountryName = useMemo(() => {
    if (!countries || !country_id) return "";
    const country = countries.find((c: any) => c.id.toString() === country_id.toString());
    return country?.name || "";
  }, [countries, country_id]);

  const onSubmit = handleSubmit((data) => {
    mutate(data, {
      onSuccess: async (res) => {
        showToast({
          type: "success",
          text: res?.message || "Profile updated successfully",
        });
        getUser();
      },
      onError: async () => {},
    });
  });

  return (
    <SafeAreaView className="bg-white h-full">
      <KeyboardAvoidingView behavior={Platform.OS === "ios" ? "padding" : "height"} style={{ flex: 1 }}>
        <ScrollView keyboardShouldPersistTaps="handled" showsVerticalScrollIndicator={false} className="flex-1 px-4">
          <View className="py-2">
            <BackButtonTitle title="Edit Profile" />
          </View>

          {/* Profile Section */}
          <View className="items-center justify-center my-8">
            <View className="relative">
              <Pressable onPress={pickImage} disabled={isUploadingAvatar}>
                <View className="w-28 h-28 rounded-full bg-slate-100 items-center justify-center border-4 border-slate-50 overflow-hidden shadow-sm">
                  {isUploadingAvatar ? (
                    <ActivityIndicator size="large" color={shades.primary.base} />
                  ) : user?.avatar ? (
                    <ImageLoader key={avatarKey} src={user.avatar} className="w-full h-full" />
                  ) : (
                    <View className="items-center justify-center">
                      <Text className="text-slate-400 text-3xl font-manrope-bold">
                        {user?.first_name?.charAt(0)}
                        {user?.last_name?.charAt(0)}
                      </Text>
                    </View>
                  )}
                </View>
                <View className="absolute bottom-1 right-1 p-2 rounded-full border-2 border-white shadow-md pointer-events-none" style={{ backgroundColor: shades.primary.base }}>
                  <CameraIcon size={20} color="white" weight="bold" />
                </View>
              </Pressable>
            </View>
            <View className="mt-4 items-center">
              <Text className="text-xl font-manrope-bold text-slate-900">{user?.full_name}</Text>
              <Text className="text-slate-500 font-manrope-medium">{user?.email}</Text>
            </View>
          </View>

          <View className="gap-y-5 pb-10">
            <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="User Name" name="username" error={formErrors.username} backendError={errors?.username} />
            <InputGroup control={control} label="Address" name="address" error={formErrors.address} backendError={errors?.address} />

            <View className="flex-row gap-x-4">
              <View className="flex-[2]">
                <InputGroup control={control} label="City" name="city" error={formErrors.city} backendError={errors?.city} />
              </View>
              <View className="flex-1">
                <InputGroup control={control} label="Zip Code" name="zip_code" error={formErrors.zip_code} backendError={errors?.zip_code} />
              </View>
            </View>

            <View>
              <Text className="text-lg font-manrope-semibold pb-2 text-slate-900">Country</Text>
              <Controller
                control={control}
                name="country_id"
                render={({ field: { value } }) => (
                  <Pressable
                    onPress={() => setModalVisible(true)}
                    className={`flex-row items-center justify-between rounded-xl border bg-white px-5 py-4 ${formErrors?.country_id || errors?.country_id ? "border-red-500" : "border-slate-200"}`}
                  >
                    <Text className={`text-lg font-manrope-semibold ${value ? "text-slate-900" : "text-slate-400"}`}>{selectedCountryName || "Select Country"}</Text>
                    <View pointerEvents="none">
                      <CaretDownIcon size={20} color="#64748b" weight="bold" />
                    </View>
                  </Pressable>
                )}
              />
              {(formErrors.country_id || errors?.country_id) && <Text className="text-red-500 text-sm mt-1 font-manrope-medium ml-1">{formErrors.country_id?.message || errors?.country_id}</Text>}
            </View>

            <Button onPress={onSubmit} isLoading={isLoading} text="Save Changes" className="mt-4" />
          </View>
        </ScrollView>
      </KeyboardAvoidingView>

      <Controller
        control={control}
        name="country_id"
        render={({ field: { value, onChange } }) => (
          <Modal animationType="slide" transparent={true} visible={modalVisible} onRequestClose={() => setModalVisible(false)}>
            <View style={{ flex: 1, justifyContent: "flex-end", backgroundColor: "rgba(0,0,0,0.6)" }}>
              <Pressable style={{ flex: 1 }} onPress={() => setModalVisible(false)} />
              <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>
                  <TouchableOpacity
                    activeOpacity={0.7}
                    onPress={() => setModalVisible(false)}
                    hitSlop={{ top: 16, bottom: 16, left: 16, right: 16 }}
                    style={{ width: 40, height: 40, borderRadius: 20, backgroundColor: "#f8fafc", alignItems: "center", justifyContent: "center" }}
                  >
                    <View pointerEvents="none">
                      <XIcon size={24} color="#64748b" weight="bold" />
                    </View>
                  </TouchableOpacity>
                </View>

                <View className="px-1 mb-4">
                  <View className="flex-row items-center bg-slate-50 rounded-2xl px-4 border border-slate-100">
                    <MagnifyingGlassIcon size={20} color="#94a3b8" />
                    <TextInput className="flex-1 h-12 ml-2 font-manrope-semibold text-slate-900" placeholder="Search countries..." value={searchQuery} onChangeText={setSearchQuery} />
                  </View>
                </View>

                <ScrollView showsVerticalScrollIndicator={false} className="mb-6">
                  {filteredCountries.map((country: any) => (
                    <TouchableOpacity
                      key={country.id}
                      activeOpacity={0.7}
                      className={`flex-row items-center justify-between py-4 px-4 border-b border-slate-50 rounded-2xl ${value?.toString() === country.id.toString() ? "bg-slate-50" : ""}`}
                      onPress={() => {
                        onChange(country.id.toString());
                        setModalVisible(false);
                        setSearchQuery("");
                      }}
                    >
                      <View className="flex-row items-center gap-x-4">
                        <View className="size-10 bg-white shadow-sm rounded-full items-center justify-center border border-slate-50">
                          {country.code ? (
                            <ImageLoader src={`https://flagcdn.com/w80/${country.code.toLowerCase()}.png`} className="w-7 h-5 rounded-sm" />
                          ) : (
                            <Globe size={20} color={shades.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>
                      {value?.toString() === country.id.toString() && (
                        <View className="size-6 rounded-full items-center justify-center" style={{ backgroundColor: shades.primary.base }}>
                          <Text className="text-white text-[10px] font-manrope-bold">✓</Text>
                        </View>
                      )}
                    </TouchableOpacity>
                  ))}
                </ScrollView>
              </View>
            </View>
          </Modal>
        )}
      />
    </SafeAreaView>
  );
}
