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

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

function ImagePreview({ value }: { value: string }) {
  return (
    <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>
  )
}

function UploadButtonLabel({ uploading, value }: { uploading: boolean; value: string | undefined }) {
  if (uploading) {
    return <>{t('presentation.field.picture.uploading')}</>
  }
  return <>{value ? t('presentation.field.picture.change') : t('presentation.field.picture.upload')}</>
}

function RemoveButton({ value, onChange }: { value: string | undefined; onChange: (url: string) => void }) {
  if (!value) {
    return null
  }
  return (
    <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>
  )
}

function ImageUploadControls({
  id,
  uploading,
  value,
  onChange,
  onFileSelect,
}: {
  id: string
  uploading: boolean
  value: string | undefined
  onChange: (url: string) => void
  onFileSelect: (e: React.ChangeEvent<HTMLInputElement>) => Promise<void>
}) {
  return (
    <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"
      >
        <UploadButtonLabel uploading={uploading} value={value} />
      </label>
      <input
        id={id}
        type="file"
        accept="image/png,image/jpeg,image/jpg,image/webp"
        className="hidden"
        onChange={(e) => {
          void onFileSelect(e)
        }}
        disabled={uploading}
      />
      <RemoveButton value={value} onChange={onChange} />
    </div>
  )
}

async function processFileUpload(file: File, onChange: (url: string) => void, setError: (error: string | null) => void) {
  const media = await uploadNip95Media(file)
  if (media.type === 'image') {
    onChange(media.url)
  } else {
    setError(t('presentation.field.picture.error.imagesOnly'))
  }
}

function useImageUpload(onChange: (url: string) => void) {
  const [uploading, setUploading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [showUnlockModal, setShowUnlockModal] = useState(false)
  const [pendingFile, setPendingFile] = useState<File | null>(null)

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

    setError(null)
    setUploading(true)

    try {
      await processFileUpload(file, onChange, setError)
    } catch (e) {
      const error = e instanceof Error ? e : new Error(String(e))
      // Check if unlock is required
      if (error.message === 'UNLOCK_REQUIRED' || (error as any).unlockRequired) {
        setPendingFile(file)
        setShowUnlockModal(true)
        setError(null) // Don't show error, show unlock modal instead
      } else {
        setError(error.message || t('presentation.field.picture.error.uploadFailed'))
      }
    } finally {
      setUploading(false)
    }
  }

  const handleUnlockSuccess = async () => {
    setShowUnlockModal(false)
    if (pendingFile) {
      // Retry upload after unlock
      setUploading(true)
      setError(null)
      try {
        await processFileUpload(pendingFile, onChange, setError)
        setPendingFile(null)
      } catch (e) {
        setError(e instanceof Error ? e.message : t('presentation.field.picture.error.uploadFailed'))
      } finally {
        setUploading(false)
      }
    }
  }

  return { uploading, error, handleFileSelect, showUnlockModal, setShowUnlockModal, handleUnlockSuccess }
}

export function ImageUploadField({ id, label, value, onChange, helpText }: ImageUploadFieldProps) {
  const { uploading, error, handleFileSelect, showUnlockModal, setShowUnlockModal, handleUnlockSuccess } = useImageUpload(onChange)
  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 && <ImagePreview value={value} />}
        <ImageUploadControls
          id={id}
          uploading={uploading}
          value={value}
          onChange={onChange}
          onFileSelect={handleFileSelect}
        />
        {error && <p className="text-sm text-red-400">{error}</p>}
        {displayHelpText && <p className="text-sm text-cyber-accent">{displayHelpText}</p>}
      </div>
      {showUnlockModal && (
        <UnlockAccountModal
          onSuccess={handleUnlockSuccess}
          onClose={() => {
            setShowUnlockModal(false)
          }}
        />
      )}
    </>
  )
}
