import { useState } from "react";
import { adminFetch } from "@/lib/adminFetch";
import { useAdminToast } from "./useAdminToast";

interface UseImageUploadOptions {
  onUploadSuccess?: (url: string) => void;
  onDeleteSuccess?: () => void;
  maxSize?: number; // in MB
}

export function useImageUpload({
  onUploadSuccess,
  onDeleteSuccess,
  maxSize = 5,
}: UseImageUploadOptions = {}) {
  const [isUploading, setIsUploading] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);
  const { showSuccess, showError } = useAdminToast();

  const uploadImage = async (file: File | File[]): Promise<string | null> => {
    const selectedFile = Array.isArray(file) ? file[0] : file;
    if (!selectedFile) return null;

    // Validate file size
    if (selectedFile.size > maxSize * 1024 * 1024) {
      showError(`File size must be less than ${maxSize}MB`);
      return null;
    }

    setIsUploading(true);
    try {
      const formData = new FormData();
      formData.append("file", selectedFile);
      const res = await adminFetch("/api/upload", {
        method: "POST",
        body: formData,
      });

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

      const { url } = await res.json();
      showSuccess("Image uploaded successfully!");
      onUploadSuccess?.(url);
      return url;
    } catch (error) {
      showError("Failed to upload image. Please try again.");
      return null;
    } finally {
      setIsUploading(false);
    }
  };

  const deleteImage = async (imageUrl: string): Promise<boolean> => {
    if (!imageUrl) return false;

    setIsDeleting(true);
    try {
      const filename = imageUrl.split("/").pop();
      if (!filename) {
        throw new Error("Invalid image URL");
      }

      const res = await adminFetch(`/api/upload?filename=${filename}`, {
        method: "DELETE",
      });

      if (!res.ok) {
        throw new Error("Failed to delete image");
      }

      showSuccess("Image deleted successfully!");
      onDeleteSuccess?.();
      return true;
    } catch (error) {
      showError("Failed to delete image. Please try again.");
      return false;
    } finally {
      setIsDeleting(false);
    }
  };

  return {
    uploadImage,
    deleteImage,
    isUploading,
    isDeleting,
  };
}


