import "./App.css";
import { useEffect, useState } from "react";
import textRU from "./utils/textRU";
import textEN from "./utils/textEN";
import { Route, Switch, useHistory, useParams } 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 MainApi from "./utils/api";

function App() {
  const [language, setLanguage] = useState<string>("");
  const [text, setText] = useState(textRU);
  const [data, setData] = useState<any>();
  const [cards, setCards] = useState<any>([]);
  const [visible, setVisible] = useState({
    popup1: true,
    popup2: false,
  });
  const [card, setCard] = useState({});


  const savedLanguage = localStorage.getItem("savedLang");
  const history = useHistory();

  const api = new MainApi("http://192.168.1.115:3001");

  useEffect(() => {
    api.getRC().then((res: any) => {
      setCards(res);
    });
  }, []);

  const handleCards = (item: any) => {
    console.log(card)
    history.push("/connect-page");
    setCard({ title: item.title, img: item.image.logo });
    localStorage.setItem('card', JSON.stringify({ title: item.title, img: item.image.logo }))
  };

  const handleCreateSession = (name: string) => {
    api
      .createSession(name)
      .then((res: any) => {
        if (res.msg === "SESSION_CREATED") {
          handleDataSession({
            link: res.link,
            code: res.connection_code,
          });
        } else {
          throw new Error();
        }
      })
      .catch((e: any) => {
        alert(e);
      });
  };


  console.log(data)

  const handleDataSession = (data: any) => {
    setData({ link: data.link, code: data.code });
    history.push(`/stream/${data.code}`);
    localStorage.setItem('data', JSON.stringify({ link: data.link, code: data.code }))
  };

  const handleConnectSession = (code: string) => {
    api
      .connectSession(code)
      .then((res: any) => {
        handleDataSession({
          link: res.connection_link,
          code: code,
        });
      })
      .catch((e: any) => {
        alert(e);
      });
  };


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







  useEffect(() => {
    if (savedLanguage !== null) {
      setSavedLanguage();
    } else {
      setInitialLanguage();
    }
  }, []);

  function setSavedLanguage() {
    if (savedLanguage === "RU") {
      setLanguage("RU");
      localStorage.setItem("lang", "RU");
      setText(textRU);
    } else if (savedLanguage === "EN") {
      setLanguage("EN");
      localStorage.setItem("lang", "EN");
      setText(textEN);
    }
  }

  function setInitialLanguage() {
    if (window.navigator.language === "ru") {
      setLanguage("RU");
      localStorage.setItem("lang", "RU");
      setText(textRU);
    } else {
      setLanguage("EN");
      setText(textEN);
    }
  }

  function changeLanguage(language: string) {
    if (language === "RU") {
      setLanguage(language);
      setText(textRU);
      localStorage.setItem("savedLang", "RU");
      localStorage.setItem("lang", "RU");
    } else {
      setLanguage("EN");
      localStorage.setItem("lang", "EN");
      localStorage.setItem("savedLang", "EN");
      setText(textEN);
    }
  }

  return (
    <Switch>
      <Route exact path="/">
        <Header
          text={text.footer}
          language={language}
          changeLanguage={changeLanguage}
        ></Header>
        <div className="main">
          <h3 className="demos__tittle">{text.demos.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
              text={text.footer}
              language={language}
              changeLanguage={changeLanguage}
            ></Header>
            <div className="content__container">
              <Main
                visible={visible}
                setVisible={setVisible}
                onConnectSession={handleConnectSession}
                onCreateSession={handleCreateSession}
                data={card}
                text={text}
              ></Main>
            </div>
          </div>
        </div>
      </Route>
      <Route exact path="/stream/:id">
        <PlayerComponent closeStream={closeStream} onConnectSession={handleConnectSession}
          data={data}></PlayerComponent>
      </Route>
    </Switch>
  );
}

export default App;
