import { useEffect, useState } from 'react'
import { createPortal } from 'react-dom'
import { X } from 'lucide-react'
import { ApiError } from '../lib/api'
import {
  updateStoreItemDiscounts,
  type StoreItem,
} from '../services/storeItemService'
import { formatIrtInput, parseIrtInput } from '../utils/irtPrice'
import { createId } from '../utils/id'
import { StoreItemPrice } from './StoreItemPrice'
import modalStyles from './VariationsModal.module.css'
import rowStyles from './CreateStoreItemsModal.module.css'

interface StoreItemDiscountModalProps {
  open: boolean
  productTitle: string
  items: StoreItem[]
  onClose: () => void
  onSaved?: (items: StoreItem[]) => void
}

interface DiscountDraftRow {
  id: string
  itemId: string
  label: string
  price: number | null
  discountedPrice: string
}

const ANIMATION_MS = 220

export function StoreItemDiscountModal({
  open,
  productTitle,
  items,
  onClose,
  onSaved,
}: StoreItemDiscountModalProps) {
  const [mounted, setMounted] = useState(open)
  const [closing, setClosing] = useState(false)
  const [rows, setRows] = useState<DiscountDraftRow[]>([])
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [error, setError] = useState('')

  useEffect(() => {
    if (open) {
      setMounted(true)
      setClosing(false)
      setRows(
        items.map((item) => ({
          id: createId(),
          itemId: item.id,
          label: item.label,
          price: item.price,
          discountedPrice:
            item.discountedPrice !== null
              ? formatIrtInput(String(item.discountedPrice))
              : '',
        })),
      )
      setError('')
    } else if (mounted) {
      setClosing(true)
      const timer = setTimeout(() => {
        setMounted(false)
        setClosing(false)
      }, ANIMATION_MS)
      return () => clearTimeout(timer)
    }
  }, [open, mounted, items])

  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 || items.length === 0) return null

  const productId = items[0]?.productId ?? ''

  const canSubmit =
    !isSubmitting &&
    rows.every((row) => {
      const discounted = parseIrtInput(row.discountedPrice)
      if (discounted === null) return true
      if (row.price === null) return false
      return discounted < row.price
    })

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    if (!canSubmit || !productId) return

    setIsSubmitting(true)
    setError('')

    try {
      const data = await updateStoreItemDiscounts({
        productId,
        items: rows.map((row) => ({
          id: row.itemId,
          discountedPrice: parseIrtInput(row.discountedPrice),
        })),
      })
      onSaved?.(data.items)
      onClose()
    } catch (err) {
      if (err instanceof ApiError) {
        setError(err.message)
      } else {
        setError('Unable to save discounts.')
      }
    } finally {
      setIsSubmitting(false)
    }
  }

  return createPortal(
    <div
      className={`${modalStyles.overlay} ${closing ? modalStyles.overlayOut : modalStyles.overlayIn}`}
      onClick={onClose}
    >
      <div
        className={`${modalStyles.modal} ${rowStyles.modalWide} ${closing ? modalStyles.modalOut : modalStyles.modalIn}`}
        onClick={(e) => e.stopPropagation()}
        role="dialog"
        aria-modal="true"
        aria-labelledby="store-discount-title"
      >
        <div className={modalStyles.header}>
          <div>
            <h3 id="store-discount-title" className={modalStyles.title}>
              Set Discounts
            </h3>
            <p className={modalStyles.subtitle}>{productTitle}</p>
          </div>
          <button className={modalStyles.closeBtn} onClick={onClose} aria-label="Close">
            <X size={20} />
          </button>
        </div>

        <form className={modalStyles.body} onSubmit={(e) => void handleSubmit(e)}>
          <div className={rowStyles.discountHeader}>
            <span>Variant</span>
            <span>Regular price</span>
            <span>Discounted price (IRT)</span>
          </div>

          <div className={rowStyles.discountRows}>
            {rows.map((row) => (
              <div key={row.id} className={rowStyles.discountRow}>
                <span className={rowStyles.discountLabel}>{row.label}</span>
                <div className={rowStyles.discountPricePreview}>
                  <StoreItemPrice price={row.price} />
                </div>
                <input
                  type="text"
                  inputMode="numeric"
                  className={rowStyles.compactInput}
                  value={row.discountedPrice}
                  onChange={(e) =>
                    setRows((prev) =>
                      prev.map((entry) =>
                        entry.id === row.id
                          ? { ...entry, discountedPrice: formatIrtInput(e.target.value) }
                          : entry,
                      ),
                    )
                  }
                  placeholder="No discount"
                  disabled={isSubmitting}
                />
              </div>
            ))}
          </div>

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

          <div className={modalStyles.actions}>
            <button
              type="button"
              className={modalStyles.cancelBtn}
              onClick={onClose}
              disabled={isSubmitting}
            >
              Cancel
            </button>
            <button type="submit" className={modalStyles.submitBtn} disabled={!canSubmit}>
              {isSubmitting ? 'Saving…' : 'Save discounts'}
            </button>
          </div>
        </form>
      </div>
    </div>
  ,
  document.body,
  )
}
