/* eslint-disable indent */

import React from 'react';
import { Redirect } from 'react-router-dom';
import { useGetVendorAgreementQuery } from 'src/queries/get-vendor-agreement';
import { useTransferWiseProfileQuery } from 'src/queries/tw-profile';
import {
    OPT_IN_PREFERENCE_TYPE_ID_COLLABORATOR_PAYOUTS,
    TW_PROFILE_STATUS_VERIFIED,
} from 'src/constants';
import { baseUrl } from 'src/urls/collaborator';
import useHasAccessToPayments from './use-has-access-to-payments';

const withPaymentsActivated = <P extends object>(
    Component: React.ComponentType<P>
) => (props: P) => {
    const hasAccessToPayments = useHasAccessToPayments();

    const {
        data: { getVendorAgreement: payoutsAgreement } = {},
        loading: payoutsAgreementLoading,
    } = useGetVendorAgreementQuery(OPT_IN_PREFERENCE_TYPE_ID_COLLABORATOR_PAYOUTS);

    const {
        data: { transferWiseProfile } = {},
        loading: transferWiseProfileLoading,
    } = useTransferWiseProfileQuery();

    const loading = payoutsAgreementLoading || transferWiseProfileLoading;

    const activated = Boolean(payoutsAgreement)
        && Boolean(transferWiseProfile)
        && transferWiseProfile?.status === TW_PROFILE_STATUS_VERIFIED;

    if (!hasAccessToPayments || (!loading && !activated))
        return <Redirect to={ baseUrl() } />;

    if (loading)
        return null;

    return <Component { ...props } />;
};

export default withPaymentsActivated;
