import { useState } from 'react'
import { uploadNip95Media } from '@/lib/nip95'
import Image from 'next/image'

interface ImageUploadFieldProps {
  id: string
  label: string
  value?: string | undefined
  onChange: (url: string) => void
  helpText?: string | undefined
}

export function ImageUploadField({ id, label, value, onChange, helpText }: ImageUploadFieldProps) {
  const [uploading, setUploading] = useState(false)
  const [error, setError] = useState<string | null>(null)

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

    setError(null)
    setUploading(true)

    try {
      const media = await uploadNip95Media(file)
      if (media.type === 'image') {
        onChange(media.url)
      } else {
        setError('Seules les images sont autorisées')
      }
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Erreur lors de l\'upload')
    } finally {
      setUploading(false)
    }
  }

  return (
    <div className="space-y-2">
      <label htmlFor={id} className="block text-sm font-medium text-neon-cyan">
        {label}
      </label>
      {value && (
        <div className="relative w-32 h-32 rounded-lg overflow-hidden border border-neon-cyan/20">
          <Image
            src={value}
            alt="Profile picture"
            fill
            className="object-cover"
          />
        </div>
      )}
      <div className="flex items-center gap-2">
        <label
          htmlFor={id}
          className="px-4 py-2 bg-neon-cyan/20 hover:bg-neon-cyan/30 text-neon-cyan rounded-lg text-sm font-medium transition-all border border-neon-cyan/50 hover:shadow-glow-cyan cursor-pointer"
        >
          {uploading ? 'Upload en cours...' : value ? 'Changer l\'image' : 'Télécharger une image'}
        </label>
        <input
          id={id}
          type="file"
          accept="image/png,image/jpeg,image/jpg,image/webp"
          className="hidden"
          onChange={handleFileSelect}
          disabled={uploading}
        />
        {value && (
          <button
            type="button"
            onClick={() => onChange('')}
            className="px-4 py-2 bg-red-500/20 hover:bg-red-500/30 text-red-400 rounded-lg text-sm font-medium transition-all border border-red-500/50"
          >
            Supprimer
          </button>
        )}
      </div>
      {error && (
        <p className="text-sm text-red-400">{error}</p>
      )}
      {helpText && (
        <p className="text-sm text-cyber-accent">{helpText}</p>
      )}
    </div>
  )
}

