import { useRef } from 'react'
import { ImagePlus, X } from 'lucide-react'
import { useT } from '../i18n/useT'
import styles from './ImageUploader.module.css'

interface ImageUploaderProps {
  images: string[]
  onChange: (images: string[]) => void
}

export function ImageUploader({ images, onChange }: ImageUploaderProps) {
  const t = useT()
  const inputRef = useRef<HTMLInputElement>(null)

  function handleFiles(e: React.ChangeEvent<HTMLInputElement>) {
    const files = Array.from(e.target.files ?? [])
    if (!files.length) return

    const readers = files.map(
      (file) =>
        new Promise<string>((resolve) => {
          const reader = new FileReader()
          reader.onload = () => resolve(reader.result as string)
          reader.readAsDataURL(file)
        }),
    )

    Promise.all(readers).then((results) => {
      onChange([...images, ...results])
    })

    e.target.value = ''
  }

  function removeImage(index: number) {
    onChange(images.filter((_, i) => i !== index))
  }

  return (
    <div className={styles.wrapper}>
      <div className={styles.grid}>
        {images.map((src, index) => (
          <div key={`${src.slice(0, 32)}-${index}`} className={styles.item}>
            <img src={src} alt={t('products.form.images')} />
            <button
              type="button"
              className={styles.removeBtn}
              onClick={() => removeImage(index)}
              aria-label={t('products.form.imagesRemove', { index: index + 1 })}
            >
              <X size={14} />
            </button>
          </div>
        ))}

        <button
          type="button"
          className={styles.addBtn}
          onClick={() => inputRef.current?.click()}
        >
          <ImagePlus size={24} />
          <span>{t('products.form.imagesAdd')}</span>
        </button>
      </div>

      <input
        ref={inputRef}
        type="file"
        accept="image/*"
        multiple
        hidden
        onChange={handleFiles}
      />
      <p className={styles.hint}>{t('products.form.imagesHint')}</p>
    </div>
  )
}
