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

import { useSetInitialValues } from "@hooks/useSetInitialValues";
import { useFetchQuote } from "../hooks/apis/useFetchQuote";
import { ScreenTab, setScreenTab } from "../store/globalSlice";
import type { ReduxStateType } from "../store/types";
import { CompareModal } from "./Compare/CompareModal";
import { Home } from "./Home";
import { InFlight } from "./InFlight";
import { BgGrid } from "./InFlight/BgGrid";
import { RecipientAddressModal } from "./RecipientAddressModal";
import { Review } from "./Review";
import { ActionStatusProvider } from "./Review/ActionStatusProvider";
import { ToastContainer } from "./Toast/ToastContainer";
import { SwapWrap } from "./common/SwapWrap";

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

	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 />
			<CompareModal />
			<ToastContainer />
		</SwapWrap>
	);
};
