import { useEffect, useState } from 'react'
import { createPortal } from 'react-dom'
import { X } from 'lucide-react'
import { useLocale } from '@meshkee/dashboard-ui'
import { useT } from '../i18n/useT'
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 t = useT()
  const { locale } = useLocale()
  const isFa = locale === 'fa'
  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 [passwordConfirm, setPasswordConfirm] = useState('')
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [error, setError] = useState('')

  useEffect(() => {
    if (open) {
      setMounted(true)
      setClosing(false)
      setFirstName('')
      setLastName('')
      setCellNumber('')
      setPassword('')
      setPasswordConfirm('')
      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

    const trimmedPassword = password.trim()
    if (trimmedPassword || passwordConfirm.trim()) {
      if (trimmedPassword.length < 8) {
        setError(t('customers.addModal.errorPasswordLength'))
        return
      }
      if (trimmedPassword !== passwordConfirm.trim()) {
        setError(t('customers.addModal.errorPasswordMatch'))
        return
      }
    }

    setIsSubmitting(true)
    setError('')
    try {
      const created = await createCustomer({
        cellNumber: normalizedCell,
        firstName: firstName.trim(),
        lastName: lastName.trim(),
        ...(trimmedPassword ? { password: trimmedPassword } : {}),
      })
      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 : t('customers.addModal.error'))
    } 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"
        lang={isFa ? 'fa' : 'en'}
        dir={isFa ? 'rtl' : 'ltr'}
      >
        <div className={modalStyles.header}>
          <div>
            <h3 id="add-customer-title" className={modalStyles.title}>
              {t('customers.addModal.title')}
            </h3>
            <p className={modalStyles.subtitle}>{t('customers.addModal.subtitle')}</p>
          </div>
          <button
            type="button"
            className={modalStyles.closeBtn}
            onClick={onClose}
            aria-label={t('common.close')}
          >
            <X size={18} />
          </button>
        </div>

        <div className={modalStyles.body}>
          <p className={formStyles.hint}>{t('customers.addModal.hint')}</p>

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

          <div className={formStyles.formGrid}>
            <div className={modalStyles.field}>
              <label htmlFor="add-customer-first-name">{t('customers.addModal.firstName')}</label>
              <input
                id="add-customer-first-name"
                value={firstName}
                onChange={(e) => setFirstName(e.target.value)}
                disabled={isSubmitting}
                dir={isFa ? 'rtl' : 'ltr'}
              />
            </div>
            <div className={modalStyles.field}>
              <label htmlFor="add-customer-last-name">{t('customers.addModal.lastName')}</label>
              <input
                id="add-customer-last-name"
                value={lastName}
                onChange={(e) => setLastName(e.target.value)}
                disabled={isSubmitting}
                dir={isFa ? 'rtl' : 'ltr'}
              />
            </div>
            <div className={`${modalStyles.field} ${formStyles.formFull}`}>
              <label htmlFor="add-customer-cell">{t('customers.addModal.cell')}</label>
              <input
                id="add-customer-cell"
                value={cellNumber}
                onChange={(e) => setCellNumber(e.target.value)}
                placeholder={t('customers.addModal.cellPlaceholder')}
                autoComplete="off"
                disabled={isSubmitting}
                inputMode="tel"
                dir="ltr"
              />
            </div>
            <div className={modalStyles.field}>
              <label htmlFor="add-customer-password">{t('customers.addModal.password')}</label>
              <input
                id="add-customer-password"
                type="password"
                autoComplete="new-password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder={t('customers.addModal.passwordPlaceholder')}
                disabled={isSubmitting}
                dir="ltr"
              />
            </div>
            <div className={modalStyles.field}>
              <label htmlFor="add-customer-password-confirm">
                {t('customers.addModal.passwordConfirm')}
              </label>
              <input
                id="add-customer-password-confirm"
                type="password"
                autoComplete="new-password"
                value={passwordConfirm}
                onChange={(e) => setPasswordConfirm(e.target.value)}
                placeholder={t('customers.addModal.passwordConfirmPlaceholder')}
                disabled={isSubmitting}
                dir="ltr"
              />
            </div>
          </div>

          <div className={modalStyles.actions}>
            <button
              type="button"
              className={modalStyles.cancelBtn}
              onClick={onClose}
              disabled={isSubmitting}
            >
              {t('customers.addModal.cancel')}
            </button>
            <button
              type="button"
              className={modalStyles.submitBtn}
              onClick={() => void handleSubmit()}
              disabled={isSubmitting || !canSubmit}
            >
              {t('customers.addModal.submit')}
            </button>
          </div>
        </div>
      </div>
    </div>
  ,
  document.body,
  )
}
