import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useAccount } from "wagmi";

import { useQuote } from "@hooks/apis/common/quote/useQuote";
import { useRegisterEventHandlers } from "@hooks/useRegisterEventHandlers";
import { useSetInitialValues } from "@hooks/useSetInitialValues";
import { ScreenTab, setScreenTab } from "../store/globalSlice";
import type { ReduxStateType } from "../store/types";
import { useHistoryCleanup } from "./History/useHistoryCleanup";
import { Home } from "./Home";
import { InFlight } from "./InFlight";
import { BgGrid } from "./InFlight/layout/BgGrid";
import { RecipientAddressModal } from "./RecipientAddressModal";
import { Review } from "./Review";
import { ActionStatusProvider } from "./Review/Auto/ActionStatusProvider";
import { ToastContainer } from "./Toast/ToastContainer";
import { SwapWrap } from "./common/SwapWrap";

export const Swap = () => {
	useQuote();
	useSetInitialValues(); // to set values from the config
	useRegisterEventHandlers();
	useHistoryCleanup();

	const { address, isDisconnected } = useAccount();
	const dispatch = useDispatch();

	const screenTab = useSelector(
		(state: ReduxStateType) => state.global.screenTab,
	);

	// Resets to homescreen on account change & disconnection
	useEffect(() => {
		if (dispatch && (isDisconnected || address)) {
			dispatch(setScreenTab(ScreenTab.HOME));
		}
	}, [address, dispatch, isDisconnected]);

	return (
		<SwapWrap>
			{screenTab === ScreenTab.HOME && <Home />}
			{screenTab === ScreenTab.REVIEW && (
				<ActionStatusProvider>
					<Review />
				</ActionStatusProvider>
			)}
			{screenTab === ScreenTab.INFLIGHT && (
				<div>
					<BgGrid />
					<InFlight />
				</div>
			)}

			<RecipientAddressModal />
			<ToastContainer />
		</SwapWrap>
	);
};
