import { useEffect, 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 { StoreItem } from '../services/storeItemService'
import { StoreItemPrice } from './StoreItemPrice'
import modalStyles from './VariationsModal.module.css'
import styles from './PickStoreVariantModal.module.css'

interface PickStoreVariantModalProps {
  open: boolean
  productTitle: string
  productNameFa: string
  variants: StoreItem[]
  onClose: () => void
  onSelect: (variant: StoreItem) => void
}

const ANIMATION_MS = 220

export function PickStoreVariantModal({
  open,
  productTitle,
  productNameFa,
  variants,
  onClose,
  onSelect,
}: PickStoreVariantModalProps) {
  const t = useT()
  const { locale } = useLocale()
  const isFa = locale === 'fa'
  const [mounted, setMounted] = useState(open)
  const [closing, setClosing] = useState(false)

  useEffect(() => {
    if (open) {
      setMounted(true)
      setClosing(false)
    } else if (mounted) {
      setClosing(true)
      const timer = setTimeout(() => {
        setMounted(false)
        setClosing(false)
      }, ANIMATION_MS)
      return () => clearTimeout(timer)
    }
  }, [open, 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 subtitle = isFa
    ? [productNameFa, productTitle].filter(Boolean).join(' / ')
    : [productTitle, productNameFa].filter(Boolean).join(' / ')

  return createPortal(
    <div
      className={`${modalStyles.overlay} ${closing ? modalStyles.overlayOut : modalStyles.overlayIn}`}
      onClick={onClose}
    >
      <div
        className={`${modalStyles.modal} ${closing ? modalStyles.modalOut : modalStyles.modalIn}`}
        onClick={(e) => e.stopPropagation()}
        role="dialog"
        aria-modal="true"
        aria-labelledby="pick-variant-title"
        lang={isFa ? 'fa' : 'en'}
        dir={isFa ? 'rtl' : 'ltr'}
      >
        <div className={modalStyles.header}>
          <div>
            <h2 id="pick-variant-title" className={modalStyles.title}>
              {t('storeItems.pick.title')}
            </h2>
            <p className={modalStyles.subtitle}>{subtitle}</p>
          </div>
          <button
            type="button"
            className={modalStyles.closeBtn}
            onClick={onClose}
            aria-label={t('common.close')}
          >
            <X size={18} />
          </button>
        </div>

        <div className={`${modalStyles.body} ${styles.body}`}>
          <ul className={styles.list}>
            {variants.map((variant) => (
              <li key={variant.id}>
                <button
                  type="button"
                  className={styles.option}
                  onClick={() => onSelect(variant)}
                >
                  <div className={styles.optionMain}>
                    <span className={styles.optionLabel}>{variant.label}</span>
                    {variant.stockQuantity !== null && (
                      <span className={styles.optionStock}>
                        {t('storeItems.pick.inStock', { count: variant.stockQuantity })}
                      </span>
                    )}
                  </div>
                  <StoreItemPrice
                    price={variant.price}
                    discountedPrice={variant.discountedPrice}
                  />
                </button>
              </li>
            ))}
          </ul>
        </div>
      </div>
    </div>
  ,
  document.body,
  )
}
