import { useState } from "react";
import URLS from "@/redux/api/constants";
import { getSession } from "next-auth/react";

const UPLOAD_BASE = process.env.NEXT_PUBLIC_S3_UPLOAD_BASE!;
const PUBLIC_BASE = process.env.NEXT_PUBLIC_S3_PUBLIC_BASE!;

export const useImageUploader = () => {
  const [isLoading, setIsLoading] = useState(false);
  const [progress, setProgress] = useState(0);

  const uploadFileToS3 = async (
    file: File,
    schema: string,
    onProgress?: (percent: number) => void
  ): Promise<string> => {
    try {
      setIsLoading(true);
      setProgress(0);

      const headers = new Headers();
      const session = await getSession();
      if (session)
        headers.set("Authorization", `Bearer ${session.accessToken}`);
      headers.set("x-client-type", "panel");
      headers.set("Content-Type", "application/json");

      // Step 1: Get pre-signed URL
      const uploadResponse = await fetch(
        `${URLS.HOST_URL}/api/v1/upload/users`,
        {
          method: "POST",
          headers,
          body: JSON.stringify({
            schema,
            fileName: file.name,
            contentType: file.type,
          }),
        }
      ).then((res) => res.json());

      // Step 2: Upload with progress using XMLHttpRequest
      await new Promise<void>((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open("PUT", uploadResponse.url, true);
        xhr.setRequestHeader("Content-Type", file.type);

        xhr.upload.onprogress = (event) => {
          if (event.lengthComputable) {
            const percent = Math.round((event.loaded / event.total) * 100);
            setProgress(percent);
            if (onProgress) onProgress(percent);
          }
        };

        xhr.onload = () => {
          if (xhr.status === 200) resolve();
          else reject(new Error("Failed to upload to S3"));
        };

        xhr.onerror = () =>
          reject(new Error("Upload failed due to network error"));
        xhr.send(file);
      });

      const uploadedUrl = uploadResponse.url.split("?")[0];
      const publicUrl = uploadedUrl.replace(UPLOAD_BASE, PUBLIC_BASE);

      return publicUrl;
    } catch (error) {
      console.error("Error uploading file:", error);
      throw new Error("Failed to upload file");
    } finally {
      setIsLoading(false);
    }
  };

  return { uploadFileToS3, isLoading, progress };
};
