/**
 * IndexedCategoryMultiSelect — category picker that only shows categories containing indexed products.
 * Queries GET /woocommerce/indexed-categories instead of raw WooCommerce categories.
 *
 * @package BoostBot
 * @since 1.3.0
 */

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

interface IndexedCategory {
  id: number
  name: string
  slug: string
  count: number
  indexed_count: number
}

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

export function IndexedCategoryMultiSelect({
  selectedIds,
  onChange,
  label,
  language,
}: IndexedCategoryMultiSelectProps) {
  const [categories, setCategories] = useState<IndexedCategory[]>([])
  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: IndexedCategory[] } }>(
          'woocommerce/indexed-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 (
      <div>
        {label && (
          <label className="block text-sm font-medium text-gray-700 mb-2">{label}</label>
        )}
        <div className="rounded-lg border border-amber-200 bg-amber-50 p-4 text-center">
          <p className="text-sm text-amber-800 mb-2">
            {t('No indexed categories found.')}
          </p>
          <Link
            to="/knowledge-base"
            className="inline-flex items-center text-sm font-medium text-blue-600 hover:text-blue-800 hover:underline"
          >
            {t('Go to Knowledge Base')} &rarr;
          </Link>
        </div>
      </div>
    )
  }

  return (
    <div>
      {label && (
        <label className="block text-sm font-medium text-gray-700 mb-2">{label}</label>
      )}

      <div className="flex items-start gap-2 mb-3 p-2.5 rounded-lg bg-blue-50 border border-blue-200 text-xs text-blue-700">
        <Info className="w-3.5 h-3.5 mt-0.5 flex-shrink-0" />
        <span>
          {t('Only categories with indexed products are shown.')}{' '}
          <Link to="/knowledge-base" className="font-medium text-blue-600 hover:underline">
            {t('Knowledge Base')}
          </Link>
        </span>
      </div>

      <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.indexed_count} {t('indexed')})
            </button>
          )
        })}
      </div>
      {selectedIds.length > 0 && (
        <p className="mt-2 text-xs text-gray-500">
          {selectedIds.length} {t('selected')}
        </p>
      )}
    </div>
  )
}
