import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { useProductTypes } from '../../product-types/hooks/useProductTypes'

const GLOBAL_VALUE = '__global__'
const ALL_VALUE = '__all__'

interface ProductTypeSelectProps {
  /** Current selected productTypeId. null = "Global", undefined = "All types" (filter mode) */
  value: number | null | undefined
  /** Called with null for "Global (todos los tipos)", undefined for "All types", or id */
  onValueChange: (value: number | null | undefined) => void
  /** If true — show an "All types" option (undefined) for filter use-case */
  showAllOption?: boolean
  /** Label for "all" option */
  allOptionLabel?: string
  /** Label for global/null option */
  globalOptionLabel?: string
  placeholder?: string
  disabled?: boolean
  'aria-label'?: string
}

/**
 * ProductTypeSelect — renders a shadcn Select populated with active ProductTypes.
 *
 * - In "filter" mode (showAllOption=true): adds an "All types" option that returns undefined
 * - Always includes a "Global (todos los tipos)" option that returns null
 * - Product types come from GET /api/v1/product-types with activo=true
 */
export function ProductTypeSelect({
  value,
  onValueChange,
  showAllOption = false,
  allOptionLabel = 'Todos los tipos',
  globalOptionLabel = 'Global (todos los tipos)',
  placeholder = 'Seleccioná un tipo de producto',
  disabled = false,
  'aria-label': ariaLabel,
}: ProductTypeSelectProps) {
  const { data } = useProductTypes({ activo: true, pageSize: 200 })
  const productTypes = data?.items ?? []

  function toSelectValue(v: number | null | undefined): string {
    if (v === undefined) return ALL_VALUE
    if (v === null) return GLOBAL_VALUE
    return String(v)
  }

  function fromSelectValue(sv: string): number | null | undefined {
    if (sv === ALL_VALUE) return undefined
    if (sv === GLOBAL_VALUE) return null
    return Number(sv)
  }

  return (
    <Select
      value={toSelectValue(value)}
      onValueChange={(sv) => onValueChange(fromSelectValue(sv))}
      disabled={disabled}
    >
      <SelectTrigger aria-label={ariaLabel ?? placeholder}>
        <SelectValue placeholder={placeholder} />
      </SelectTrigger>
      <SelectContent>
        {showAllOption && (
          <SelectItem value={ALL_VALUE}>{allOptionLabel}</SelectItem>
        )}
        <SelectItem value={GLOBAL_VALUE}>{globalOptionLabel}</SelectItem>
        {productTypes.map((pt) => (
          <SelectItem key={pt.id} value={String(pt.id)}>
            {pt.nombre}
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  )
}
