import { useEffect } from "react";
import { AppProvider } from "context";
import {
  Checkout,
  checkoutEvents,
  UserProvider,
  AddressProvider,
} from "@deuna/checkout-core";
import envVariables from "envVariables";
import { CardCreationWidgetProps } from "index";
import { Config } from "interfaces/config";
import { WidgetRudderStack } from "utils";
import guestSteps from "steps/GuestUserSteps";

import authSteps from "./AuthSteps";

export interface CheckoutStepsProps {
  checkoutConfig: Config;
  onEventDispatch?: (event: string, data: any) => void;
}

const CheckoutComponent = ({
  checkoutConfig,
  themeProps,
  handleClose,
  onExit,
}: CardCreationWidgetProps["WidgetComponentProps"]) => {
  useEffect(() => {
    const env = checkoutConfig.env || "staging";
    const rudderStack = new WidgetRudderStack({
      writeKey: envVariables[env].RUDDERSTACK_WRITE_KEY,
      dataPlaneUrl: envVariables[env].RUDDERSTACK_DATA_PLANE_URL,
    });
    checkoutEvents.setEmitters([rudderStack]);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <AppProvider>
      <Checkout
        config={checkoutConfig}
        themeProps={themeProps}
        modules={{ User: UserProvider, Address: AddressProvider }}
        useMemoryRouter
        overrideLayout={{
          LayoutsContainer: {
            $style: {
              width: "430px",
              minHeight: "fit-content",
              borderBottomLeftRadius: "8px",
              borderBottomRightRadius: "8px",
              borderTopRightRadius: "8px",
              borderTopLeftRadius: "8px",
              backgroundColor: "white",
              ["@media screen and (max-width: 768px)"]: {
                width: "100vw",
                borderBottomLeftRadius: "0px",
                borderBottomRightRadius: "0px",
              },
            },
          },
        }}
        steps={({ userContext }) => {
          const isGuest = !userContext.user || userContext.user?.is_guest;

          return isGuest
            ? guestSteps({ handleClose, onExit })
            : authSteps({ handleClose, onExit });
        }}
      />
    </AppProvider>
  );
};

export default CheckoutComponent;
