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 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,
  isSubmitting = false,
}: CategoryModalProps) {
  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 [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"
        lang={isFa ? 'fa' : 'en'}
        dir={isFa ? 'rtl' : 'ltr'}
      >
        <div className={styles.header}>
          <h3 id="category-modal-title" className={styles.title}>
            {title ?? t('categories.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('categories.modal.parent')}</label>
            <SearchableSelect
              options={parentOptions}
              value={parentId}
              onChange={setParentId}
              placeholder={t('categories.select.search')}
            />
          </div>

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

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

          <div className={styles.field}>
            <label htmlFor="description">{t('categories.modal.description')}</label>
            <textarea
              id="description"
              name="description"
              rows={3}
              dir={isFa ? 'rtl' : 'ltr'}
              placeholder={t('categories.modal.descriptionPlaceholder')}
              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}
            >
              {t('categories.modal.cancel')}
            </button>
            <button type="submit" className={styles.submitBtn} disabled={isSubmitting}>
              {isSubmitting ? t('categories.modal.saving') : t('categories.modal.save')}
            </button>
          </div>
        </form>
      </div>
    </div>
  ,
  document.body,
  )
}
