import React, { useEffect } from "react";
import { useAppSelector } from "./hooks/hooks";
import { RequestCode } from "./features/auth/RequestCode";
import { VerifyCode } from "./features/auth/VerifyCode";
import { ChatWindow } from "./features/chat/ChatWindow";
import { useAppDispatch } from "./hooks/hooks";
import { restoreSession } from "./features/auth/authSlice";
import { fetchChatMessages } from "./features/chat/chatSlice";
import styles from './features/chat/ChatWindow.module.scss';

type AppProps = {
	chatIsOpen: boolean;
};

export default function App({ chatIsOpen }: AppProps) {
	const dispatch = useAppDispatch();
	const { verified, isRestoring, conversationId, codeRequested, email } = useAppSelector((s) => s.auth);
	const { conversationStatus: chatConversationStatus } = useAppSelector((s) => s.chat);


	useEffect(() => {
		dispatch(restoreSession());
	}, [dispatch]);

	useEffect(() => {
		if (!conversationId || !verified) return;
		if (chatConversationStatus === 'closed') return;

		const id = window.setInterval(() => {
			dispatch(fetchChatMessages());
		}, 4000);

		return () => window.clearInterval(id);
	}, [
		conversationId,
		verified,
		chatConversationStatus,
		dispatch
	]);


	// BLOCKER: While checking the session, show nothing.
	// This prevents the "RequestCode" component from flashing.
	if (isRestoring) {
		return <div>Checking session...</div>;
	}

	if (!verified) {
		return (
			<div className={styles.zozoChatGlobalClass}>
				{!codeRequested ? <RequestCode /> : <VerifyCode />}
			</div>
		);
	}
	return <ChatWindow chatIsOpen={chatIsOpen} />;
}
