import { useEffect, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import { X } from 'lucide-react'
import type { Category, CategoryFormData } from '../types/category'
import { flattenCategories } from '../utils/categories'
import { SearchableSelect } from './SearchableSelect'
import styles from './CategoryModal.module.css'

interface CategoryModalProps {
  open: boolean
  onClose: () => void
  onSubmit: (data: CategoryFormData) => void
  categories: Category[]
  defaultParentId?: string
  editingCategory?: Category | null
  title?: string
  isSubmitting?: boolean
}

const ANIMATION_MS = 220

export function CategoryModal({
  open,
  onClose,
  onSubmit,
  categories,
  defaultParentId = '',
  editingCategory = null,
  title = 'Add Category',
  isSubmitting = false,
}: CategoryModalProps) {
  const formRef = useRef<HTMLFormElement>(null)
  const [mounted, setMounted] = useState(open)
  const [closing, setClosing] = useState(false)
  const [parentId, setParentId] = useState(defaultParentId)
  const [nameEn, setNameEn] = useState('')
  const [nameFa, setNameFa] = useState('')
  const [description, setDescription] = useState('')

  useEffect(() => {
    if (open) {
      setMounted(true)
      setClosing(false)
      setParentId(editingCategory?.parentId ?? defaultParentId)
      setNameEn(editingCategory?.nameEn ?? '')
      setNameFa(editingCategory?.nameFa ?? '')
      setDescription(editingCategory?.description ?? '')
    } else if (mounted) {
      setClosing(true)
      const timer = setTimeout(() => {
        setMounted(false)
        setClosing(false)
      }, ANIMATION_MS)
      return () => clearTimeout(timer)
    }
  }, [open, defaultParentId, editingCategory, 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({
      parentId,
      nameFa: nameFa.trim(),
      nameEn: nameEn.trim(),
      description: description.trim(),
    })
  }

  const parentOptions = flattenCategories(
    categories.filter((category) => category.id !== editingCategory?.id),
  )

  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="category-modal-title"
      >
        <div className={styles.header}>
          <h3 id="category-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>Parent Category</label>
            <SearchableSelect
              options={parentOptions}
              value={parentId}
              onChange={setParentId}
            />
          </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)}
              required
              disabled={isSubmitting}
            />
          </div>

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

          <div className={styles.field}>
            <label htmlFor="description">Description</label>
            <textarea
              id="description"
              name="description"
              rows={3}
              placeholder="Short description of this category"
              value={description}
              onChange={(e) => setDescription(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 Category'}
            </button>
          </div>
        </form>
      </div>
    </div>
  ,
  document.body,
  )
}
