import React, { Children, ReactNode, useEffect } from 'react';
import { Box, CardBase, IconType, MainButton, Step, StepOverview, Text } from '@nova-hf/ui';
import { MainButtonProps } from '@nova-hf/ui/umd/ts/src/buttons/MainButton/MainButton';
import { MainColorType, ThemeColorType } from '@nova-hf/ui/umd/ts/src/styles/vars.css';
import Layout from 'beta/components/layouts/Layout';
import StepsLayout from 'beta/components/layouts/StepsLayout';
import Steps from 'beta/store/steps';
import { reaction } from 'mobx';
import { inject, observer } from 'mobx-react';
import { useRouter } from 'next/router';
import { useTranslation } from 'utils/i18n';

export type StepChildrenProps = {
  onNext?: () => void;
  onPrev?: () => void;
  color?: ThemeColorType;
  customerId?: string;
  serviceId?: string;
  paymentMethodId?: string;
};

type StepWrapperProps = {
  steps?: Steps;
  children?: ReactNode;
  color?: MainColorType;
  returnUrl?: string;
  childrenBottom?: ReactNode;
  title?: string;
  subTitle?: string;
  icon?: IconType;
  button?: MainButtonProps;
  mainButton?: MainButtonProps;
  isMulti?: boolean;
  totalChecks?: number;
  hasTooltip?: boolean;
};

const StepWrapper = ({
  steps,
  children,
  childrenBottom,
  color,
  returnUrl,
  title,
  subTitle,
  icon,
  button,
  mainButton,
  isMulti,
  totalChecks,
  hasTooltip,
}: StepWrapperProps) => {
  const { t } = useTranslation('steps');
  const router = useRouter();

  const { query, pathname } = router;
  const currentStep = query?.step;
  const customerId = query?.customerId;
  const serviceId = query?.serviceId;
  const paymentMethodId = query?.paymentMethodId;

  useEffect(() => {
    if (currentStep !== '1') {
      steps?.setStep(1);
      if (query.paymentMethodId) {
        router.replace({
          pathname,
          query: {
            step: '1',
            paymentMethodId,
            customerId,
          },
        });
      }
      if (query.serviceId) {
        router.replace({
          pathname,
          query: {
            step: '1',
            serviceId,
            customerId,
          },
        });
      }
    }
    // Update path on step change
    const stepReaction = reaction(
      () => steps?.currentStep,
      (step) => {
        if (query.serviceId) {
          router.replace({
            pathname,
            query: {
              step,
              serviceId,
              customerId,
            },
          });
        }
        if (query.paymentMethodId) {
          router.replace({
            pathname,
            query: {
              step,
              paymentMethodId,
              customerId,
            },
          });
        }
      },
    );

    return () => {
      stepReaction();
      steps?.reset();
    };
  }, []);

  const onBackClick = () => {
    if (steps?.currentStep === 1) {
      steps?.close();
    } else {
      steps?.prev();
    }
  };

  const stepCount =
    Children.toArray(children).map((child) => {
      return child;
    })?.length || 1;

  return (
    <Layout hideFooter hideNavbar>
      <StepsLayout
        returnUrl={returnUrl}
        sideOverviewChildren={
          <StepOverview
            color={color}
            onClose={() => steps?.close()}
            isMulti={isMulti}
            {...(hasTooltip
              ? {
                  tooltip: {
                    children: (
                      <CardBase borderColor="grey200" dottedShadow="none" hasBorder>
                        <Box padding={2}>
                          <Text marginBottom={1} variant="pSmallBold">
                            {t('general.multi')}
                          </Text>
                          <Text marginBottom={1} variant="pXSmallRegular">
                            {t('general.multiInfo')}
                          </Text>
                        </Box>
                      </CardBase>
                    ),
                    placement: 'bottom-end',
                    shouldShowOnHover: true,
                  },
                }
              : {})}
            totalChecks={totalChecks}
            header={{
              title,
              icon,
              descriptionTitle: {
                text: subTitle ?? '',
                isActive: false,
              },
            }}
            backButton={{
              renderAs: 'button',
              colorScheme: color,
              text: t('general.step', {
                currentStep: steps?.currentStep,
                stepCount: stepCount,
              }),
              icon: 'longArrowLeft',
              onClick: () => onBackClick(),
            }}
            stepCount={stepCount}
            currentStep={steps?.currentStep}
            childrenBottom={childrenBottom}
            mainButton={mainButton}
          >
            {!!button?.text && (
              <Box height="100%" padding={3}>
                <MainButton {...button} />
              </Box>
            )}
          </StepOverview>
        }
      >
        {Children.toArray(children).map((child, i) => {
          if (i + 1 !== steps?.currentStep) {
            return null;
          }
          return (
            <Step key={i}>
              {React.isValidElement(child)
                ? React.cloneElement(child as React.ReactElement<StepChildrenProps>, {
                    onNext: () => steps?.next(),
                    onPrev: () => steps?.prev(),
                    color,
                    customerId: customerId as string,
                    serviceId: serviceId as string,
                    paymentMethodId: paymentMethodId as string,
                  })
                : child}
            </Step>
          );
        })}
      </StepsLayout>
    </Layout>
  );
};

export default inject('steps')(observer(StepWrapper));
