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 styles from './CategoryModal.module.css'

export interface StoreSpecialModalValues {
  key: string
  title: string
}

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

const ANIMATION_MS = 220
const KEY_PATTERN = /^[a-zA-Z][a-zA-Z0-9_-]*$/

export function StoreSpecialModal({
  open,
  onClose,
  onSubmit,
  initialKey = '',
  initialTitle = '',
  title,
  submitLabel,
  isSubmitting = false,
}: StoreSpecialModalProps) {
  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 [groupKey, setGroupKey] = useState(initialKey)
  const [groupTitle, setGroupTitle] = useState(initialTitle)

  useEffect(() => {
    if (open) {
      setMounted(true)
      setClosing(false)
      setGroupKey(initialKey)
      setGroupTitle(initialTitle)
    } else if (mounted) {
      setClosing(true)
      const timer = setTimeout(() => {
        setMounted(false)
        setClosing(false)
      }, ANIMATION_MS)
      return () => clearTimeout(timer)
    }
  }, [open, initialKey, 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

  const trimmedKey = groupKey.trim()
  const trimmedTitle = groupTitle.trim()
  const keyValid = KEY_PATTERN.test(trimmedKey)
  const canSubmit = keyValid && trimmedTitle.length > 0

  function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault()
    if (!canSubmit) return
    onSubmit({ key: trimmedKey, title: trimmedTitle })
  }

  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"
        lang={isFa ? 'fa' : 'en'}
        dir={isFa ? 'rtl' : 'ltr'}
      >
        <div className={styles.header}>
          <h2 id="special-modal-title" className={styles.title}>
            {title ?? t('website.specialItems.createTitle')}
          </h2>
          <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 htmlFor="special-group-key">{t('website.groupKey')}</label>
            <input
              id="special-group-key"
              value={groupKey}
              onChange={(e) => setGroupKey(e.target.value)}
              placeholder={t('website.groupKeyPlaceholder')}
              autoFocus
              disabled={isSubmitting}
              dir="ltr"
              autoComplete="off"
              spellCheck={false}
            />
            <p className={styles.hint}>{t('website.groupKeyHint')}</p>
          </div>

          <div className={styles.field}>
            <label htmlFor="special-group-title">{t('website.groupValue')}</label>
            <input
              id="special-group-title"
              value={groupTitle}
              onChange={(e) => setGroupTitle(e.target.value)}
              placeholder={t('website.groupValuePlaceholder')}
              disabled={isSubmitting}
              dir={isFa ? 'rtl' : 'ltr'}
            />
          </div>

          <div className={styles.actions}>
            <button
              type="button"
              className={styles.cancelBtn}
              onClick={onClose}
              disabled={isSubmitting}
            >
              {t('products.form.cancel')}
            </button>
            <button
              type="submit"
              className={styles.submitBtn}
              disabled={isSubmitting || !canSubmit}
            >
              {isSubmitting
                ? t('website.saving')
                : (submitLabel ?? t('website.create'))}
            </button>
          </div>
        </form>
      </div>
    </div>
  ,
  document.body,
  )
}
