import { useEffect, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import { X } from 'lucide-react'
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 = 'Add Brand',
  isSubmitting = false,
}: BrandModalProps) {
  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"
      >
        <div className={styles.header}>
          <h3 id="brand-modal-title" className={styles.title}>
            {title}
          </h3>
          <button className={styles.closeBtn} onClick={onClose} aria-label="Close">
            <X size={20} />
          </button>
        </div>

        <form ref={formRef} className={styles.form} onSubmit={handleSubmit}>
          <div className={styles.field}>
            <label>Brand logo</label>
            <ImageCropper
              value={image}
              onChange={setImage}
              outputFormat="png"
              accept="image/png"
              uploadLabel="Upload brand logo"
              hint="PNG only — transparent background recommended"
              changeLabel="Change logo"
            />
          </div>

          <div className={styles.field}>
            <label htmlFor="nameFa">Name (FA)</label>
            <input
              id="nameFa"
              name="nameFa"
              type="text"
              dir="rtl"
              className="faText"
              placeholder="نام برند"
              value={nameFa}
              onChange={(e) => setNameFa(e.target.value)}
              disabled={isSubmitting}
            />
          </div>

          <div className={styles.field}>
            <label htmlFor="nameEn">Name (EN)</label>
            <input
              id="nameEn"
              name="nameEn"
              type="text"
              dir="ltr"
              placeholder="Brand name"
              value={nameEn}
              onChange={(e) => setNameEn(e.target.value)}
              required
              disabled={isSubmitting}
            />
          </div>

          <div className={styles.field}>
            <label htmlFor="about">About</label>
            <textarea
              id="about"
              name="about"
              rows={3}
              placeholder="Short description of this brand"
              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}
            >
              Cancel
            </button>
            <button type="submit" className={styles.submitBtn} disabled={isSubmitting}>
              {isSubmitting ? 'Saving...' : 'Save Brand'}
            </button>
          </div>
        </form>
      </div>
    </div>
  ,
  document.body,
  )
}
