import { useEffect, useId, useState } from 'react'
import { Check, ChevronLeft, X } from 'lucide-react'
import type { Product, ProductOptionValue } from '../lib/types'
import { formatPriceFa, formatProductPrice } from '../lib/types'
import './ProductOptionsModal.css'

type ProductOptionsModalProps = {
  open: boolean
  product: Product
  quantity: number
  onClose: () => void
  onConfirm: (options: ProductOptionValue[]) => void
}

function optionLabel(option: ProductOptionValue) {
  const flavor = option.flavor?.nameFa?.trim()
  if (flavor && option.amount) return `${flavor} — ${option.amount}`
  return flavor || option.amount || 'گزینه'
}

export default function ProductOptionsModal({
  open,
  product,
  quantity,
  onClose,
  onConfirm,
}: ProductOptionsModalProps) {
  const titleId = useId()
  const [selectedIds, setSelectedIds] = useState<string[]>([])
  const options = product.options ?? []

  useEffect(() => {
    if (!open) return
    setSelectedIds([])
  }, [open, product.id])

  useEffect(() => {
    if (!open) return
    function onKey(event: KeyboardEvent) {
      if (event.key === 'Escape') onClose()
    }
    document.addEventListener('keydown', onKey)
    return () => document.removeEventListener('keydown', onKey)
  }, [open, onClose])

  if (!open) return null

  const selected = options.filter((option) => selectedIds.includes(option.id))
  const optionsTotal = selected.reduce((sum, option) => sum + option.price, 0)
  const lineTotal = Math.round((product.price + optionsTotal) * quantity)
  const price = formatProductPrice(product)

  function toggle(optionId: string) {
    setSelectedIds((current) =>
      current.includes(optionId)
        ? current.filter((id) => id !== optionId)
        : [...current, optionId],
    )
  }

  return (
    <div className="options-modal-overlay" onClick={onClose} role="presentation">
      <div
        className="options-modal"
        role="dialog"
        aria-modal="true"
        aria-labelledby={titleId}
        onClick={(event) => event.stopPropagation()}
      >
        <div className="options-modal__header">
          <div>
            <p className="options-modal__eyebrow">Product Options</p>
            <h2 id={titleId} className="options-modal__title">
              {product.nameFa}
            </h2>
            <p className="options-modal__meta">
              {price.amount} تومان / {price.unitLabel}
            </p>
          </div>
          <button type="button" className="options-modal__close" onClick={onClose} aria-label="بستن">
            <X size={18} />
          </button>
        </div>

        <fieldset className="options-modal__fieldset">
          <legend>گزینه‌ها</legend>
          <div className="options-modal__list">
            {options.map((option) => {
              const checked = selectedIds.includes(option.id)
              return (
                <label
                  key={option.id}
                  className={`options-modal__chip${checked ? ' is-active' : ''}`}
                >
                  <input
                    type="checkbox"
                    checked={checked}
                    onChange={() => toggle(option.id)}
                  />
                  <span className="options-modal__check" aria-hidden>
                    {checked ? <Check size={14} strokeWidth={2.25} /> : null}
                  </span>
                  <span className="options-modal__chip-text">
                    <span>{optionLabel(option)}</span>
                    {option.price > 0 && (
                      <span className="options-modal__chip-price">
                        +{formatPriceFa(option.price)} تومان
                      </span>
                    )}
                  </span>
                </label>
              )
            })}
          </div>
        </fieldset>

        <p className="options-modal__preview">
          جمع: {formatPriceFa(lineTotal)} تومان
        </p>

        <div className="options-modal__actions">
          <button type="button" className="options-modal__cancel" onClick={onClose}>
            انصراف
          </button>
          <button
            type="button"
            className="btn-primary"
            onClick={() => onConfirm(selected)}
          >
            افزودن به سبد خرید
            <ChevronLeft size={14} />
          </button>
        </div>
      </div>
    </div>
  )
}
