import React, { ReactElement, useEffect, useState } from 'react';
import {
  BrowserRouter as Router,
  Route,
  Switch
} from 'react-router-dom';
import { CaloriesList } from '../components/caloriesList/CaloriesList';
import { AppContext } from './AppContext';
import { PageFooter } from './pageFooter/PageFooter';
import { PageHeader } from './pageHeader/PageHeader';

import './app.css';

const AppContextProvider = AppContext.Provider;
const storedCalories = JSON.parse(localStorage.getItem('calorieItems') || '[]');

function App (): ReactElement {
  const [calorieItems, setCalorieItems] = useState<CalorieItems>(storedCalories);
  const [selectedDate, setSelectedDate] = useState<number>(Date.now());

  useEffect(() => {
    localStorage.setItem('calorieItems', JSON.stringify(calorieItems));
  });

  return (
    <AppContextProvider value={{calorieItems, setCalorieItems, selectedDate, setSelectedDate}}>
      <PageHeader />

      <main id="pageContent">
        <Router>
          <Switch>
            <Route path="/">
              <CaloriesList />
            </Route>
          </Switch>
        </Router>
      </main>

      <PageFooter />
    </AppContextProvider>
  );
}

export {
  App
};
