import { useEffect, useState } from 'react'
import { createPortal } from 'react-dom'
import { X } from 'lucide-react'
import { ApiError } from '../lib/api'
import { formatCellForDisplay, toE164CellNumber } from '../lib/cellNumber'
import { updateCustomer, type BusinessCustomerListItem } from '../services/customerService'
import modalStyles from './VariationsModal.module.css'

interface EditCustomerModalProps {
  open: boolean
  customer: BusinessCustomerListItem | null
  onClose: () => void
  onSaved: (customer: BusinessCustomerListItem) => void
}

const ANIMATION_MS = 220

export function EditCustomerModal({
  open,
  customer,
  onClose,
  onSaved,
}: EditCustomerModalProps) {
  const [mounted, setMounted] = useState(open)
  const [closing, setClosing] = useState(false)
  const [firstName, setFirstName] = useState('')
  const [lastName, setLastName] = useState('')
  const [cellNumber, setCellNumber] = useState('')
  const [email, setEmail] = useState('')
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [error, setError] = useState('')

  useEffect(() => {
    if (open && customer) {
      setMounted(true)
      setClosing(false)
      setFirstName(customer.firstName ?? '')
      setLastName(customer.lastName ?? '')
      setCellNumber(formatCellForDisplay(customer.cellNumber))
      setEmail(customer.email ?? '')
      setError('')
    } else if (mounted) {
      setClosing(true)
      const timer = setTimeout(() => {
        setMounted(false)
        setClosing(false)
      }, ANIMATION_MS)
      return () => clearTimeout(timer)
    }
  }, [open, customer, 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 || !customer) return null

  const canSave =
    firstName.trim().length >= 1 &&
    lastName.trim().length >= 1 &&
    toE164CellNumber(cellNumber.trim()).length > 0

  async function handleSubmit() {
    if (!customer || !canSave) return

    const normalizedCell = toE164CellNumber(cellNumber.trim())
    if (!normalizedCell) return

    setIsSubmitting(true)
    setError('')
    try {
      const updated = await updateCustomer(customer.id, {
        firstName: firstName.trim(),
        lastName: lastName.trim(),
        cellNumber: normalizedCell,
        email: email.trim(),
      })
      onSaved({
        ...customer,
        firstName: updated.firstName,
        lastName: updated.lastName,
        cellNumber: updated.cellNumber,
        email: updated.email,
        label: updated.label,
        isEnabled: updated.isEnabled,
      })
      onClose()
    } catch (err) {
      setError(err instanceof ApiError ? err.message : 'Unable to update customer.')
    } finally {
      setIsSubmitting(false)
    }
  }

  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="edit-customer-title"
      >
        <div className={modalStyles.header}>
          <div>
            <h3 id="edit-customer-title" className={modalStyles.title}>
              Edit customer
            </h3>
            <p className={modalStyles.subtitle}>Update customer contact details.</p>
          </div>
          <button type="button" className={modalStyles.closeBtn} onClick={onClose} aria-label="Close">
            <X size={18} />
          </button>
        </div>

        <div className={modalStyles.body}>
          {error && <p className={modalStyles.errorText}>{error}</p>}

          <div className={modalStyles.field}>
            <label htmlFor="edit-customer-first-name">First name</label>
            <input
              id="edit-customer-first-name"
              value={firstName}
              onChange={(e) => setFirstName(e.target.value)}
              disabled={isSubmitting}
            />
          </div>

          <div className={modalStyles.field}>
            <label htmlFor="edit-customer-last-name">Last name</label>
            <input
              id="edit-customer-last-name"
              value={lastName}
              onChange={(e) => setLastName(e.target.value)}
              disabled={isSubmitting}
            />
          </div>

          <div className={modalStyles.field}>
            <label htmlFor="edit-customer-cell">Cell number</label>
            <input
              id="edit-customer-cell"
              value={cellNumber}
              onChange={(e) => setCellNumber(e.target.value)}
              autoComplete="off"
              disabled={isSubmitting}
            />
          </div>

          <div className={modalStyles.field}>
            <label htmlFor="edit-customer-email">Email (optional)</label>
            <input
              id="edit-customer-email"
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              disabled={isSubmitting}
            />
          </div>

          <div className={modalStyles.actions}>
            <button
              type="button"
              className={modalStyles.cancelBtn}
              onClick={onClose}
              disabled={isSubmitting}
            >
              Cancel
            </button>
            <button
              type="button"
              className={modalStyles.submitBtn}
              onClick={() => void handleSubmit()}
              disabled={isSubmitting || !canSave}
            >
              Save
            </button>
          </div>
        </div>
      </div>
    </div>
  ,
  document.body,
  )
}
