import { useEffect, useState } from 'react'
import { createPortal } from 'react-dom'
import { X } from 'lucide-react'
import { useToast } from '../context/ToastContext'
import { ApiError } from '../lib/api'
import { updateOrder, type Order } from '../services/orderService'
import type { OrderProcessStep } from '../services/settingsService'
import { defaultStepColorForId, normalizeStepColor, stepBadgeStyle } from '../utils/stepColors'
import modalStyles from './VariationsModal.module.css'
import styles from './OrderStepModal.module.css'

interface OrderStepModalProps {
  open: boolean
  order: Order | null
  steps: OrderProcessStep[]
  onClose: () => void
  onSaved?: (order: Order) => void
}

const ANIMATION_MS = 220

export function OrderStepModal({
  open,
  order,
  steps,
  onClose,
  onSaved,
}: OrderStepModalProps) {
  const { showToast } = useToast()
  const [mounted, setMounted] = useState(open)
  const [closing, setClosing] = useState(false)
  const [savingStepId, setSavingStepId] = useState<string | null>(null)
  const [error, setError] = useState('')

  useEffect(() => {
    if (open && order) {
      setMounted(true)
      setClosing(false)
      setError('')
      setSavingStepId(null)
    } else if (mounted) {
      setClosing(true)
      const timer = setTimeout(() => {
        setMounted(false)
        setClosing(false)
      }, ANIMATION_MS)
      return () => clearTimeout(timer)
    }
  }, [open, mounted, order])

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

  async function handleSelectStep(stepId: string) {
    if (!order || savingStepId) return

    if (stepId === order.processStepId) {
      onClose()
      return
    }

    setSavingStepId(stepId)
    setError('')

    try {
      const result = await updateOrder(order.id, { processStepId: stepId })
      showToast(`Order ${order.orderNumber} step updated.`, 'success')
      onSaved?.(result.order)
      onClose()
    } catch (err) {
      setError(err instanceof ApiError ? err.message : 'Unable to update order step.')
    } finally {
      setSavingStepId(null)
    }
  }

  if (!mounted || !order) return null

  const currentLabel =
    order.processStepLabel?.trim() ||
    steps.find((step) => step.id === order.processStepId)?.label ||
    order.processStepId

  return createPortal(
    <div
      className={`${modalStyles.overlay} ${closing ? modalStyles.overlayOut : modalStyles.overlayIn}`}
      onClick={() => {
        if (!savingStepId) onClose()
      }}
    >
      <div
        className={`${modalStyles.modal} ${closing ? modalStyles.modalOut : modalStyles.modalIn}`}
        onClick={(e) => e.stopPropagation()}
        role="dialog"
        aria-modal="true"
        aria-labelledby="order-step-title"
      >
        <div className={modalStyles.header}>
          <div>
            <h2 id="order-step-title" className={modalStyles.title}>
              Change order step
            </h2>
            <p className={modalStyles.subtitle}>
              {order.orderNumber} · Current: {currentLabel}
            </p>
          </div>
          <button
            type="button"
            className={modalStyles.closeBtn}
            onClick={onClose}
            disabled={Boolean(savingStepId)}
            aria-label="Close"
          >
            <X size={20} />
          </button>
        </div>

        <div className={modalStyles.body}>
          {error && (
            <div className={modalStyles.errorText} role="alert">
              {error}
            </div>
          )}

          <div className={styles.stepList} role="listbox" aria-label="Order process step">
            {steps.map((step, index) => {
              const selected = order.processStepId === step.id
              const saving = savingStepId === step.id
              const color = normalizeStepColor(step.color, defaultStepColorForId(step.id, index))
              return (
                <button
                  key={step.id}
                  type="button"
                  role="option"
                  aria-selected={selected}
                  className={`${styles.stepOption} ${selected ? styles.stepOptionSelected : ''} ${saving ? styles.stepOptionSaving : ''}`}
                  style={selected ? stepBadgeStyle(color) : undefined}
                  disabled={Boolean(savingStepId)}
                  onClick={() => void handleSelectStep(step.id)}
                >
                  <span className={styles.stepColorDot} style={{ backgroundColor: color }} />
                  <span className={styles.stepNumber}>{index + 1}</span>
                  <span className={styles.stepLabel}>
                    {saving ? 'Saving...' : step.label}
                  </span>
                </button>
              )
            })}
          </div>

          {!steps.length && (
            <p className={styles.emptyText}>
              No order steps configured. Add steps in Store settings first.
            </p>
          )}
        </div>
      </div>
    </div>
  ,
  document.body,
  )
}
