import { useEffect, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import { X } from 'lucide-react'
import { useLocale } from '@meshkee/dashboard-ui'
import { useT } from '../i18n/useT'
import { ImageCropper } from './ImageCropper'
import type { Brand, BrandFormData } from '../types/brand'
import styles from './BrandModal.module.css'

interface BrandModalProps {
  open: boolean
  onClose: () => void
  onSubmit: (data: BrandFormData) => void
  editingBrand?: Brand | null
  title?: string
  isSubmitting?: boolean
}

const ANIMATION_MS = 220

export function BrandModal({
  open,
  onClose,
  onSubmit,
  editingBrand = null,
  title,
  isSubmitting = false,
}: BrandModalProps) {
  const t = useT()
  const { locale } = useLocale()
  const isFa = locale === 'fa'
  const formRef = useRef<HTMLFormElement>(null)
  const [mounted, setMounted] = useState(open)
  const [closing, setClosing] = useState(false)
  const [nameEn, setNameEn] = useState('')
  const [nameFa, setNameFa] = useState('')
  const [about, setAbout] = useState('')
  const [image, setImage] = useState<string | null>(null)
  const [imageMediaId, setImageMediaId] = useState<string | null>(null)

  useEffect(() => {
    if (open) {
      setMounted(true)
      setClosing(false)
      setNameEn(editingBrand?.nameEn ?? '')
      setNameFa(editingBrand?.nameFa ?? '')
      setAbout(editingBrand?.about ?? '')
      setImage(editingBrand?.imageUrl ?? null)
      setImageMediaId(editingBrand?.imageMediaId ?? null)
    } else if (mounted) {
      setClosing(true)
      const timer = setTimeout(() => {
        setMounted(false)
        setClosing(false)
      }, ANIMATION_MS)
      return () => clearTimeout(timer)
    }
  }, [open, editingBrand, mounted])

  useEffect(() => {
    if (!mounted || closing) return
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose()
    }
    document.addEventListener('keydown', onKey)
    return () => document.removeEventListener('keydown', onKey)
  }, [mounted, closing, onClose])

  if (!mounted) return null

  function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault()
    onSubmit({
      nameFa: nameFa.trim(),
      nameEn: nameEn.trim(),
      about: about.trim(),
      image,
      imageMediaId,
    })
  }

  return createPortal(
    <div
      className={`${styles.overlay} ${closing ? styles.overlayOut : styles.overlayIn}`}
      onClick={onClose}
    >
      <div
        className={`${styles.modal} ${closing ? styles.modalOut : styles.modalIn}`}
        onClick={(e) => e.stopPropagation()}
        role="dialog"
        aria-modal="true"
        aria-labelledby="brand-modal-title"
        lang={isFa ? 'fa' : 'en'}
        dir={isFa ? 'rtl' : 'ltr'}
      >
        <div className={styles.header}>
          <h3 id="brand-modal-title" className={styles.title}>
            {title ?? t('brands.add')}
          </h3>
          <button
            type="button"
            className={styles.closeBtn}
            onClick={onClose}
            aria-label={t('common.close')}
          >
            <X size={20} />
          </button>
        </div>

        <form ref={formRef} className={styles.form} onSubmit={handleSubmit}>
          <div className={styles.field}>
            <label>{t('brands.modal.logo')}</label>
            <ImageCropper
              value={image}
              onChange={setImage}
              outputFormat="png"
              accept="image/png"
              uploadLabel={t('brands.modal.uploadLogo')}
              hint={t('brands.modal.logoHint')}
              changeLabel={t('brands.modal.changeLogo')}
            />
          </div>

          <div className={styles.field}>
            <label htmlFor="nameFa">{t('brands.modal.nameFa')}</label>
            <input
              id="nameFa"
              name="nameFa"
              type="text"
              dir="rtl"
              className="faText"
              placeholder={t('brands.modal.nameFaPlaceholder')}
              value={nameFa}
              onChange={(e) => setNameFa(e.target.value)}
              disabled={isSubmitting}
            />
          </div>

          <div className={styles.field}>
            <label htmlFor="nameEn">{t('brands.modal.nameEn')}</label>
            <input
              id="nameEn"
              name="nameEn"
              type="text"
              dir={isFa ? 'rtl' : 'ltr'}
              placeholder={t('brands.modal.nameEnPlaceholder')}
              value={nameEn}
              onChange={(e) => setNameEn(e.target.value)}
              required
              disabled={isSubmitting}
            />
          </div>

          <div className={styles.field}>
            <label htmlFor="about">{t('brands.modal.about')}</label>
            <textarea
              id="about"
              name="about"
              rows={3}
              dir={isFa ? 'rtl' : 'ltr'}
              placeholder={t('brands.modal.aboutPlaceholder')}
              value={about}
              onChange={(e) => setAbout(e.target.value)}
              disabled={isSubmitting}
            />
          </div>

          <div className={styles.actions}>
            <button
              type="button"
              className={styles.cancelBtn}
              onClick={onClose}
              disabled={isSubmitting}
            >
              {t('brands.modal.cancel')}
            </button>
            <button type="submit" className={styles.submitBtn} disabled={isSubmitting}>
              {isSubmitting ? t('brands.modal.saving') : t('brands.modal.save')}
            </button>
          </div>
        </form>
      </div>
    </div>
  ,
  document.body,
  )
}
