import { Avatar, Box, Button, Grid, styled } from "@mui/material";
import React from "react";
import { useLocation, useNavigate, useParams } from "react-router-dom";
import QuestionService from "../services/istar/QuestionService";
import UserResponseService from "../services/istar/UserResponseService";

const FlexBox = styled(Grid)(() => ({
  //   container,
  direction: "column",
  justifyContent: "center",
  alignItems: "center",
}));

const buttonStyle = {
  backgroundColor: "#F7EBFC",
  color: "#6F1EBC",
  borderColor: "#6F1EBC",
  borderRadius: "2rem",
  width: "12rem",
  height: "4rem",
  marginBottom: "1rem",
};

const bottomButton = {
  color: "#6F1EBC",
  fontSize: "1rem",
  fontWeight: "bold",
};

const Questions = () => {
  const navigate = useNavigate();
  const params = useParams();
  const location = useLocation();
  console.log("LOCAOIN: ", location);
  const [firstQuest, setFirstQuest] = React.useState({});
  const [currentQuest, setCurrentQuest] = React.useState({});
  const [questCount, setQuestCount] = React.useState(0);
  const [questions, setQuestions] = React.useState([]);
  const [response, setResponse] = React.useState([]);
  const [company, setCompany] = React.useState(location?.state?.company);
  const [buttonDisabled, setButtonDisabled] = React.useState(false);

  React.useEffect(() => {
    QuestionService.getFirstQuestion({
      companyId: params?.id,
    }).then((res) => {
      console.log("RES: ", res);
      setFirstQuest(res);
      setCurrentQuest(res);
      setQuestCount(questCount + 1);
      setQuestions([...questions, res]);
    });
  }, []);

  const handleAnsClick = (ans) => {
    console.log("ANS: ", ans);
    let prevResponse = [...response];
    setResponse([
      ...response,
      { question: currentQuest._id, answer: ans.title },
    ]);
    if (ans.linkQuestion) {
      console.log("RESSSS: ", response);
      QuestionService.getSingleQuestion(ans.linkQuestion).then((res) => {
        setCurrentQuest(res);
        setQuestCount(questCount + 1);
        setQuestions([...questions, res]);
      });
    } else {
      // alert("DONE");
      handleSubmit(prevResponse, ans);
    }
  };

  const handleSubmit = (prevResponse, ans) => {
    let newRes = [];
    if (ans && ans.title) {
      newRes = [
        ...prevResponse,
        { question: currentQuest._id, answer: ans.title },
      ];
    } else {
      newRes = [...prevResponse];
    }

    console.log("RESPONSE:", newRes);
    // UserResponseService.submitResponse({
    //   responses: newRes,
    //   customerId: location.state?.customerId,
    //   companyId:params?.id
    // });
    navigate(`/${params?.id}/hearingTest`, {
      state: {
        customerId: location?.state?.customerId,
        responses: newRes,
        company,
      },
    });
  };

  const handleBack = () => {
    console.log("res.question: ", response);
    console.log("currentQuest.question: ", currentQuest._id);

    let questArr = [...questions];
    questArr.pop();
    setQuestions(questArr);
    setCurrentQuest(questArr[questArr.length - 1]);
    setQuestCount(questCount - 1);

    let found = response.find(
      (res) => res.question == questArr[questArr.length - 1]._id
    );
    console.log("FOUND: ", found);
    if (found) {
      let ansArr = [...response];
      ansArr.pop();
      console.log("ANS");
      setResponse(ansArr);
    }
  };

  const handleSkip = async () => {
    console.log("Total crrent Response: ", response);
    setButtonDisabled(true);
    let prevResponse = [...response];
    // setResponse([
    //   ...response,
    //   { question: currentQuest._id, answer: ans.title },
    // ]);
    let flag = false;
    for (let i = 0; i < currentQuest.answers.length; i++) {
      if (currentQuest.answers[i].linkQuestion) {
        flag = true;

        let res = await QuestionService.getSingleQuestion(
          currentQuest.answers[i].linkQuestion
        );
        // .then((res) => {
        setCurrentQuest(res);
        setQuestCount(questCount + 1);
        setQuestions([...questions, res]);
        // });
        continue;
      }
    }
    setButtonDisabled(false);
    console.log("flag", flag);
    if (!flag) {
      console.log("No flag");
      handleSubmit(prevResponse, {});
    }
  };

  return (
    <div>
      <Grid
        container
        direction="column"
        justifyContent="center"
        alignItems="center"
        // spacing={2}
      >
        <Avatar
          src={company?.logo}
          alt={company?.name}
          style={{ marginBottom: "1rem", width: 100, height: 100 }}
        />
      </Grid>
      <Grid
        container
        direction="column"
        justifyContent="center"
        alignItems="center"
      >
        <p>Question {questCount}</p>

        <p
          style={{
            fontSize: "2rem",
            marginBottom: "3rem",
          }}
        >
          {currentQuest.question}
        </p>

        <Grid
          container
          direction="column"
          justifyContent="center"
          alignItems="center"
          style={{ minHeight: "15rem" }}
        >
          {currentQuest.answers &&
            currentQuest.answers.length > 0 &&
            currentQuest.answers.map((ans, index) => (
              <Button
                key={index}
                variant="outlined"
                style={buttonStyle}
                onClick={() => handleAnsClick(ans)}
              >
                {ans.title}
              </Button>
            ))}
        </Grid>
        {/* </Box> */}
      </Grid>
      <Grid
        container
        direction="row"
        justifyContent="space-evenly"
        alignItems="center"
        style={{ marginTop: "3rem" }}
      >
        <Button
          disabled={questCount <= 1}
          style={bottomButton}
          onClick={handleBack}
        >
          Back
        </Button>
        <Button
          style={bottomButton}
          disabled={buttonDisabled}
          onClick={handleSkip}
        >
          Skip
        </Button>
      </Grid>
      {/* </Grid> */}
    </div>
  );
};

export default Questions;
