'use client'

import { useState, useRef } from 'react'
import { Upload, X, Loader2 } from 'lucide-react'

type Props = {
  currentImage?: string | null
  onUpload: (url: string) => void
  folder?: string
  label?: string
}

export function ImageUpload({ currentImage, onUpload, folder = 'craftsmen', label = 'الصورة' }: Props) {
  const inputRef = useRef<HTMLInputElement>(null)
  const [uploading, setUploading] = useState(false)
  const [preview, setPreview] = useState(currentImage || '')

  const handleFile = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file) return

    if (!file.type.startsWith('image/')) return alert('يرجى اختيار صورة')
    if (file.size > 2 * 1024 * 1024) return alert('حجم الصورة يجب أن لا يتجاوز 2MB')

    setUploading(true)
    try {
      const reader = new FileReader()
      reader.onload = async () => {
        const base64 = reader.result as string
        const res = await fetch('/api/upload', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ image: base64, folder }),
        })
        if (!res.ok) { alert('فشل رفع الصورة'); return }
        const data = await res.json()
        setPreview(data.url)
        onUpload(data.url)
      }
      reader.readAsDataURL(file)
    } catch {
      alert('حدث خطأ')
    } finally {
      setUploading(false)
    }
  }

  const remove = () => {
    setPreview('')
    onUpload('')
  }

  return (
    <div className="space-y-2">
      <label className="block text-sm font-medium text-gray-700">{label}</label>
      {preview ? (
        <div className="relative inline-block">
          <img src={preview} alt="" className="w-32 h-32 object-cover rounded-xl border border-gray-200" />
          <button type="button" onClick={remove} className="absolute -top-2 -left-2 w-6 h-6 bg-red-500 text-white rounded-full flex items-center justify-center hover:bg-red-600 transition-colors">
            <X className="w-3.5 h-3.5" />
          </button>
        </div>
      ) : (
        <button
          type="button"
          onClick={() => inputRef.current?.click()}
          disabled={uploading}
          className="w-32 h-32 border-2 border-dashed border-gray-300 rounded-xl flex flex-col items-center justify-center gap-2 text-gray-400 hover:border-blue-400 hover:text-blue-500 transition-colors disabled:opacity-50"
        >
          {uploading ? <Loader2 className="w-6 h-6 animate-spin" /> : <><Upload className="w-6 h-6" /><span className="text-xs">اختر صورة</span></>}
        </button>
      )}
      <input ref={inputRef} type="file" accept="image/*" onChange={handleFile} className="hidden" />
    </div>
  )
}
