import { useEffect, useState } from 'react'
import { createPortal } from 'react-dom'
import { X } from 'lucide-react'
import { useLocale } from '@meshkee/dashboard-ui'
import type { ContactSubmission } from '../types/contactSubmission'
import { formatCellForDisplay } from '../lib/cellNumber'
import { useT } from '../i18n/useT'
import modalStyles from './VariationsModal.module.css'
import styles from './ContactSubmissionDetailModal.module.css'

interface ContactSubmissionDetailModalProps {
  open: boolean
  submission: ContactSubmission | null
  onClose: () => void
}

const ANIMATION_MS = 220

function formatDateTime(value: string, locale: 'en' | 'fa') {
  const d = new Date(value)
  if (Number.isNaN(d.getTime())) return { date: value, time: '' }
  const intlLocale = locale === 'fa' ? 'fa-IR' : 'en-US'
  return {
    date: d.toLocaleDateString(intlLocale, { year: 'numeric', month: 'short', day: '2-digit' }),
    time: d.toLocaleTimeString(intlLocale, { hour: '2-digit', minute: '2-digit' }),
  }
}

export function ContactSubmissionDetailModal({
  open,
  submission,
  onClose,
}: ContactSubmissionDetailModalProps) {
  const t = useT()
  const { locale } = useLocale()
  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 || !submission) return null

  const { date, time } = formatDateTime(submission.createdAt, locale)

  return createPortal(
    <div
      className={`${modalStyles.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="contact-submission-title"
      >
        <div className={modalStyles.header}>
          <div>
            <h2 id="contact-submission-title" className={modalStyles.title}>
              {t('website.contact.detailTitle')}
            </h2>
            <p className={modalStyles.subtitle}>{submission.title}</p>
          </div>
          <button
            type="button"
            className={modalStyles.closeBtn}
            onClick={onClose}
            aria-label={t('common.close')}
          >
            <X size={20} />
          </button>
        </div>

        <div className={styles.body}>
          <dl className={styles.metaGrid}>
            <div className={styles.metaItem}>
              <dt>{t('website.contact.col.name')}</dt>
              <dd>{submission.name}</dd>
            </div>
            <div className={styles.metaItem}>
              <dt>{t('website.contact.col.email')}</dt>
              <dd>{submission.email ?? '—'}</dd>
            </div>
            <div className={styles.metaItem}>
              <dt>{t('website.contact.col.cell')}</dt>
              <dd>
                {submission.cellNumber ? formatCellForDisplay(submission.cellNumber) : '—'}
              </dd>
            </div>
            <div className={styles.metaItem}>
              <dt>{t('website.contact.col.date')}</dt>
              <dd>{date}</dd>
            </div>
            <div className={styles.metaItem}>
              <dt>{t('website.contact.col.time')}</dt>
              <dd>{time || '—'}</dd>
            </div>
          </dl>

          <div className={styles.messageBlock}>
            <h3 className={styles.messageLabel}>{t('website.contact.detailMessage')}</h3>
            <p className={styles.messageText}>{submission.text}</p>
          </div>
        </div>
      </div>
    </div>
  ,
  document.body,
  )
}
