import { Form } from 'react-bootstrap';
import RequiredField from "./RequiredField";
import { validateUUID } from '../../../services/utils';

function Selector(props) {
  const {
    complex,
    disabled,
    errors,
    inputName, 
    label,
    onChange,  // controlled onChange (if provided)
    value,     // controlled value (if provided)
    placeholder,
    register,
    validationText,
    values
  } = props;

  if (!values) return 'no values';

  // Special case: if this is for companyId, render a hidden input with the default company info.
  const defaultCompanyId = localStorage.getItem('Uniti.defaultCompanyId');
  const defaultCompanyName = localStorage.getItem('Uniti.defaultCompanyName');

  if (validateUUID(defaultCompanyId) && defaultCompanyName && inputName === 'companyId') {
    return (
      <Form.Group className="mb-3">
        <div className="size-65 text-muted mb-2">company</div>
        <div className="mt-3">{defaultCompanyName}</div>
        <input 
          type="hidden" 
          {...(typeof register === 'function' 
                ? register(inputName, { 
                    onChange,
                    value: defaultCompanyId
                  }) 
                : {})} 
        />
      </Form.Group>
    );
  }

  // Safely get registration props if register is provided.
  const regProps = typeof register === 'function' 
    ? register(inputName, { onChange, shouldUnregister: true })
    : {};

  return (
    <Form.Group className="mb-3">
      <div className="size-65 text-muted mb-2">
        {label}
        {errors && (<RequiredField validationText={validationText} />)}
      </div>
      <Form.Select
        className="p-3"
        disabled={disabled}
        {...regProps}
        value={typeof value !== 'undefined' ? value : (regProps.value || "")}
        onChange={(e) => {
          if (onChange) onChange(e);
          if (regProps.onChange) regProps.onChange(e);
        }}
      >
        {placeholder?.length > 0 && (
          <option key="-1" value="">
            {placeholder}
          </option>
        )}
        {values && !complex && Object.entries(values).map((theRow, key) => (
          <option key={key} value={theRow[0]}>
            {theRow[1]}
          </option>
        ))}
        {values && complex && Object.values(values).map((theRow, key) => (
          <option key={key} value={theRow.value}>
            {theRow.label}
          </option>
        ))}
      </Form.Select>
    </Form.Group>
  );
}

export default Selector;