"use client";
import { CldImage, CldUploadWidget } from "next-cloudinary";
import { useState } from "react";

// By default, the CldImage component applies auto-format and auto-quality to all delivery URLs for optimized delivery.
export function CloudinaryImage() {
  return (
    <CldImage
      src="cld-sample-5" // Use this sample image or upload your own via the Media Explorer
      width="500" // Transform the image: auto-crop to square aspect_ratio
      height="500"
      crop={{
        type: "auto",
        source: true,
      }}
      alt={"Cloudinary Image Example"}
    />
  );
}

export function CloudinaryUpload() {
  const [imageUrl, setImageUrl] = useState<string | null>(null);

  const handleUpload = (result: any) => {
    setImageUrl(result?.info?.secure_url);
  };
  return (
    <div className="cursor-pointer flex flex-col items-center justify-center bg-gray-50 p-6">
      <CldUploadWidget
        uploadPreset="your_unsigned_preset" // Replace with your unsigned preset
        onSuccess={handleUpload}
        options={{ sources: ["local", "url", "camera"], multiple: false }}
      >
        {({ open,  cloudinary, results}) => {
          console.log("Cloudinary SDK:", cloudinary, results);
          return (
            <button
              className="bg-primary text-white px-4 py-2 rounded hover:bg-slate-950 transition"
              onClick={() => open()}
              type="button"
            >
              Upload Image
            </button>
          )
        }}
      </CldUploadWidget>

      {imageUrl && (
        <div className="mt-6">
          <img
            src={imageUrl}
            alt="Uploaded"
            className="w-64 h-auto rounded shadow"
          />
          <p className="mt-2 text-sm text-gray-700">{imageUrl}</p>
        </div>
      )}
    </div>
  );
}
