import { useEffect, useState } from 'react'
import { createPortal } from 'react-dom'
import { AlertTriangle, PackagePlus, X } from 'lucide-react'
import { useLocale } from '@meshkee/dashboard-ui'
import { useT } from '../i18n/useT'
import styles from './ConfirmBulkAddStoreItemsModal.module.css'

export interface BulkAddResult {
  created: number
  skipped: number
  failed: number
}

interface ConfirmBulkAddStoreItemsModalProps {
  open: boolean
  busy: boolean
  result: BulkAddResult | null
  onConfirm: () => void
  onClose: () => void
}

const ANIMATION_MS = 220

export function ConfirmBulkAddStoreItemsModal({
  open,
  busy,
  result,
  onConfirm,
  onClose,
}: ConfirmBulkAddStoreItemsModalProps) {
  const t = useT()
  const { locale } = useLocale()
  const isFa = locale === 'fa'
  const [mounted, setMounted] = useState(open)
  const [closing, setClosing] = useState(false)
  const [agreed, setAgreed] = useState(false)

  useEffect(() => {
    if (open) {
      setMounted(true)
      setClosing(false)
      setAgreed(false)
    } else if (mounted) {
      setClosing(true)
      const timer = setTimeout(() => {
        setMounted(false)
        setClosing(false)
        setAgreed(false)
      }, ANIMATION_MS)
      return () => clearTimeout(timer)
    }
  }, [open, mounted])

  useEffect(() => {
    if (!mounted || closing) return
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && !busy) onClose()
    }
    document.addEventListener('keydown', onKey)
    return () => document.removeEventListener('keydown', onKey)
  }, [mounted, closing, onClose, busy])

  if (!mounted) return null

  const showResult = result !== null

  return createPortal(
    <div
      className={`${styles.overlay} ${closing ? styles.overlayOut : styles.overlayIn}`}
      onClick={() => {
        if (!busy) onClose()
      }}
    >
      <div
        className={`${styles.modal} ${closing ? styles.modalOut : styles.modalIn}`}
        onClick={(e) => e.stopPropagation()}
        role="alertdialog"
        aria-modal="true"
        aria-labelledby="confirm-bulk-add-title"
        lang={isFa ? 'fa' : 'en'}
        dir={isFa ? 'rtl' : 'ltr'}
      >
        <div className={styles.iconWrap}>
          {showResult ? <PackagePlus size={28} /> : <AlertTriangle size={28} />}
        </div>

        <h3 id="confirm-bulk-add-title" className={styles.title}>
          {showResult
            ? t('storeItems.create.addAllResultTitle')
            : t('storeItems.create.addAllConfirmTitle')}
        </h3>

        {showResult ? (
          <p className={styles.message}>
            {t('storeItems.create.addAllDone', {
              created: String(result.created),
              skipped: String(result.skipped),
              failed: String(result.failed),
            })}
          </p>
        ) : (
          <>
            <p className={styles.message}>{t('storeItems.create.addAllConfirmIntro')}</p>
            <ul className={styles.points}>
              <li>{t('storeItems.create.addAllConfirmMax')}</li>
              <li>{t('storeItems.create.addAllConfirmSkip')}</li>
              <li>{t('storeItems.create.addAllConfirmHeavy')}</li>
            </ul>

            <label className={styles.agree}>
              <input
                type="checkbox"
                className={styles.agreeCheck}
                checked={agreed}
                onChange={(e) => setAgreed(e.target.checked)}
                disabled={busy}
              />
              <span>{t('storeItems.create.addAllAgree')}</span>
            </label>
          </>
        )}

        <div className={styles.actions}>
          {showResult ? (
            <button type="button" className={styles.confirmBtn} onClick={onClose}>
              {t('storeItems.create.addAllDoneBtn')}
            </button>
          ) : (
            <>
              <button
                type="button"
                className={styles.cancelBtn}
                onClick={onClose}
                disabled={busy}
              >
                {t('storeItems.create.cancel')}
              </button>
              <button
                type="button"
                className={styles.confirmBtn}
                onClick={onConfirm}
                disabled={!agreed || busy}
              >
                {busy
                  ? t('storeItems.create.addingAll')
                  : t('storeItems.create.addAllConfirm')}
              </button>
            </>
          )}
        </div>

        <button
          className={styles.closeBtn}
          onClick={onClose}
          aria-label={t('common.close')}
          disabled={busy}
        >
          <X size={18} />
        </button>
      </div>
    </div>,
    document.body,
  )
}
