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

interface ImageUploadFieldProps {
  id: string
  label?: string | undefined
  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(t('presentation.field.picture.error.imagesOnly'))
      }
    } catch (e) {
      setError(e instanceof Error ? e.message : t('presentation.field.picture.error.uploadFailed'))
    } finally {
      setUploading(false)
    }
  }

  const displayLabel = label ?? t('presentation.field.picture')
  const displayHelpText = helpText ?? t('presentation.field.picture.help')

  return (
    <div className="space-y-2">
      <label htmlFor={id} className="block text-sm font-medium text-neon-cyan">
        {displayLabel}
      </label>
      {value && (
        <div className="relative w-32 h-32 rounded-lg overflow-hidden border border-neon-cyan/20">
          <Image
            src={value}
            alt={t('presentation.field.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 ? t('presentation.field.picture.uploading') : value ? t('presentation.field.picture.change') : t('presentation.field.picture.upload')}
        </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"
          >
            {t('presentation.field.picture.remove')}
          </button>
        )}
      </div>
      {error && (
        <p className="text-sm text-red-400">{error}</p>
      )}
      {displayHelpText && (
        <p className="text-sm text-cyber-accent">{displayHelpText}</p>
      )}
    </div>
  )
}
