import { Platform } from "react-native";
import { isNative } from "../firebase";

export async function uploadProfileImage(
  uid: string,
  localUri: string
): Promise<string> {
  if (!uid || !localUri) {
    throw new Error("Missing uid or image uri");
  }

  const fileName = `profile_${uid}_${Date.now()}.jpg`;

  if (isNative) {
    let storageModule: any;
    try {
      console.log(
        "[profileImageService] Using native Firebase Storage upload",
        {
          uid,
          localUri,
        }
      );
      storageModule = require("@react-native-firebase/storage").default;
    } catch (e) {
      console.error(
        "[profileImageService] @react-native-firebase/storage not available",
        e
      );
      throw new Error("Storage module not installed");
    }

    const path = `profile-images/${uid}/${fileName}`;
    console.log("[profileImageService] Upload path (native):", path);
    const ref = storageModule().ref(path);

    try {
      console.log(
        "[profileImageService] Calling putFile with localUri",
        localUri
      );
      const result = await ref.putFile(localUri);
      console.log(
        "[profileImageService] putFile result:",
        result?.state || result
      );
    } catch (error) {
      console.error("[profileImageService] Error during putFile", error);
      throw error;
    }

    try {
      console.log("[profileImageService] Fetching download URL for path", path);
      const downloadUrl = await ref.getDownloadURL();
      console.log("[profileImageService] getDownloadURL success", downloadUrl);
      return downloadUrl;
    } catch (error) {
      console.error("[profileImageService] Error during getDownloadURL", error);
      throw error;
    }
  }

  // Web / other platforms using Firebase JS SDK storage
  console.log("[profileImageService] Using web Firebase Storage upload", {
    uid,
    localUri,
  });
  const { getStorage, ref, uploadBytes, getDownloadURL } = await import(
    "firebase/storage"
  );

  const storage = getStorage();
  const response = await fetch(localUri);
  const blob = await response.blob();
  const storageRefPath = `profile-images/${uid}/${fileName}`;
  console.log("[profileImageService] Upload path (web):", storageRefPath);
  const storageRef = ref(storage, storageRefPath);
  try {
    await uploadBytes(storageRef, blob);
  } catch (error) {
    console.error("[profileImageService] Error during uploadBytes", error);
    throw error;
  }
  try {
    const downloadUrl = await getDownloadURL(storageRef);
    console.log(
      "[profileImageService] Web getDownloadURL success",
      downloadUrl
    );
    return downloadUrl;
  } catch (error) {
    console.error("[profileImageService] Error during getDownloadURL", error);
    throw error;
  }
}
