import React, { useMemo } from 'react';
import { Select, SelectOption } from '../../ui/Select';
import { useIngredients } from '../../../api/hooks/inventory';
import { useCurrentTenant } from '../../../stores/tenant.store';
import { IngredientResponse } from '../../../api/types/inventory';

interface ProductSelectorProps {
  value?: string;
  onChange: (productId: string, product?: IngredientResponse) => void;
  placeholder?: string;
  error?: string;
  disabled?: boolean;
  excludeIds?: string[];
  label?: string;
  isRequired?: boolean;
}

export function ProductSelector({
  value,
  onChange,
  placeholder = 'Select product...',
  error,
  disabled = false,
  excludeIds = [],
  label = 'Product',
  isRequired = false,
}: ProductSelectorProps) {
  const currentTenant = useCurrentTenant();

  // Fetch all active ingredients
  const { data: ingredients, isLoading } = useIngredients(
    currentTenant?.id || '',
    { is_active: true },
    { enabled: !!currentTenant?.id }
  );

  // Convert ingredients to select options
  const productOptions: SelectOption[] = useMemo(() => {
    if (!ingredients) return [];

    return ingredients
      .filter(ingredient => !excludeIds.includes(ingredient.id))
      .map(ingredient => ({
        value: ingredient.id,
        label: ingredient.name,
        description: ingredient.category
          ? `${ingredient.category}${ingredient.subcategory ? ` - ${ingredient.subcategory}` : ''}`
          : undefined,
        group: ingredient.category || 'Other',
      }))
      .sort((a, b) => {
        // Sort by group first, then by label
        const groupCompare = (a.group || '').localeCompare(b.group || '');
        return groupCompare !== 0 ? groupCompare : a.label.localeCompare(b.label);
      });
  }, [ingredients, excludeIds]);

  const handleChange = (selectedValue: string | number | Array<string | number>) => {
    if (typeof selectedValue === 'string') {
      const selectedProduct = ingredients?.find(ing => ing.id === selectedValue);
      onChange(selectedValue, selectedProduct);
    }
  };

  return (
    <Select
      label={label}
      value={value}
      onChange={handleChange}
      options={productOptions}
      placeholder={placeholder}
      error={error}
      disabled={disabled || isLoading}
      loading={isLoading}
      searchable
      clearable
      isRequired={isRequired}
      isInvalid={!!error}
      loadingMessage="Loading products..."
      noOptionsMessage="No products available"
      size="md"
      variant="outline"
    />
  );
}
