import { useMemo } from 'react';
import { useOutletContext } from 'react-router-dom';
import { 
  Col,
  Row,
} from 'react-bootstrap';

// components

import Selector from '../../common/formElements/Selector';

// hooks

import useFilteredCompanies from '../useFilteredCompanies';

function useCompanySelector({ 
  accountd,
  active = true,
  errors, 
  inputName = 'companyId', 
  label = 'company', 
  noRow = false,
  onChange, 
  placeholder, 
  register,
  servicd,
  stockd,
}) {

  const { companyData } = useOutletContext(); 

  /* eslint-disable react-hooks/exhaustive-deps */

  const companyNames = useFilteredCompanies({
    accountd,
    active,
    companyData,
    servicd,
    stockd
  }) || {};

  /* eslint-enable react-hooks/exhaustive-deps */
  
  const computedPlaceholder = useMemo(() => {

    return placeholder || (Object.keys(companyNames).length > 1 ? `select ${label.toLowerCase()}` : null);

  }, 
  [
    companyNames, 
    label,
    placeholder, 
  ]);

  if (Object.keys(companyNames).length < 1) { return {}; } // This is a fail-safe to prevent errors when the companyData is not load

  // Return props for the Selector and the JSX for rendering
  
  if (noRow) {

    return {
      companySelector: (
        <Col xs={12} sm={6}>
          <Selector
            errors={errors}
            inputName={inputName}
            label={label}
            onChange={onChange}
            placeholder={computedPlaceholder}
            register={register}
            values={companyNames}
          />
        </Col>
      ),
      companyNames, // Exporting for any other parent logic
    };

} else {

  return {
    companySelector: (
      <Row>
        <Col xs={12} sm={6}>
          <Selector
            errors={errors}
            inputName={inputName}
            label={label}
            onChange={onChange}
            placeholder={computedPlaceholder}
            register={register}
            values={companyNames}
          />
        </Col>
      </Row>
    ),
      companyNames, // Exporting for any other parent logic
    };

  }

}

export default useCompanySelector;