"use client"

import { useRef, useState } from "react"
import { CameraIcon, Loader2Icon, UploadIcon, XCircleIcon } from "lucide-react"

const MAX_FILE_SIZE = 5 * 1024 * 1024

interface ImageCardProps {
  label: string
  hint?: string
  currentUrl: string | null | undefined
  aspectRatio?: "square" | "cover"
  isUploading: boolean
  onUpload: (file: File) => Promise<void>
  onDelete: () => Promise<void>
}

export function ImageCard({
  label,
  hint,
  currentUrl,
  aspectRatio = "cover",
  isUploading,
  onUpload,
  onDelete,
}: ImageCardProps) {
  const inputRef = useRef<HTMLInputElement>(null)
  const [error, setError] = useState<string | null>(null)

  const handleFile = async (file: File) => {
    setError(null)
    if (file.size > MAX_FILE_SIZE) return setError("La taille maximale est de 5 Mo")
    if (!file.type.startsWith("image/")) return setError("Seules les images sont acceptées")
    await onUpload(file)
  }

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (file) handleFile(file)
    e.target.value = ""
  }

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault()
    const file = e.dataTransfer.files?.[0]
    if (file) handleFile(file)
  }

  const containerClass =
    aspectRatio === "square" ? "aspect-square w-36 rounded-xl" : "aspect-[3/1] w-full rounded-xl"

  return (
    <div className="flex flex-col gap-1.5">
      <span className="text-sm font-medium">{label}</span>
      {hint && <span className="text-xs text-muted-foreground -mt-1">{hint}</span>}

      <div
        className={`relative overflow-hidden border-2 border-dashed border-muted-foreground/30 bg-muted/30 transition-colors hover:border-primary/50 ${containerClass}`}
        onDrop={handleDrop}
        onDragOver={(e) => e.preventDefault()}
      >
        {currentUrl ? (
          <>
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img src={currentUrl} alt={label} className="absolute inset-0 h-full w-full object-cover" />
            <div className="absolute inset-0 flex items-center justify-center gap-2 bg-black/40 opacity-0 hover:opacity-100 transition-opacity">
              <button
                type="button"
                disabled={isUploading}
                onClick={() => inputRef.current?.click()}
                className="rounded-full bg-white/90 p-2 text-foreground hover:bg-white disabled:opacity-50"
              >
                <CameraIcon className="size-4" />
              </button>
              <button
                type="button"
                disabled={isUploading}
                onClick={onDelete}
                className="rounded-full bg-white/90 p-2 text-destructive hover:bg-white disabled:opacity-50"
              >
                <XCircleIcon className="size-4" />
              </button>
            </div>
            {isUploading && (
              <div className="absolute inset-0 flex items-center justify-center bg-black/30">
                <Loader2Icon className="size-6 animate-spin text-white" />
              </div>
            )}
          </>
        ) : (
          <button
            type="button"
            disabled={isUploading}
            onClick={() => inputRef.current?.click()}
            className="absolute inset-0 flex flex-col items-center justify-center gap-1.5 text-muted-foreground hover:text-primary transition-colors disabled:opacity-50"
          >
            {isUploading ? <Loader2Icon className="size-5 animate-spin" /> : <UploadIcon className="size-5" />}
            <span className="text-xs">{isUploading ? "Envoi…" : "Cliquez ou glissez"}</span>
          </button>
        )}
      </div>

      {error && <p className="text-xs text-destructive">{error}</p>}
      <input ref={inputRef} type="file" accept="image/*" className="hidden" onChange={handleChange} />
    </div>
  )
}
