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
}
function ImagePreview({ value }: { value: string }) {
return (
)
}
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 (
)
}
function ImageUploadControls({
id,
uploading,
value,
onChange,
onFileSelect,
}: {
id: string
uploading: boolean
value: string | undefined
onChange: (url: string) => void
onFileSelect: (e: React.ChangeEvent) => Promise
}) {
return (
{
void onFileSelect(e)
}}
disabled={uploading}
/>
)
}
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(null)
const handleFileSelect = async (e: React.ChangeEvent) => {
const file = e.target.files?.[0]
if (!file) {
return
}
setError(null)
setUploading(true)
try {
await processFileUpload(file, onChange, setError)
} catch (e) {
setError(e instanceof Error ? e.message : t('presentation.field.picture.error.uploadFailed'))
} finally {
setUploading(false)
}
}
return { uploading, error, handleFileSelect }
}
export function ImageUploadField({ id, label, value, onChange, helpText }: ImageUploadFieldProps) {
const { uploading, error, handleFileSelect } = useImageUpload(onChange)
const displayLabel = label ?? t('presentation.field.picture')
const displayHelpText = helpText ?? t('presentation.field.picture.help')
return (
{value &&
}
{error &&
{error}
}
{displayHelpText &&
{displayHelpText}
}
)
}