import { useEffect, useMemo, useState } from 'react'
import { createPortal } from 'react-dom'
import { X } from 'lucide-react'
import { useLocale } from '@meshkee/dashboard-ui'
import { useT } from '../i18n/useT'
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 t = useT()
  const { locale } = useLocale()
  const isFa = locale === 'fa'
  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(t('website.specialCategories.pickErrorLoad'))
      }
    } 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)
  }

  function confirmLabel() {
    if (isSubmitting) return t('website.adding')
    if (selectedIds.length === 1) return t('website.pick.addOneCategory')
    return t('website.pick.addCategories', { count: selectedIds.length })
  }

  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"
        lang={isFa ? 'fa' : 'en'}
        dir={isFa ? 'rtl' : 'ltr'}
      >
        <div className={modalStyles.header}>
          <div>
            <h2 id="pick-categories-title" className={modalStyles.title}>
              {t('website.pick.addTo', { title: groupTitle })}
            </h2>
            <p className={modalStyles.subtitle}>{t('website.specialCategories.pickSubtitle')}</p>
          </div>
          <button
            type="button"
            className={modalStyles.closeBtn}
            onClick={onClose}
            aria-label={t('common.close')}
          >
            <X size={20} />
          </button>
        </div>

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

          {isLoading ? (
            <p className={styles.empty}>{t('website.specialCategories.pickLoading')}</p>
          ) : options.length === 0 ? (
            <p className={styles.empty}>{t('website.specialCategories.pickEmpty')}</p>
          ) : (
            <StoreItemMultiSearchSelect
              options={options}
              selectedIds={selectedIds}
              onToggle={toggleSelection}
              placeholder={t('website.specialCategories.pickSearch')}
              disabled={isSubmitting}
            />
          )}

          <div className={styles.footer}>
            <button type="button" className={styles.cancelBtn} onClick={onClose} disabled={isSubmitting}>
              {t('products.form.cancel')}
            </button>
            <button
              type="button"
              className={styles.confirmBtn}
              onClick={handleConfirm}
              disabled={isSubmitting || selectedIds.length === 0}
            >
              {confirmLabel()}
            </button>
          </div>
        </div>
      </div>
    </div>
  ,
  document.body,
  )
}
