import React, { useEffect, useState } from "react";
import { Badge, Card, Stack } from "react-bootstrap";
import { useLocation } from "react-router-dom";
import SectionsToEvaluate from "../components/SectionsToEvaluate";
import useFetchFromEndpoint from "../hooks/useFetchFromEndpoint";

const StudentPage = () => {
  const location = useLocation();
  const username = location.state.username;
  const token = location.state.token;

  const [userData, userDataStatus] = useFetchFromEndpoint(
    `/users/${username}/`,
    token
  );
  const [studentData, studentStatus] = useFetchFromEndpoint(
    `/students/${username}/`,
    token
  );
  const [sectionsToEval, sectionsStatus] = useFetchFromEndpoint(
    `/students/${username}/available_survey/`,
    token
  );

  const [majorData, setMajorData] = useState(null);

  useEffect(() => {
    const getMajorData = async (majorId) => {
      const response = await fetch(`http://localhost:8000/majors/${majorId}/`, {
        headers: { Authorization: `Token ${token}` },
      });
      if (response.ok) setMajorData(await response.json());
    };

    if (studentData) getMajorData(studentData.major);
  }, [studentData, token]);

  // fetch the user here, so we don't have to draw any component
  // if the status is an error

  let compRender = <></>;

  userData &&
    studentData &&
    sectionsToEval &&
    majorData &&
    studentStatus < 220 &&
    sectionsStatus < 220 ? (
    (compRender = (
      <Stack gap={5} className="mb-5">
        <Card body className="mt-4">
          <Stack
            direction="horizontal"
            gap={5}
            className="justify-content-center"
          >
            <h4>
              <strong>{userData.pid}</strong>
            </h4>
            <div className="vr"></div>
            <h2>
              <strong>{`${userData.first_name} ${userData.last_name}`}</strong>
            </h2>
            <div className="vr"></div>
            <h4>
              <strong>{`${majorData.degree} ${majorData.subject_area}`}</strong>
            </h4>
          </Stack>
        </Card>

        <SectionsToEvaluate sections={sectionsToEval} studentData={studentData} token={token} />
      </Stack>
    ))
  ) : (
    <h3>
      <Badge>Please use the login page first</Badge>
    </h3>
  );

  return <div className="StudentPage">{compRender}</div>;
};

export default StudentPage;
