import { useEffect, useState} from "react";
import './App.css';
import Header from "./components/Header";
import Body from "./components/Body";
import {getQuestion, getScoreboard, getReset} from "./components/api";

function App()  {
  const [timeLeft, setTimeLeft] = useState(10*1000);
  const [question, setQuestion] = useState('?')
  const [ans1, setAns1] = useState('?')
  const [ans2, setAns2] = useState('?')
  const [ans3, setAns3] = useState('?')
  const [correctans, setCorrectAns] = useState()
  const [correctfield, setCorrectField] = useState()
  const [scoreblue, setScoreBlue] = useState()
  const [scoregreen, setScoreGreen] = useState()
  const [scorered, setScoreRed] = useState()


  const [timerRunning, setTimerRunning] = useState(false);
  const [questionCount, setQuestionCount] = useState(0);
  const [teamsize, setTeamSize] = useState(0);

  useEffect(() => {
    // This function will be executed when the component is loaded
    getReset(setAns1, setAns2, setAns3, setQuestion);
    getScoreboard(setScoreBlue, setScoreGreen, setScoreRed);
  }, []);

  useEffect(() => {
    let timer;
    if (timerRunning && timeLeft > 0) {
      timer = setTimeout(() => {
        setTimeLeft(timeLeft-10);
      }, 10);}
    else if (timeLeft === 0) {
      alert("Zeit ist um !");
      showcorrect();
      getScoreboard(setScoreBlue, setScoreGreen, setScoreRed);
      setTimerRunning(false);
      setTimeLeft(10);
    }
    return () => clearTimeout(timer);

  }, [timeLeft, timerRunning]);

  function formatTime(time) {
    const seconds = Math.floor((time / 1000) % 60).toString().padStart(2, '0');
    return `${seconds} s`;
  }

  const showcorrect = () => {
    alert("Richtiges Feld: " + correctfield + "\nRichtige Antwort: " + correctans)
  }

  const startQuestion = () => {
    if (questionCount <= 5){
      setQuestionCount(questionCount+1)
      getQuestion(setAns1, setAns2, setAns3, setQuestion, setCorrectField, setCorrectAns).then(r => console.log(r))
      setTimeLeft(10*1000);
      setTimerRunning(true);
    }
    else {
      alert("Spiel vorbei !");
      getReset(setAns1, setAns2, setAns3, setQuestion);
    }
  }

  const stopTimer = () => {
    setTimerRunning(false)
    setTimeLeft(10*1000);
  }

  return (<>
    <Header timerRunning={timerRunning} timerContent={formatTime(timeLeft)} questionCount={questionCount} question={question}/>
    <Body startQuestion={startQuestion} timerRunning={timerRunning} stopTimer={stopTimer} setQuestionCount={setQuestionCount}
          setTeamSize={setTeamSize} teamsize={teamsize}
        ans2={ans2} ans3={ans3} ans1={ans1}
        scoreblue={scoreblue} scorered={scorered} scoregreen={scoregreen}
          setScoreGreen={setScoreGreen} setScoreRed={setScoreRed} setScoreBlue={setScoreBlue}
          setAns3={setAns3} setAns1={setAns1} setAns2={setAns2} setQuestion={setQuestion}
    />
    </>
  );
}

export default App;
