import React from 'react';
import { DropdownSelect, DropdownSelectItem } from '../../DropdownSelect';
import { ButtonSize } from '../../Button/ButtonTypes';

export interface SelectFieldOption {
  id: string | number;
  label: string;
  value: any;
}

export interface SelectFieldProps {
  value?: string | number | null;
  onChange?: (value: any) => void;
  label?: string;
  options: SelectFieldOption[];
  placeholder?: string;
  required?: boolean;
  disabled?: boolean;
  description?: string;
  className?: string;
  size?: ButtonSize;
}

const SelectField: React.FC<SelectFieldProps> = ({
  value,
  onChange,
  label,
  options,
  placeholder = 'Select an option',
  required = false,
  disabled = false,
  description,
  className = '',
  size = 'md'
}) => {
  // Convert options to DropdownSelectItem format
  const items: DropdownSelectItem[] = options.map(opt => ({
    id: opt.id,
    label: opt.label,
    value: opt.value
  }));

  // Find selected item ID from value
  const selectedItemId = value !== null && value !== undefined
    ? options.find(opt => opt.value === value || opt.id === value)?.id ?? null
    : null;

  const handleSelect = (item: DropdownSelectItem | null) => {
    if (onChange) {
      onChange(item ? item.value : null);
    }
  };

  return (
    <div className={className}>
      {label && (
        <div style={{ marginBottom: '8px' }}>
          <label style={{ 
            fontSize: '0.875rem', 
            fontWeight: 500, 
            color: 'var(--color-text)',
            fontFamily: 'var(--font-family)'
          }}>
            {label}
            {required && <span style={{ color: 'var(--color-error)', marginLeft: '4px' }}>*</span>}
          </label>
          {description && (
            <div style={{ 
              fontSize: '0.75rem', 
              color: 'var(--color-primary)', 
              marginTop: '4px',
              fontStyle: 'italic'
            }}>
              {description}
            </div>
          )}
        </div>
      )}
      <DropdownSelect
        items={items}
        selectedItemId={selectedItemId}
        onSelect={handleSelect}
        placeholder={placeholder}
        disabled={disabled}
        size={size}
        variant="primary"
        showClearButton={false}
        minWidth="100%"
      />
    </div>
  );
};

export default SelectField;

