import { useEffect, useState } from "react";
import { Button, ButtonGroup, Card, Dropdown, DropdownButton, Stack } from "react-bootstrap";
import { fetchFromEndpoint } from "../../api/fetchFromEndpoint";
import FacultyReportChart from "./FacultyReportChart";

const SubjectAreaYearDropdown = ({ subjectAreaCourseCurriculum, subjectAreaYearFilter, setSubjectAreaYearFilter }) => {
  const [availableYears, setAvailableYears] = useState([]);


  useEffect(() => {
    if (subjectAreaCourseCurriculum) {
      const years = []
      for (const [year, semester] of Object.entries(subjectAreaCourseCurriculum))
        years.push(year);

      setAvailableYears(years);
    }
  }, [subjectAreaCourseCurriculum])

  return (
    <DropdownButton as={ButtonGroup} title={subjectAreaYearFilter} onSelect={event => setSubjectAreaYearFilter(event)}>
      {availableYears.map(year => (
        <Dropdown.Item key={year} eventKey={year}>{year}</Dropdown.Item>
      ))}
    </DropdownButton>)
}

const SubjectAreaSemesterDropdown = ({ subjectAreaCourseCurriculum, selectedYear, subjectAreaSemesterFilter, setSubjectAreaSemesterFilter }) => {
  const [availableSemesters, setAvailableSemesters] = useState([])

  useEffect(() => {
    if (subjectAreaCourseCurriculum && selectedYear && selectedYear !== "Year") {
      const avSemesters = []
      for (const [semester, _] of Object.entries(subjectAreaCourseCurriculum[selectedYear]))
        avSemesters.push(semester);

      setAvailableSemesters(avSemesters);
    }
  }, [subjectAreaCourseCurriculum, selectedYear])

  return (
    <DropdownButton as={ButtonGroup} title={subjectAreaSemesterFilter} onSelect={event => setSubjectAreaSemesterFilter(event)}>
      {availableSemesters.map(semester => (
        <Dropdown.Item key={semester} eventKey={semester}>{semester}</Dropdown.Item>
      ))}
    </DropdownButton>)
}

const SubjectAreaCourseDropdown = ({ subjectAreaCourseCurriculum, selectedYear, selectedSemester, subjectAreaCourseFilter, setSubjectAreaCourseFilter }) => {
  return (
    <DropdownButton as={ButtonGroup} title={subjectAreaCourseFilter} onSelect={event => setSubjectAreaCourseFilter(event)}>
      {subjectAreaCourseCurriculum && selectedYear !== "Year" && selectedSemester !== "Semester" ? subjectAreaCourseCurriculum[selectedYear][selectedSemester].map(course => (
        <Dropdown.Item key={course} eventKey={course}>{course}</Dropdown.Item>
      )) : <></>}
    </DropdownButton>
  )
}

