import { useEffect, useState } from 'react'
import { createPortal } from 'react-dom'
import { X } from 'lucide-react'
import type { ProductVariant } from '../types/productVariant'
import { buildVariantLabel } from '../types/productVariant'
import type { ProductVariantAttribute } from '../services/productVariantService'
import styles from './VariationsModal.module.css'

interface CreateProductVariantModalProps {
  open: boolean
  attributes: ProductVariantAttribute[]
  existingVariants: ProductVariant[]
  isSubmitting?: boolean
  error?: string
  onClose: () => void
  onSubmit: (payload: { variationId: string; optionId: string }) => void
}

const ANIMATION_MS = 220

export function CreateProductVariantModal({
  open,
  attributes,
  existingVariants,
  isSubmitting = false,
  error = '',
  onClose,
  onSubmit,
}: CreateProductVariantModalProps) {
  const [mounted, setMounted] = useState(open)
  const [closing, setClosing] = useState(false)
  const [variationId, setVariationId] = useState('')
  const [optionId, setOptionId] = useState('')

  const selectedVariation = attributes.find((item) => item.id === variationId)
  const options = selectedVariation?.options ?? []

  useEffect(() => {
    if (open) {
      setMounted(true)
      setClosing(false)
      const first = attributes[0]
      setVariationId(first?.id ?? '')
      setOptionId(first?.options[0]?.id ?? '')
    } else if (mounted) {
      setClosing(true)
      const timer = setTimeout(() => {
        setMounted(false)
        setClosing(false)
      }, ANIMATION_MS)
      return () => clearTimeout(timer)
    }
  }, [open, mounted, attributes])

  useEffect(() => {
    if (!selectedVariation) return
    if (!options.some((item) => item.id === optionId)) {
      setOptionId(options[0]?.id ?? '')
    }
  }, [selectedVariation, options, optionId])

  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 selectedOption = options.find((item) => item.id === optionId)
  const selectionList = selectedVariation && selectedOption
    ? [
        {
          attributeId: selectedVariation.id,
          attributeName: selectedVariation.name,
          optionId: selectedOption.id,
          value: selectedOption.label,
        },
      ]
    : []

  const label = buildVariantLabel(selectionList)
  const isDuplicate = existingVariants.some((variant) =>
    variant.selections.some((selection) => selection.optionId === optionId),
  )
  const canSubmit =
    Boolean(variationId && optionId && selectionList.length) &&
    !isDuplicate &&
    !isSubmitting

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    if (!canSubmit) return
    onSubmit({ variationId, optionId })
  }

  return createPortal(
    <div
      className={`${styles.overlay} ${styles.overlayNested} ${closing ? styles.overlayOut : styles.overlayIn}`}
      onClick={onClose}
    >
      <div
        className={`${styles.modal} ${closing ? styles.modalOut : styles.modalIn}`}
        onClick={(e) => e.stopPropagation()}
        role="dialog"
        aria-modal="true"
        aria-labelledby="create-variant-title"
      >
        <div className={styles.header}>
          <h3 id="create-variant-title" className={styles.title}>
            Create Variation
          </h3>
          <button className={styles.closeBtn} onClick={onClose} aria-label="Close">
            <X size={20} />
          </button>
        </div>

        <form className={styles.body} onSubmit={handleSubmit}>
          {attributes.length === 0 ? (
            <p className={styles.emptyText}>
              This product category has no variations. Add variations on the category first.
            </p>
          ) : (
            <>
              <div className={styles.field}>
                <label htmlFor="variation-type">Variation</label>
                <select
                  id="variation-type"
                  value={variationId}
                  onChange={(e) => setVariationId(e.target.value)}
                >
                  {attributes.map((attr) => (
                    <option key={attr.id} value={attr.id}>
                      {attr.name}
                    </option>
                  ))}
                </select>
              </div>

              <div className={styles.field}>
                <label htmlFor="variation-value">Value</label>
                <select
                  id="variation-value"
                  value={optionId}
                  onChange={(e) => setOptionId(e.target.value)}
                  disabled={!selectedVariation}
                >
                  {options.map((option) => (
                    <option key={option.id} value={option.id}>
                      {option.label}
                    </option>
                  ))}
                </select>
              </div>
            </>
          )}

          {label && (
            <div className={styles.preview}>
              <span className={styles.previewLabel}>Preview:</span> {label}
            </div>
          )}

          {isDuplicate && (
            <p className={styles.errorText}>This variation value already exists.</p>
          )}

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

          <div className={styles.actions}>
            <button type="button" className={styles.cancelBtn} onClick={onClose}>
              Cancel
            </button>
            <button
              type="submit"
              className={styles.submitBtn}
              disabled={!canSubmit || attributes.length === 0}
            >
              {isSubmitting ? 'Creating...' : 'Create'}
            </button>
          </div>
        </form>
      </div>
    </div>
  ,
  document.body,
  )
}
