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

interface AddCustomerModalProps {
  open: boolean
  onClose: () => void
  onCreated: (customer: BusinessCustomerListItem) => void
}

const ANIMATION_MS = 220

export function AddCustomerModal({ open, onClose, onCreated }: AddCustomerModalProps) {
  const [mounted, setMounted] = useState(open)
  const [closing, setClosing] = useState(false)
  const [firstName, setFirstName] = useState('')
  const [lastName, setLastName] = useState('')
  const [cellNumber, setCellNumber] = useState('')
  const [password, setPassword] = useState('')
  const [email, setEmail] = useState('')
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [error, setError] = useState('')

  useEffect(() => {
    if (open) {
      setMounted(true)
      setClosing(false)
      setFirstName('')
      setLastName('')
      setCellNumber('')
      setPassword('')
      setEmail('')
      setError('')
    } 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 canSubmit =
    firstName.trim().length >= 2 &&
    lastName.trim().length >= 2 &&
    toE164CellNumber(cellNumber.trim()).length > 0

  async function handleSubmit() {
    const normalizedCell = toE164CellNumber(cellNumber.trim())
    if (!canSubmit || !normalizedCell) return

    setIsSubmitting(true)
    setError('')
    try {
      const created = await createCustomer({
        cellNumber: normalizedCell,
        firstName: firstName.trim(),
        lastName: lastName.trim(),
        ...(password.trim() ? { password: password.trim() } : {}),
        ...(email.trim() ? { email: email.trim() } : {}),
      })
      onCreated({
        id: created.id,
        cellNumber: created.cellNumber,
        firstName: created.firstName,
        lastName: created.lastName,
        email: created.email,
        label: created.label,
        createdAt: created.createdAt,
        isEnabled: created.isEnabled,
      })
      onClose()
    } catch (err) {
      setError(err instanceof ApiError ? err.message : 'Unable to add 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="add-customer-title"
      >
        <div className={modalStyles.header}>
          <div>
            <h3 id="add-customer-title" className={modalStyles.title}>
              Add customer
            </h3>
            <p className={modalStyles.subtitle}>
              Creates a verified customer account or links an existing user to your business.
            </p>
          </div>
          <button type="button" className={modalStyles.closeBtn} onClick={onClose} aria-label="Close">
            <X size={18} />
          </button>
        </div>

        <div className={modalStyles.body}>
          <p className={formStyles.hint}>
            Password is required only for new accounts. Existing users are added as verified
            customers.
          </p>

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

          <div className={formStyles.formGrid}>
            <div className={modalStyles.field}>
              <label htmlFor="add-customer-first-name">First name</label>
              <input
                id="add-customer-first-name"
                value={firstName}
                onChange={(e) => setFirstName(e.target.value)}
                disabled={isSubmitting}
              />
            </div>
            <div className={modalStyles.field}>
              <label htmlFor="add-customer-last-name">Last name</label>
              <input
                id="add-customer-last-name"
                value={lastName}
                onChange={(e) => setLastName(e.target.value)}
                disabled={isSubmitting}
              />
            </div>
            <div className={`${modalStyles.field} ${formStyles.formFull}`}>
              <label htmlFor="add-customer-cell">Cell number</label>
              <input
                id="add-customer-cell"
                value={cellNumber}
                onChange={(e) => setCellNumber(e.target.value)}
                placeholder="0912..."
                autoComplete="off"
                disabled={isSubmitting}
              />
            </div>
            <div className={`${modalStyles.field} ${formStyles.formFull}`}>
              <label htmlFor="add-customer-password">Password (new users)</label>
              <input
                id="add-customer-password"
                type="password"
                autoComplete="new-password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder="Min. 8 characters"
                disabled={isSubmitting}
              />
            </div>
            <div className={`${modalStyles.field} ${formStyles.formFull}`}>
              <label htmlFor="add-customer-email">Email (optional)</label>
              <input
                id="add-customer-email"
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                disabled={isSubmitting}
              />
            </div>
          </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 || !canSubmit}
            >
              Add customer
            </button>
          </div>
        </div>
      </div>
    </div>
  ,
  document.body,
  )
}
