/**
 * CategoryMultiSelect — reusable button-cloud component for selecting WooCommerce categories.
 * Fetches categories on mount and renders clickable chips.
 *
 * @package BoostBot
 * @since 1.3.0
 */

import { useState, useEffect } from 'react'
import { Loader2 } from 'lucide-react'
import { t } from '@/lib/i18n'
import { apiClient } from '@/api/client'

interface CategoryOption {
  id: number
  name: string
  slug: string
  count: number
}

interface CategoryMultiSelectProps {
  selectedIds: number[]
  onChange: (ids: number[]) => void
  label?: string
  language?: string
}

export function CategoryMultiSelect({
  selectedIds,
  onChange,
  label,
  language,
}: CategoryMultiSelectProps) {
  const [categories, setCategories] = useState<CategoryOption[]>([])
  const [isLoading, setIsLoading] = useState(true)

  useEffect(() => {
    let cancelled = false

    const fetchCategories = async () => {
      setIsLoading(true)
      try {
        const params: Record<string, unknown> = {}
        if (language) params.language = language
        const resp = await apiClient.get<{ data: { categories: CategoryOption[] } }>(
          'woocommerce/categories',
          params,
        )
        if (!cancelled) {
          setCategories(resp?.data?.categories || [])
        }
      } catch {
        if (!cancelled) setCategories([])
      } finally {
        if (!cancelled) setIsLoading(false)
      }
    }

    fetchCategories()
    return () => { cancelled = true }
  }, [language])

  const handleToggle = (catId: number) => {
    const newIds = selectedIds.includes(catId)
      ? selectedIds.filter(id => id !== catId)
      : [...selectedIds, catId]
    onChange(newIds)
  }

  if (isLoading) {
    return (
      <div className="flex items-center gap-2 py-3 text-sm text-gray-500">
        <Loader2 className="w-4 h-4 animate-spin" />
        {t('Loading categories...')}
      </div>
    )
  }

  if (categories.length === 0) {
    return (
      <p className="text-sm text-gray-500 py-2">{t('No categories available')}</p>
    )
  }

  return (
    <div>
      {label && (
        <label className="block text-sm font-medium text-gray-700 mb-2">{label}</label>
      )}
      <div className="flex flex-wrap gap-2">
        {categories.map(cat => {
          const isSelected = selectedIds.includes(cat.id)
          return (
            <button
              type="button"
              key={cat.id}
              onClick={() => handleToggle(cat.id)}
              className={`px-3 py-1.5 rounded-full text-sm transition-colors cursor-pointer ${
                isSelected
                  ? 'bg-purple-600 text-white'
                  : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
              }`}
            >
              {cat.name} ({cat.count})
            </button>
          )
        })}
      </div>
      {selectedIds.length > 0 && (
        <p className="mt-2 text-xs text-gray-500">
          {selectedIds.length} {t('selected')}
        </p>
      )}
    </div>
  )
}
