import { useEffect, useMemo, useState } from 'react'
import { createPortal } from 'react-dom'
import { X } from 'lucide-react'
import { ApiError } from '../lib/api'
import { listProductCategories, mapProductCategoryToUi } from '../services/productCategoryService'
import {
  StoreItemMultiSearchSelect,
  type StoreItemSearchOption,
} from './StoreItemMultiSearchSelect'
import modalStyles from './VariationsModal.module.css'
import styles from './PickStoreSpecialItemsModal.module.css'

interface PickWebsiteCategoriesModalProps {
  open: boolean
  groupTitle: string
  existingCategoryIds: string[]
  onClose: () => void
  onConfirm: (categoryIds: string[]) => void
  isSubmitting?: boolean
}

const ANIMATION_MS = 220

export function PickWebsiteCategoriesModal({
  open,
  groupTitle,
  existingCategoryIds,
  onClose,
  onConfirm,
  isSubmitting = false,
}: PickWebsiteCategoriesModalProps) {
  const [mounted, setMounted] = useState(open)
  const [closing, setClosing] = useState(false)
  const [options, setOptions] = useState<StoreItemSearchOption[]>([])
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState('')
  const [selectedIds, setSelectedIds] = useState<string[]>([])

  const existingSet = useMemo(() => new Set(existingCategoryIds), [existingCategoryIds])

  useEffect(() => {
    if (open) {
      setMounted(true)
      setClosing(false)
      setSelectedIds([])
      setError('')
    } else if (mounted) {
      setClosing(true)
      const timer = setTimeout(() => {
        setMounted(false)
        setClosing(false)
      }, ANIMATION_MS)
      return () => clearTimeout(timer)
    }
  }, [open, mounted])

  useEffect(() => {
    if (!open) return

    const controller = new AbortController()
    void loadOptions(controller.signal)
    return () => controller.abort()
  }, [open, existingCategoryIds])

  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])

  async function loadOptions(signal?: AbortSignal) {
    setIsLoading(true)
    setError('')

    try {
      const items = await listProductCategories(signal)
      const nextOptions = items
        .map(mapProductCategoryToUi)
        .map((category) => ({
          id: category.id,
          title: category.nameEn,
          nameFa: category.nameFa,
          image: null,
        }))
        .filter((option) => !existingSet.has(option.id))

      setOptions(nextOptions)
    } catch (err) {
      if (err instanceof DOMException && err.name === 'AbortError') return
      if (err instanceof ApiError) {
        setError(err.message)
      } else {
        setError('Unable to load categories.')
      }
    } finally {
      setIsLoading(false)
    }
  }

  function toggleSelection(categoryId: string) {
    setSelectedIds((prev) =>
      prev.includes(categoryId) ? prev.filter((id) => id !== categoryId) : [...prev, categoryId],
    )
  }

  function handleConfirm() {
    if (selectedIds.length === 0) return
    onConfirm(selectedIds)
  }

  if (!mounted) return null

  return createPortal(
    <div
      className={`${modalStyles.overlay} ${closing ? modalStyles.overlayOut : modalStyles.overlayIn}`}
      onClick={(e) => e.target === e.currentTarget && onClose()}
      role="presentation"
    >
      <div
        className={`${modalStyles.modal} ${styles.modalWide} ${closing ? modalStyles.modalOut : modalStyles.modalIn}`}
        role="dialog"
        aria-modal="true"
        aria-labelledby="pick-categories-title"
      >
        <div className={modalStyles.header}>
          <div>
            <h2 id="pick-categories-title" className={modalStyles.title}>
              Add to {groupTitle}
            </h2>
            <p className={modalStyles.subtitle}>Select product categories to feature in this group.</p>
          </div>
          <button type="button" className={modalStyles.closeBtn} onClick={onClose} aria-label="Close">
            <X size={20} />
          </button>
        </div>

        <div className={modalStyles.body}>
          {error && <p className={styles.error}>{error}</p>}

          {isLoading ? (
            <p className={styles.empty}>Loading categories...</p>
          ) : options.length === 0 ? (
            <p className={styles.empty}>All categories are already in this group.</p>
          ) : (
            <StoreItemMultiSearchSelect
              options={options}
              selectedIds={selectedIds}
              onToggle={toggleSelection}
              placeholder="Type 3+ characters to search categories"
              disabled={isSubmitting}
            />
          )}

          <div className={styles.footer}>
            <button type="button" className={styles.cancelBtn} onClick={onClose} disabled={isSubmitting}>
              Cancel
            </button>
            <button
              type="button"
              className={styles.confirmBtn}
              onClick={handleConfirm}
              disabled={isSubmitting || selectedIds.length === 0}
            >
              {isSubmitting
                ? 'Adding...'
                : `Add ${selectedIds.length || ''} categor${selectedIds.length === 1 ? 'y' : 'ies'}`}
            </button>
          </div>
        </div>
      </div>
    </div>
  ,
  document.body,
  )
}
