import { useEffect, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import { Plus, Sparkles, Trash2, X } from 'lucide-react'
import { useLocale } from '@meshkee/dashboard-ui'
import type { TechnicalFieldType, TechnicalFormFieldDraft } from '../types/technicalForm'
import { useT } from '../i18n/useT'
import type { BusinessMessageKey } from '../i18n/messages'
import { createId } from '../utils/id'
import { Tooltip } from './Tooltip'
import styles from './VariationsModal.module.css'
import fieldStyles from './TechnicalFormModal.module.css'
import aiStyles from '../styles/ai.module.css'

interface TechnicalFormModalProps {
  open: boolean
  categoryName: string
  fields: TechnicalFormFieldDraft[]
  isLoading?: boolean
  isSaving?: boolean
  isGenerating?: boolean
  escapeDisabled?: boolean
  error?: string
  onClose: () => void
  onChange: (fields: TechnicalFormFieldDraft[]) => void
  onSave: () => void
  onGenerate?: () => void
  onGenerateClick?: () => void
}

const ANIMATION_MS = 220

const FIELD_TYPE_KEYS: Record<TechnicalFieldType, BusinessMessageKey> = {
  text: 'categories.technical.type.text',
  textarea: 'categories.technical.type.textarea',
  select: 'categories.technical.type.select',
  multi_select: 'categories.technical.type.multi_select',
}

function createEmptyField(): TechnicalFormFieldDraft {
  return {
    id: createId(),
    label: '',
    type: 'text',
    isRequired: false,
    options: [''],
  }
}

export function TechnicalFormModal({
  open,
  categoryName,
  fields,
  isLoading = false,
  isSaving = false,
  isGenerating = false,
  escapeDisabled = false,
  error = '',
  onClose,
  onChange,
  onSave,
  onGenerate,
  onGenerateClick,
}: TechnicalFormModalProps) {
  const t = useT()
  const { locale } = useLocale()
  const isFa = locale === 'fa'
  const [mounted, setMounted] = useState(open)
  const [closing, setClosing] = useState(false)
  const optionInputRefs = useRef<Record<string, (HTMLInputElement | null)[]>>({})
  const pendingFocus = useRef<{ fieldId: string; index: number } | null>(null)

  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 (!pendingFocus.current) return
    const { fieldId, index } = pendingFocus.current
    optionInputRefs.current[fieldId]?.[index]?.focus()
    pendingFocus.current = null
  }, [fields])

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

  if (!mounted) return null

  function updateField(fieldId: string, patch: Partial<TechnicalFormFieldDraft>) {
    onChange(
      fields.map((field) => (field.id === fieldId ? { ...field, ...patch } : field)),
    )
  }

  function removeField(fieldId: string) {
    onChange(fields.filter((field) => field.id !== fieldId))
  }

  function addField() {
    onChange([...fields, createEmptyField()])
  }

  function updateOption(fieldId: string, index: number, value: string) {
    onChange(
      fields.map((field) => {
        if (field.id !== fieldId) return field
        return {
          ...field,
          options: field.options.map((option, optionIndex) =>
            optionIndex === index ? value : option,
          ),
        }
      }),
    )
  }

  function addOption(fieldId: string) {
    onChange(
      fields.map((field) =>
        field.id === fieldId ? { ...field, options: [...field.options, ''] } : field,
      ),
    )
  }

  function removeOption(fieldId: string, index: number) {
    onChange(
      fields.map((field) => {
        if (field.id !== fieldId) return field
        const next = field.options.filter((_, optionIndex) => optionIndex !== index)
        return { ...field, options: next.length ? next : [''] }
      }),
    )
  }

  function handleOptionKeyDown(
    fieldId: string,
    index: number,
    e: React.KeyboardEvent<HTMLInputElement>,
    options: string[],
  ) {
    if (e.key !== 'Enter') return
    e.preventDefault()

    const nextIndex = index + 1
    if (nextIndex < options.length) {
      optionInputRefs.current[fieldId]?.[nextIndex]?.focus()
      return
    }

    pendingFocus.current = { fieldId, index: nextIndex }
    addOption(fieldId)
  }

  const canSave =
    !isLoading &&
    !isSaving &&
    !isGenerating &&
    fields.every((field) => {
      if (!field.label.trim()) return false
      if (field.type === 'select' || field.type === 'multi_select') {
        return field.options.some((option) => option.trim())
      }
      return true
    })

  return createPortal(
    <div
      className={`${styles.overlay} ${closing ? styles.overlayOut : styles.overlayIn}`}
      onClick={onClose}
    >
      <div
        className={`${styles.modal} ${fieldStyles.modalWide} ${closing ? styles.modalOut : styles.modalIn}`}
        onClick={(e) => e.stopPropagation()}
        role="dialog"
        aria-modal="true"
        aria-labelledby="technical-form-title"
        lang={isFa ? 'fa' : 'en'}
        dir={isFa ? 'rtl' : 'ltr'}
      >
        <div className={styles.header}>
          <div>
            <h3 id="technical-form-title" className={styles.title}>
              {t('categories.technical.title')}
            </h3>
            {categoryName ? <p className={styles.subtitle}>{categoryName}</p> : null}
          </div>
          <button
            className={styles.closeBtn}
            onClick={onClose}
            aria-label={t('common.close')}
            type="button"
          >
            <X size={20} />
          </button>
        </div>

        <div className={styles.body}>
          {isLoading ? (
            <p className={styles.emptyText}>{t('categories.technical.loading')}</p>
          ) : (
            <>
              <div className={fieldStyles.fieldList}>
                {fields.map((field) => (
                  <div key={field.id} className={fieldStyles.fieldCard}>
                    <div className={fieldStyles.fieldMainRow}>
                      <input
                        id={`label-${field.id}`}
                        type="text"
                        className={fieldStyles.compactInput}
                        placeholder={t('categories.technical.fieldLabel')}
                        value={field.label}
                        onChange={(e) => updateField(field.id, { label: e.target.value })}
                        aria-label={t('categories.technical.fieldLabel')}
                      />
                      <select
                        id={`type-${field.id}`}
                        className={fieldStyles.compactInput}
                        value={field.type}
                        aria-label={t('categories.technical.inputType')}
                        onChange={(e) => {
                          const type = e.target.value as TechnicalFieldType
                          updateField(field.id, {
                            type,
                            options:
                              type === 'select' || type === 'multi_select'
                                ? field.options.length
                                  ? field.options
                                  : ['']
                                : [],
                          })
                        }}
                      >
                        {(Object.keys(FIELD_TYPE_KEYS) as TechnicalFieldType[]).map((value) => (
                          <option key={value} value={value}>
                            {t(FIELD_TYPE_KEYS[value])}
                          </option>
                        ))}
                      </select>
                      <label
                        className={fieldStyles.requiredCell}
                        title={t('categories.technical.required')}
                      >
                        <input
                          type="checkbox"
                          checked={field.isRequired}
                          onChange={(e) =>
                            updateField(field.id, { isRequired: e.target.checked })
                          }
                        />
                        <span>{t('categories.technical.required')}</span>
                      </label>
                      <div className={fieldStyles.removeCell}>
                        <Tooltip label={t('categories.technical.removeField')}>
                          <button
                            type="button"
                            className={styles.removeRowBtn}
                            onClick={() => removeField(field.id)}
                            aria-label={t('categories.technical.removeField')}
                          >
                            <Trash2 size={15} />
                          </button>
                        </Tooltip>
                      </div>
                    </div>

                    {(field.type === 'select' || field.type === 'multi_select') && (
                      <div className={fieldStyles.optionsBlock}>
                        <span className={fieldStyles.optionsLabel}>
                          {t('categories.technical.options')}
                        </span>
                        <div className={fieldStyles.customValues}>
                          {field.options.map((option, optionIndex) => (
                            <div key={optionIndex} className={fieldStyles.customRow}>
                              <input
                                ref={(el) => {
                                  if (!optionInputRefs.current[field.id]) {
                                    optionInputRefs.current[field.id] = []
                                  }
                                  optionInputRefs.current[field.id][optionIndex] = el
                                }}
                                type="text"
                                placeholder={t('categories.technical.optionN', {
                                  n: optionIndex + 1,
                                })}
                                value={option}
                                onChange={(e) =>
                                  updateOption(field.id, optionIndex, e.target.value)
                                }
                                onKeyDown={(e) =>
                                  handleOptionKeyDown(field.id, optionIndex, e, field.options)
                                }
                              />
                              {field.options.length > 1 && (
                                <div className={fieldStyles.removeCell}>
                                  <Tooltip label={t('categories.technical.removeOption')}>
                                    <button
                                      type="button"
                                      className={styles.removeRowBtn}
                                      onClick={() => removeOption(field.id, optionIndex)}
                                      aria-label={t('categories.technical.removeOption')}
                                    >
                                      <X size={16} />
                                    </button>
                                  </Tooltip>
                                </div>
                              )}
                              {field.options.length <= 1 && <div />}
                            </div>
                          ))}
                          <button
                            type="button"
                            className={styles.addValueBtn}
                            onClick={() => addOption(field.id)}
                          >
                            <Plus size={14} />
                            {t('categories.technical.addOption')}
                          </button>
                        </div>
                      </div>
                    )}
                  </div>
                ))}

                {!fields.length && (
                  <p className={styles.emptyText}>{t('categories.technical.empty')}</p>
                )}
              </div>

              <div className={fieldStyles.toolbar}>
                <button type="button" className={styles.addBtn} onClick={addField}>
                  <Plus size={18} />
                  {t('categories.technical.addField')}
                </button>
              </div>
            </>
          )}

          {error ? <p className={styles.errorText}>{error}</p> : null}

          <div className={`${styles.actions} ${fieldStyles.actionsRow}`}>
            <div className={fieldStyles.actionsMain}>
              <button
                type="button"
                className={styles.submitBtn}
                onClick={onSave}
                disabled={!canSave}
              >
                {isSaving
                  ? t('categories.technical.saving')
                  : t('categories.technical.save')}
              </button>
              <button
                type="button"
                className={styles.cancelBtn}
                onClick={onClose}
                disabled={isSaving || isGenerating}
              >
                {t('categories.modal.cancel')}
              </button>
            </div>
            {(onGenerateClick ?? onGenerate) ? (
              <button
                type="button"
                className={`${aiStyles.aiBtn} ${fieldStyles.actionsAi}`}
                onClick={onGenerateClick ?? onGenerate}
                disabled={isLoading || isSaving || isGenerating}
              >
                <Sparkles size={16} />
                {isGenerating
                  ? t('products.form.aiGenerating')
                  : t('categories.technical.generateAi')}
              </button>
            ) : null}
          </div>
        </div>
      </div>
    </div>,
    document.body,
  )
}
