import { useAuthStore } from "@/providers/AuthStoreProviders";
import { Pressable, View } from "react-native";
import ImageLoader from "../ui/ImageLoader";
import userAvatar from "@/assets/images/user.png";
import { PencilLineIcon } from "phosphor-react-native";
import { useColor } from "@/hooks/useColor";
import * as ImagePicker from "expo-image-picker";
import { showToast } from "@/utils/toast";
import { API_BASE_URL, TOKEN_NAME } from "@/configs";
import { storage } from "@/configs/storage";
import { useState } from "react";

export default function ChangeProfileImage() {
  const user = useAuthStore((state) => state.user);
  const getUser = useAuthStore((state) => state.getUser);
  const setUser = useAuthStore((state) => state.setUser);
  const { primary } = useColor();
  const [isLoading, setIsLoading] = useState(false);
  const [avatarKey, setAvatarKey] = useState(0);

  const uploadAvatar = async (image: ImagePicker.ImagePickerAsset) => {
    setIsLoading(true);
    try {
      const token = storage.getString(TOKEN_NAME);

      const formData = new FormData();
      formData.append("_method", "PUT");
      formData.append("avatar", {
        uri: image.uri,
        name: image.fileName || `avatar_${Date.now()}.jpg`,
        type: image.mimeType || "image/jpeg",
      } as any);

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

      const data = await response.json();
      console.log("📸 avatar upload response:", JSON.stringify(data));

      if (response.ok && data.status !== false) {
        const updatedUser = data?.data;
        if (updatedUser) {
          setUser({ ...user, ...updatedUser });
        } else {
          await getUser();
        }
        setAvatarKey((k) => k + 1);
        showToast({ type: "success", text: "Avatar updated successfully" });
      } else {
        showToast({
          type: "error",
          text: data?.message || "Failed to update avatar",
        });
      }
    } catch (error: any) {
      console.log("❌ Upload error:", error);
      showToast({
        type: "error",
        text: error?.message || "Failed to update avatar",
      });
    } finally {
      setIsLoading(false);
    }
  };

  const pickImage = async () => {
    try {
      const result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ["images"],
        allowsEditing: true,
        aspect: [4, 3],
        quality: 1,
        allowsMultipleSelection: false,
      });

      if (!result.canceled) {
        const image = result.assets[0];
        await uploadAvatar(image);
      }
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <View>
      <ImageLoader
        key={avatarKey}
        src={user?.avatar ?? userAvatar}
        alt=""
        className="size-20 rounded-full object-cover"
      />
      <Pressable
        className="absolute bottom-0 end-0 rounded-full p-2"
        style={{
          backgroundColor: primary.base,
        }}
        onPress={pickImage}
        disabled={isLoading}
      >
        <PencilLineIcon size={16} color="white" />
      </Pressable>
    </View>
  );
}
