import { AWS, BASE_URL } from "@/constants/config";
import api from "@/services/axiosClient";
import axios from "axios";

interface PresignedUrlField {
  key: string;
  "x-amz-meta-originalFileName": string;
  bucket: string;
  "X-Amz-Algorithm": string;
  "X-Amz-Credential": string;
  "X-Amz-Date": string;
  Policy: string;
  "X-Amz-Signature": string;
}

export interface PresignedUrlDataItem {
  url: string;
  fields: PresignedUrlField;
  originalFileName: string;
}

export function bytesToMB(bytes: number) {
  if (!bytes) return 0;
  const MB = 1024 * 1024;
  return bytes / MB;
}

interface PresignedUrlResponse {
  message: string;
  data?: PresignedUrlDataItem[];
}

export const handleUpload = async (
  uri: string,
  presignedUrl: PresignedUrlDataItem
) => {
  const formData = new FormData();
  console.log("Presigned URL:", presignedUrl.url);
  if (!presignedUrl) {
    console.log("Presigned URL not found for file", uri);
    throw new Error("Image upload failed.");
  }
  for (const [key, value] of Object.entries(presignedUrl.fields)) {
    formData.append(key, value);
  }

  formData.append("success_action_status", 201);
  const fileType = getFileTypeFromUri(uri);
  const fileName = extractFileName(uri);

  formData.append("file", {
    uri: uri,
    type: fileType,
    name: fileName,
  });

  const instance = axios.create({
    baseURL: presignedUrl.url,
    timeout: 5000,
  });
  try {
    await axios.post(presignedUrl.url, formData, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
      maxRedirects: 0, // optional, to detect redirection errors more explicitly
    });
  } catch (error) {
    console.error("Error uploading image:", error);
    throw new Error("Image upload failed.");
  }
};

export function extractFileName(filePath: string) {
  let parts = filePath.split("/");
  return parts[parts.length - 1];
}

export const getFileTypeFromUri = (uri: string): string => {
  const extension = uri.split(".").pop()?.toLowerCase() || "";

  const mimeTypes: Record<string, string> = {
    jpg: "image/jpeg",
    jpeg: "image/jpeg",
    png: "image/png",
    gif: "image/gif",
    bmp: "image/bmp",
    svg: "image/svg+xml",
    webp: "image/webp",
    txt: "text/plain",
    pdf: "application/pdf",
    doc: "application/msword",
    docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    xls: "application/vnd.ms-excel",
    xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    ppt: "application/vnd.ms-powerpoint",
    pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
    mp4: "video/mp4",
    mp3: "audio/mpeg",
    wav: "audio/wav",
  };

  return mimeTypes[extension] || "application/octet-stream";
};

export const updateUserProfile = ({
  mobile,
  name,
  profile_url,
}: {
  mobile: string;
  name?: string;
  profile_url?: string;
}) => {
  if (!mobile) {
    throw new Error("Mobile number is required");
  }

  const payload: { mobile: string; name?: string; profile_url?: string } = {
    mobile,
  };

  if (typeof name === "string" && name.trim() !== "") {
    payload.name = name;
  }

  if (typeof profile_url === "string" && profile_url.trim() !== "") {
    payload.profile_url = profile_url;
  }

  return api.put(`${BASE_URL}/api/v1/update-user-information`, payload);
};

export const uploadImage = async (uri: string) => {
  const fileName = uri.split("/").pop() || "image.jpg";
  const getPresignedUrl = `${BASE_URL}/api/v1/generate-presigned-urls`;

  const response = await api.post<PresignedUrlResponse>(getPresignedUrl, {
    files: [fileName],
  });

  const uploadData = response?.data?.data?.[0];
  if (!uploadData) throw new Error("Presigned URL not received");

  const { url, fields, originalFileName } = uploadData;
  const presignedUrl: PresignedUrlDataItem = {
    url,
    fields,
    originalFileName,
  };
  await handleUpload(uri, presignedUrl);

  const region = AWS.REGION;
  const bucketName = AWS.BUCKET_NAME;
  const objectKey = presignedUrl.fields.key;

  const uploadedImageUrl = `https://s3.${region}.amazonaws.com/${bucketName}/${encodeURIComponent(
    objectKey
  )}`;

  return uploadedImageUrl;
};
