import "./App.css";
import "styles/styles.css";

import { useEffect } from "react";
import { Redirect, Route, Switch, useHistory } from "react-router-dom";

import { useTranslation } from "react-i18next";
import cookies from "js-cookie";

import { Header } from "components/shared/Header/Header";
import { Card } from "components/pages/Main/Card/Card";
import { PopupComponent } from "components/pages/ConnectPage/PopupComponent/PopupComponent";
import { PlayerComponent } from "components/pages/Stream/PlayerComponent/PlayerComponent";
import { PlanComponent } from "components/pages/Plan/PlanComponent";

import { useAppDispatch, useAppSelector } from "hooks/redux";
import { fetchCards } from "store/reducers/ActionCreator";
import { cardSlice } from "store/reducers/cardSlice";
import { ICards } from "models/ICards";

const App: React.FC = () => {
  const dispatch = useAppDispatch();
  const history = useHistory();
  const { handleCurrentCard } = cardSlice.actions;
  const { cards, currentCard } = useAppSelector((state) => state.cardReducer);
  const { currentLang } = useAppSelector((state) => state.languageReducer);


  useEffect(() => {
    dispatch(fetchCards(cookies.get("i18next")));
  }, []);

  useEffect(() => {
    dispatch(fetchCards(cookies.get("i18next")));
  }, [currentLang])

  const handleCards = (card: ICards) => {
    dispatch(handleCurrentCard(card));
    history.push("/connect-page");
  };

  const closeStream = () => {
    history.push("/");
  };

  const { t } = useTranslation();

  return (
    <Switch>
      <Route exact path="/">
        <div className="main">
          <h2 className="card-title">{t("demo-title")}</h2>
          <div className="card-container">
            {cards.map((i: ICards) => (
              <Card onClick={() => handleCards(i)} key={i._id} item={i}></Card>
            ))}
          </div>
        </div>
      </Route>
      <Route path="/connect-page">
        {currentCard ? (
          <div className="background">
            <Header></Header>
            <div className="popup-container">
              <div className="content__container">
                <PopupComponent></PopupComponent>
              </div>
            </div>
          </div>
        ) : (
          <Redirect to="/" />
        )}
      </Route>
      <Route exact path="/stream/:id">
        <PlayerComponent closeStream={closeStream}></PlayerComponent>
      </Route>
      <Route path="/plan">
        <Header></Header>
        <div className="popup-container">
          <PlanComponent></PlanComponent>
        </div>
      </Route>
    </Switch>
  );
};

export default App;
