import { useEffect, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import { X } from 'lucide-react'
import styles from './CategoryModal.module.css'

interface StoreSpecialModalProps {
  open: boolean
  onClose: () => void
  onSubmit: (title: string) => void
  initialTitle?: string
  title?: string
  submitLabel?: string
  fieldLabel?: string
  isSubmitting?: boolean
}

const ANIMATION_MS = 220

export function StoreSpecialModal({
  open,
  onClose,
  onSubmit,
  initialTitle = '',
  title = 'Add Special Category',
  submitLabel = 'Create',
  fieldLabel = 'Category title',
  isSubmitting = false,
}: StoreSpecialModalProps) {
  const formRef = useRef<HTMLFormElement>(null)
  const [mounted, setMounted] = useState(open)
  const [closing, setClosing] = useState(false)
  const [categoryTitle, setCategoryTitle] = useState(initialTitle)

  useEffect(() => {
    if (open) {
      setMounted(true)
      setClosing(false)
      setCategoryTitle(initialTitle)
    } else if (mounted) {
      setClosing(true)
      const timer = setTimeout(() => {
        setMounted(false)
        setClosing(false)
      }, ANIMATION_MS)
      return () => clearTimeout(timer)
    }
  }, [open, initialTitle, 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()
    const trimmed = categoryTitle.trim()
    if (!trimmed) return
    onSubmit(trimmed)
  }

  return createPortal(
    <div
      className={`${styles.overlay} ${closing ? styles.overlayOut : styles.overlayIn}`}
      onClick={(e) => e.target === e.currentTarget && onClose()}
      role="presentation"
    >
      <div
        className={`${styles.modal} ${closing ? styles.modalOut : styles.modalIn}`}
        role="dialog"
        aria-modal="true"
        aria-labelledby="special-modal-title"
      >
        <div className={styles.header}>
          <h2 id="special-modal-title" className={styles.title}>
            {title}
          </h2>
          <button type="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 htmlFor="special-category-title">{fieldLabel}</label>
            <input
              id="special-category-title"
              value={categoryTitle}
              onChange={(e) => setCategoryTitle(e.target.value)}
              placeholder="e.g. Special Sale, Our Best Sellers"
              autoFocus
              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 || !categoryTitle.trim()}
            >
              {isSubmitting ? 'Saving...' : submitLabel}
            </button>
          </div>
        </form>
      </div>
    </div>
  ,
  document.body,
  )
}
