import React, {ReactNode} from 'react';
import {useState} from 'react';
import {PowerSchoolData, Section, Page} from "./interfaces";
import {Container} from "react-bootstrap";
import TeacherInterface from "./views/Teachers";
import Header from "./components/navigation/Header";
import Footer from "./components/navigation/Footer";
import LoginInterface from "./views/Login";
import SectionsInterface from "./views/Sections";
import DashboardInterface from "./views/Dashboard";
import ScheduleInterface from "./views/Schedule";
import GradesInterface from "./views/Grades";
import {globalContext} from "./contexts";

export const App = () => {
    // State holding the PowerSchool data object. This has everything that needs to be displayed
    const [psData, setPsData] = useState<PowerSchoolData | null>(null);

    // States for page routing
    const [currentPage, setCurrentPage] = useState<Page>(Page.login);
    const [selectedSection, setSelectedSection] = useState<Section>();

    // Set page to login if no data is loaded
    if (psData === null && currentPage !== Page.login) {
        setCurrentPage(Page.login)
    }

    // Redirect from login to dashboard if data has been loaded
    if (psData !== null && currentPage === Page.login) {
        setCurrentPage(Page.dashboard)
    }

    // If the grads page has been selected but no section has been defined, redirect to the sections page to avoid an error
    if (currentPage === Page.sectionGrades && selectedSection === undefined) {
        setCurrentPage(Page.sections)
    }

    // Mapping the page enum to page components
    const router: { [K in Page]: ReactNode } = {
        [Page.login]: <LoginInterface setPsData={setPsData}/>,
        [Page.dashboard]: <DashboardInterface/>,
        [Page.sections]: <SectionsInterface/>,
        // @ts-ignore
        [Page.sectionGrades]: <GradesInterface section={selectedSection}/>,
        [Page.schedule]: <ScheduleInterface/>,
        [Page.teachers]: <TeacherInterface/>
    };

    return (
        <>
            {/* @ts-ignore */}
            <globalContext.Provider value={{psData: psData, currentPage: currentPage, setCurrentPage: setCurrentPage, setCurrentSection: setSelectedSection}}>
                <Header signOutFunction={() => {
                    setPsData(null);
                    setCurrentPage(Page.login);
                }}/>
                <Container className="App mb-4 flex-shrink-0">
                    {router[currentPage]}
                </Container>
                <Footer/>
            </globalContext.Provider>
        </>
    );
};

export default App;