import { useEffect, useState } from 'react'
import { createPortal } from 'react-dom'
import { X } from 'lucide-react'
import { CheckoutAddAddressPanel } from './CheckoutAddAddressPanel'
import modalStyles from '../VariationsModal.module.css'
import styles from './CheckoutAddAddressModal.module.css'

interface CheckoutAddAddressModalProps {
  open: boolean
  onClose: () => void
  onSaved: () => void
}

const ANIMATION_MS = 220

export function CheckoutAddAddressModal({ open, onClose, onSaved }: CheckoutAddAddressModalProps) {
  const [mounted, setMounted] = useState(open)
  const [closing, setClosing] = useState(false)
  const [formKey, setFormKey] = useState(0)

  useEffect(() => {
    if (open) {
      setMounted(true)
      setClosing(false)
      setFormKey((key) => key + 1)
    } 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 prevOverflow = document.body.style.overflow
    document.body.style.overflow = 'hidden'

    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose()
    }

    document.addEventListener('keydown', onKey)
    return () => {
      document.body.style.overflow = prevOverflow
      document.removeEventListener('keydown', onKey)
    }
  }, [mounted, closing, onClose])

  if (!mounted) return null

  function handleSaved() {
    onSaved()
    onClose()
  }

  return createPortal(
    <div
      className={`${modalStyles.overlay} ${styles.overlay} ${closing ? modalStyles.overlayOut : modalStyles.overlayIn}`}
      onClick={onClose}
    >
      <div
        className={`${modalStyles.modal} ${styles.modal} ${closing ? modalStyles.modalOut : modalStyles.modalIn}`}
        onClick={(e) => e.stopPropagation()}
        role="dialog"
        aria-modal="true"
        aria-labelledby="checkout-add-address-title"
        lang="fa"
        dir="rtl"
      >
        <div className={modalStyles.header}>
          <div>
            <h2 id="checkout-add-address-title" className={modalStyles.title}>
              افزودن آدرس جدید
            </h2>
            <p className={modalStyles.subtitle}>آدرس ارسال سفارش را وارد کنید.</p>
          </div>
          <button type="button" className={modalStyles.closeBtn} onClick={onClose} aria-label="بستن">
            <X size={20} />
          </button>
        </div>

        <div className={modalStyles.body}>
          <CheckoutAddAddressPanel
            key={formKey}
            inModal
            onSaved={handleSaved}
            onCancel={onClose}
          />
        </div>
      </div>
    </div>,
    document.body,
  )
}
