import "./App.css";
import { useEffect, useState } from "react";
import { Route, Switch, useHistory } from "react-router-dom";

import { Header } from "./components/header/header";
import { Demos } from "./components/demos/demos";
import { Main } from "./components/Main/Main";
import { PlayerComponent } from "./components/playerComponent/playerComponent";

import { useAppDispatch, useAppSelector } from "./hooks/redux";
import { fetchCards } from "./store/reducers/ActionCreator";
import { cardSlice } from "./store/reducers/cardSlice";
import { languageSlice } from "./store/reducers/languageSlice";
import { ICards } from "./models/ICards";
import { useTranslation } from "react-i18next";
import cookies from "js-cookie";

const App: React.FC<any> = () => {
  const [visible, setVisible] = useState({
    popup1: true,
    popup2: false,
  });

  const dispatch = useAppDispatch();
  const history = useHistory();
  const { handleCurrentCard } = cardSlice.actions;
  const { handleChangeLanguage } = languageSlice.actions;
  const { cards } = useAppSelector((state) => state.cardReducer);

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

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

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

  const { t } = useTranslation();

  return (
    <Switch>
      <Route exact path="/">
        <Header></Header>
        <div className="main">
          <h3 className="demos__tittle">{t("demo-title")}</h3>
          <div className="demo__container">
            {cards.map((i: any) => (
              <Demos
                onClick={() => handleCards(i)}
                key={i._id}
                item={i}
              ></Demos>
            ))}
          </div>
        </div>
      </Route>
      <Route path="/connect-page">
        <div className="background">
          <div className="blur">
            <Header></Header>
            <div className="content__container">
              <Main visible={visible} setVisible={setVisible}></Main>
            </div>
          </div>
        </div>
      </Route>
      <Route exact path="/stream/:id">
        <PlayerComponent
          dispatch={dispatch}
          closeStream={closeStream}
        ></PlayerComponent>
      </Route>
    </Switch>
  );
};

export default App;
