import ButtonKDS from '../Buttons/ButtonKDS';
import { getElements } from '../utils/helperFunctions';
import { ButtonsContainerProps } from '../utils/types';
import { ButtonsWrapper } from './style';
import { useTranslation } from 'react-i18next';

const showProcessedButtons = (toDone: string[]): boolean =>
  toDone && toDone.length > 0;

const showDeliveredButton = (allDone: string[], toDone: string[]): boolean =>
  allDone && allDone.length > 0 && toDone && toDone.length === 0;

const ButtonsContainer = (props: ButtonsContainerProps): JSX.Element => {
  const {
    isZoomIn,
    setIsZoomIn,
    lines,
    callOrderApi,
    orderId,
    authProvider,
    kdsDeviceConfigs,
  } = props;
  const { toDone, allDone, toPrepare, toConfirm } = getElements(lines);
  const { t } = useTranslation();

  const setOrderStatus = async (type: any, elements: any[]) => {
    try {
      const { token } = await authProvider();
      callOrderApi(
        orderId,
        type,
        token,
        elements,
        'KDS_STAGE_DONE' in kdsDeviceConfigs
          ? kdsDeviceConfigs.KDS_STAGE_DONE
          : null
      );
    } catch (error) {
      console.warn(error);
    }
  };

  return (
    <ButtonsWrapper>
      {toConfirm.length > 0 && (
        <ButtonKDS
          text={t('OS.KDS.Card.Button.CancelPreparing')}
          callOrderApi={() => setOrderStatus('confirm', toConfirm)}
        />
      )}
      {toPrepare.length > 0 && (
        <ButtonKDS
          text={t('OS.KDS.Card.Button.PrepareAll')}
          callOrderApi={() => setOrderStatus('prepare', toPrepare)}
        />
      )}

      {showProcessedButtons(toDone) && (
        <>
          <ButtonKDS
            text={t('OS.KDS.Card.Button.DoneAll')}
            isIcon={true}
            callOrderApi={() => setOrderStatus('prepared', toDone)}
          />
          {isZoomIn ? (
            <ButtonKDS
              type="white"
              text={t('OS.KDS.Card.Button.Minimize')}
              setIsZoomIn={setIsZoomIn}
              isZoomIn={isZoomIn}
            />
          ) : (
            <ButtonKDS
              type="white"
              isIcon={true}
              text={t('OS.KDS.Card.Button.Enlarge')}
              setIsZoomIn={setIsZoomIn}
              isZoomIn={isZoomIn}
            />
          )}
        </>
      )}
      {showDeliveredButton(allDone, toDone) && (
        <ButtonKDS
          text={t('OS.KDS.Card.Button.Delivered')}
          type="large"
          callOrderApi={() => setOrderStatus('deliver', [])}
        />
      )}
    </ButtonsWrapper>
  );
};

export default ButtonsContainer;
