'use client';

import { useEffect, useRef } from 'react';
import { useAppDispatch, useAppSelector } from '@akinon/next/redux/hooks';
import { setCurrentStep } from '@akinon/next/redux/reducers/checkout';
import { CheckoutStep } from '@akinon/next/types';
import { RootState } from '@theme/redux/store';
import PluginModule, { Component } from '@akinon/next/components/plugin-module';
import { CheckoutStepList } from '@theme/views/checkout/step-list';
import { Summary } from '@theme/views/checkout/summary';
import ShippingStep from '@theme/views/checkout/steps/shipping';
import PaymentStep from '@theme/views/checkout/steps/payment';
import { pushAddPaymentInfo, pushAddShippingInfo } from '@theme/utils/gtm';
import type { CheckoutVariantProps } from '../types';

const MultiStepCheckout = (_props: CheckoutVariantProps) => {
  const { steps, preOrder } = useAppSelector(
    (state: RootState) => state.checkout
  );
  const dispatch = useAppDispatch();
  const initialStepChanged = useRef<boolean>(false);

  useEffect(() => {
    if (steps.shipping.completed && !initialStepChanged.current) {
      dispatch(setCurrentStep(CheckoutStep.Payment));
      initialStepChanged.current = true;
    }
  }, [steps.shipping.completed]); // eslint-disable-line react-hooks/exhaustive-deps

  useEffect(() => {
    if (preOrder && !preOrder.shipping_option) {
      initialStepChanged.current = true;
    }
  }, [preOrder]);

  useEffect(() => {
    if (!preOrder?.basket?.basketitem_set) return;
    const products = preOrder.basket.basketitem_set.map((item) => ({
      ...item.product
    }));
    if (steps.current === CheckoutStep.Shipping) {
      pushAddShippingInfo(products);
    }
    if (steps.current === CheckoutStep.Payment) {
      pushAddPaymentInfo(products, String(preOrder?.payment_option?.name));
    }
  }, [steps.current, preOrder?.payment_option?.name]); // eslint-disable-line react-hooks/exhaustive-deps

  return (
    <PluginModule component={Component.MasterpassProvider}>
      <PluginModule component={Component.MasterpassDeleteConfirmationModal} />
      <PluginModule component={Component.MasterpassOtpModal} />
      <PluginModule component={Component.MasterpassLinkModal} />

      <div className="container flex flex-col flex-wrap w-full px-4 md:px-0">
        <CheckoutStepList />

        <div className="w-full flex flex-wrap">
          <div className="w-full h-fit-content lg:w-2/3">
            {steps.current === CheckoutStep.Shipping && <ShippingStep />}
            {steps.current === CheckoutStep.Payment && <PaymentStep />}
          </div>

          <div className="w-full h-fit-content mt-6 lg:w-1/3 lg:pl-8 lg:mt-0">
            <Summary />
          </div>
        </div>
      </div>
    </PluginModule>
  );
};

export default MultiStepCheckout;
