import React from "react";

const SelectField = ({ label, id, name, options, value, onChange, error, required }) => {
  // Convert value to string for comparison with option values
  // Handle both number and string values
  const stringValue = value !== null && value !== undefined && value !== '' ? String(value) : "";
  
  return (
    <div className="form-group">
      <label htmlFor={id || name}>
        {label}
        {required && <span className="text-danger"> *</span>}
      </label>
      <select
        id={id || name}
        name={name}
        className={`form-control ${error ? 'is-invalid' : ''}`}
        value={stringValue}
        onChange={onChange}
      >
        <option value="">Select {label.toLowerCase()}...</option>
        {options && options.length > 0 ? (
          options.map((option) => (
            <option key={option.value} value={String(option.value)}>
              {option.label}
            </option>
          ))
        ) : (
          <option value="" disabled>No options available</option>
        )}
      </select>
      {error && (
        <div className="invalid-feedback">{error}</div>
      )}
    </div>
  );
};

export default SelectField;