"use client";

import { CldUploadWidget } from "next-cloudinary";
import { ImagePlus, X } from "lucide-react";
import Image from "next/image";

interface ImageUploadProps {
  value: string;
  onChange: (value: string) => void;
  folder?: string;
  label?: string;
  name?: string; // Add name prop for hidden input
}

export default function ImageUpload({ value, onChange, folder = "kozmosbeach", label = "Görsel Yükle", name }: ImageUploadProps) {
  const onUpload = (result: any) => {
    onChange(result.info.secure_url);
  };

  return (
    <div className="w-full">
      {name && <input type="hidden" name={name} value={value} />}
      {value ? (
        <div className="relative w-full aspect-video rounded-xl overflow-hidden border border-gray-200">
          <Image
            fill
            sizes="(max-width: 768px) 100vw, 33vw"
            className="object-cover"
            alt="Upload"
            src={value}
          />
          <div className="absolute top-2 right-2 flex gap-2">
            <button
              type="button"
              onClick={() => onChange("")}
              className="p-1.5 bg-red-500 text-white rounded-full hover:bg-red-600 transition shadow-sm"
            >
              <X size={16} />
            </button>
          </div>
        </div>
      ) : (
        <CldUploadWidget
          signatureEndpoint="/api/cloudinary"
          options={{
            folder: folder,
            maxFiles: 1,
            sources: ["local", "url", "camera"],
          }}
          onSuccess={onUpload}
        >
          {({ open }) => {
            const onClick = (e: React.MouseEvent) => {
              e.preventDefault();
              open();
            };

            return (
              <button
                type="button"
                onClick={onClick}
                className="w-full h-32 border-2 border-dashed border-gray-300 rounded-xl flex flex-col items-center justify-center gap-2 text-gray-500 hover:border-turquoise hover:text-turquoise transition-colors bg-gray-50 hover:bg-turquoise/5"
              >
                <ImagePlus size={24} />
                <span className="text-sm font-medium">{label}</span>
              </button>
            );
          }}
        </CldUploadWidget>
      )}
    </div>
  );
}