const FacultyReportMenu = ({ areaCoordinator, username, token }) => {
  const [curriculum, setCurriculum] = useState(null);
  const [coursesKey, setCoursesKey] = useState(null);

  const [yearFilter, setYearFilter] = useState("");
  const [semesterFilter, setSemesterFilter] = useState("");
  const [courseFilter, setCourseFilter] = useState("");
  const [referenceFilter, setReferenceFilter] = useState("");

  const [yearOptions, setYearOptions] = useState([]);
  const [courseOptions, setCourseOptions] = useState([]);
  const [semesterOptions, setSemesterOptions] = useState([]);
  const [referencesOptions, setReferencesOptions] = useState([]);

  const [showSummary, setShowSummary] = useState(false);

  const [subjectAreaDegreeCurriculum, setSubjectAreaDegreeCurriculum] = useState(null);
  const [subjectAreaCourseCurriculum, setSubjectAreaCourseCurriculum] = useState(null);

  const [subjectAreaSelectedDegree, setSubjectAreaSelectedDegree] = useState("Degree");
  const [subjectAreaYearFilter, setSubjectAreaYearFilter] = useState("Year");
  const [subjectAreaSemesterFilter, setSubjectAreaSemesterFilter] = useState("Semester");
  const [subjectAreaCourseFilter, setSubjectAreaCourseFilter] = useState("Course");

  const semesterNames = { 1: "Spring", 5: "Summer", 8: "Fall" }

  useEffect(() => {
    const trySetCurriculum = async () => {
      const curr = await fetchFromEndpoint(`/faculty/${username}/view_faculty_curriculum/`, token)
        .then(response => response.json())
        .then(data => data);

      if (curr) {
        setCoursesKey(curr.course_key)
        delete curr['course_key'];

        const curriculumYears = []
        for (const [year, _] of Object.entries(curr))
          curriculumYears.push(year);

        setCurriculum(curr);
        setYearOptions(curriculumYears);
      }
    }

    trySetCurriculum();

  }, [username, token])

  // make sure that whenever the year, course, or semester filter changes, this is reset
  // to prevent wrong inputs to the backend
  useEffect(() => {
    setReferenceFilter("");
    setSemesterFilter("");
    setCourseFilter("");
  }, [yearFilter]);

  useEffect(() => {
    setSemesterFilter("");
    setReferenceFilter("");
  }, [courseFilter])

  useEffect(() => {
    setReferenceFilter("");
  }, [semesterFilter])



  // if the user is a subject area coordinator,
  // fetch info
  useEffect(() => {
    // fetch available degrees
    const trySetSubjectAreaDegreeCurriculum = async () => {
      await fetchFromEndpoint(`/faculty/${username}/subject_area_degree_curriculum/`, token)
        .then(response => response.json())
        .then(data => setSubjectAreaDegreeCurriculum(data));
    };

    // try fetch available curriculum
    const trySetSubjectAreaCourseCurriculum = async () => {
      await fetchFromEndpoint(`/faculty/${username}/subject_area_course_curriculum/`, token)
        .then(response => response.json())
        .then(data => setSubjectAreaCourseCurriculum(data));
    }

    if (areaCoordinator) {
      trySetSubjectAreaDegreeCurriculum();
      trySetSubjectAreaCourseCurriculum();
    }
  }, [areaCoordinator])

  const handleGenerateReportOnClick = event => {
    if (yearFilter !== "" && courseFilter !== "") {
      if (semesterFilter === "All Semesters" || semesterFilter === "") {
        setSemesterFilter("All Semesters")
        setReferenceFilter("All Sections")
      }

      setShowSummary(true);
    }
  }


  return (
    <Stack gap={5}>
      <Card
        body
        style={{
          display: "flex",
          alignItems: "center",
        }}>

        {/* YEAR DROPDOWN */}
        <ButtonGroup>
          <DropdownButton as={ButtonGroup} title={yearFilter === "" ? "Year" : yearFilter} onSelect={year => {
            const tempCourses = [];
            for (const [course, _] of Object.entries(curriculum[year]))
              tempCourses.push(course);
            setCourseOptions(tempCourses);
            setYearFilter(year);
          }}>
            {yearOptions.map(year => (<Dropdown.Item key={year} eventKey={year}>{year}</Dropdown.Item>))}
          </DropdownButton>

          {/* COURSE DROPDOWN */}
          <DropdownButton
            as={ButtonGroup}
            title={courseFilter === "" ? "Course" : coursesKey[courseFilter]}
            onSelect={course => {
              const tempSemesters = [];
              for (const [semester, _] of Object.entries(curriculum[yearFilter][course]))
                tempSemesters.push(semester);

              setSemesterOptions(tempSemesters);
              setCourseFilter(course);
            }}>
            {courseOptions.map(course => (<Dropdown.Item key={course} eventKey={course}>{coursesKey[course]}</Dropdown.Item>))}
          </DropdownButton>

          {/* SEMESTER DROPDOWN */}
          <DropdownButton
            as={ButtonGroup}
            title={semesterFilter === "" ? "Semester" : semesterFilter === "All Semesters" ? "All Semesters" : semesterNames[semesterFilter]}
            onSelect={semester => {
              if (semester !== "All Semesters") {
                const tempReferences = curriculum[yearFilter][courseFilter][semester];
                setReferencesOptions(tempReferences);
              }

              setSemesterFilter(semester);
            }}>
            <Dropdown.Item eventKey="All Semesters">All Semesters</Dropdown.Item>
            {semesterOptions.map(semester => (<Dropdown.Item key={semester} eventKey={semester}>{semesterNames[semester]}</Dropdown.Item>))}
          </DropdownButton>

          {/* SECTION DROPDOWN */}
          <DropdownButton
            as={ButtonGroup}
            title={referenceFilter === "" ? "Section" : referenceFilter}
            onSelect={reference => {
              setReferenceFilter(reference);
            }}>
            {semesterFilter === "All Semesters" ? (<Dropdown.Item eventKey="All Sections">All Sections</Dropdown.Item>) : referencesOptions.map(reference => (<Dropdown.Item key={reference} eventKey={reference}>{reference}</Dropdown.Item>))}
          </DropdownButton>
          <Button onClick={handleGenerateReportOnClick}>Generate Report</Button>
        </ButtonGroup>
      </Card>

      {/* {areaCoordinator && subjectAreaDegreeCurriculum ? (
        <Card
          body
          style={{
            display: "flex",
            alignItems: "center",
          }}>
          <Stack direction="horizontal">
            <strong className="mx-5">Subject Area controls</strong>
            <ButtonGroup>
              <DropdownButton as={ButtonGroup} title={subjectAreaSelectedDegree} onSelect={event => setSubjectAreaSelectedDegree(event)}>
                {subjectAreaDegreeCurriculum.map((degree, id) => (<Dropdown.Item key={`${degree}-${id}`} eventKey={degree}>{degree}</Dropdown.Item>))}
              </DropdownButton>
              <SubjectAreaYearDropdown subjectAreaCourseCurriculum={subjectAreaCourseCurriculum} setSubjectAreaYearFilter={setSubjectAreaYearFilter} subjectAreaYearFilter={subjectAreaYearFilter} />
              <SubjectAreaSemesterDropdown subjectAreaCourseCurriculum={subjectAreaCourseCurriculum} selectedYear={subjectAreaYearFilter} subjectAreaSemesterFilter={subjectAreaSemesterFilter} setSubjectAreaSemesterFilter={setSubjectAreaSemesterFilter} />
              <SubjectAreaCourseDropdown subjectAreaCourseCurriculum={subjectAreaCourseCurriculum} selectedYear={subjectAreaYearFilter} selectedSemester={subjectAreaSemesterFilter} subjectAreaCourseFilter={subjectAreaCourseFilter} setSubjectAreaCourseFilter={setSubjectAreaCourseFilter} />
            </ButtonGroup>

            <Button className="mx-5" onClick={event => {
              if (subjectAreaSelectedDegree !== "Degree" && subjectAreaYearFilter !== "Year")
                setShowSummary(true);
            }}>
              Generate Report
            </Button>
          </Stack>
        </Card>
      ) : <></>} */}

      {showSummary ? (
        <FacultyReportChart
          year={yearFilter}
          course={courseFilter}
          month={semesterFilter}
          reference={referenceFilter}
          isAreaCoordinator={subjectAreaSelectedDegree !== "Degree" && subjectAreaYearFilter !== "Year" && yearFilter !== "Year"}
          saDegree={subjectAreaSelectedDegree}
          saYear={subjectAreaYearFilter}
          saSemester={subjectAreaSemesterFilter}
          saCourse={subjectAreaCourseFilter}
          username={username}
          token={token}
        />
      ) : <></>}
    </Stack>
  );
};

export default FacultyReportMenu;
