import React, { useEffect } from 'react';
import { inject, observer } from 'mobx-react';
import { useRouter } from 'next/router';
import MobileSignup from 'store/mobileSignup';
import { SignupStep } from 'store/signupSteps';
import UI from 'store/ui';
import { IContext } from 'typings/context';
import { isCompany, signupScroll } from 'utils/helpers';

import LayoutWrapper from '../../pages/farsimi/components/LayoutWrapper';
import { findCorrespondingStepContent } from '../../pages/farsimi/kaupa/StepSetup';
import Authentication from '../../store/authentication';
import { useCustomerLazyQuery, useIsEligibleForNetNetLazyQuery } from '../../typings/graphql';

type SignupProps = {
  mobileSignup: MobileSignup;
  authentication: Authentication;
  ui: UI;
  steps: Array<SignupStep>;
  type: string;
};
const SignupContainer = ({ mobileSignup, ui, steps, type, authentication }: SignupProps) => {
  const router = useRouter();
  const step = router.query.step;
  const customerId = authentication?.customerId;
  const hasCookieState = mobileSignup.getFromCookie();
  const [isEligible] = useIsEligibleForNetNetLazyQuery();

  const [getCustomer] = useCustomerLazyQuery({
    onCompleted: (data) => {
      if (data?.customer?.nationalId) {
        mobileSignup.setIsCompany(isCompany(data?.customer?.nationalId));
      }
    },
  });

  const isEligibleForNetNet = async (): Promise<boolean> => {
    if (!customerId) return false;
    const { data } = await isEligible({
      variables: {
        input: {
          id: customerId,
        },
      },
    });

    return !!data?.isEligibleForNetNet;
  };

  useEffect(() => {
    ui.setIsHiddenFooter(true);
    mobileSignup.fetchAllProducts();
    if (hasCookieState) {
      if (mobileSignup.secondaryVariant.includes('med-heimanet')) {
        (async () => {
          const isEligible = await isEligibleForNetNet();
          mobileSignup.setIsEligibleForNetNet(isEligible);
          if (isEligible) {
            router.push(`/${type}/kaupa?step=${steps[3].id}`, undefined, {
              shallow: true,
            });
          } else {
            router.push(`/${type}/kaupa?step=${steps[2].id}`, undefined, {
              shallow: true,
            });
          }
        })();
      } else {
        router.push(`/${type}/kaupa?step=${steps[3].id}`, undefined, {
          shallow: true,
        });
      }
      mobileSignup.clearCookie();
    } else {
      router.push(`/${type}/kaupa?step=${steps[0].id}`, undefined, {
        shallow: true,
      });
    }
  }, []);

  useEffect(() => {
    if (step) {
      if (typeof step === 'string') {
        // Remove smooth scroll when user is coming back from authentication
        signupScroll(`#${step}`, hasCookieState ? true : false);
      }
    }
  }, [step]);

  useEffect(() => {
    if (!authentication.isStaff && customerId) {
      getCustomer({
        variables: { input: { id: customerId } },
      });
    }
  }, [customerId]);

  return (
    <LayoutWrapper image="https://images.ctfassets.net/j5d5y4z9f7ki/4Jxfhb9O6Gukm9iiatm1ut/2eb32063fd5a63376cf720f6c27b78be/2db0b4974a1bd84423a18970a5b7becfd0ba02b2.jpg">
      {steps.map((stepData) => {
        return findCorrespondingStepContent(stepData.id, {
          id: stepData.id,
          title: stepData.title,
        });
      })}
    </LayoutWrapper>
  );
};

SignupContainer.getInitialProps = ({ pathname }: IContext) => {
  return {
    pathname,
    namespacesRequired: ['service'],
  };
};

export default inject('authentication', 'mobileSignup', 'ui')(observer(SignupContainer));
