import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import "./FilterPage.css";
import { fetchCourses } from "../api";
import Navbar from "./Navbar";
import { toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

const FilterPage = ({ setCourses }) => {
  const currentYear = new Date().getFullYear();

  // Load saved filters from localStorage or set default values
  const savedFilters = JSON.parse(localStorage.getItem("filterState")) || {
    scheme: "",
    semester: "",
    department: "",
    program: "",
    academicYear: `${currentYear}-${(currentYear + 1).toString().slice(-2)}`,
  };

  const [formData, setFormData] = useState(savedFilters);
  const navigate = useNavigate();

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData({ ...formData, [name]: value });

    // Reset semester if program changes
    if (name === "program") {
      setFormData((prevData) => ({ ...prevData, semester: "" }));
    }
  };

  const handleApplyFilter = async () => {
    if (
      !formData.scheme ||
      !formData.semester ||
      !formData.department ||
      !formData.program ||
      !formData.academicYear
    ) {
      toast.error("Please fill all the fields before applying the filter.");
      return;
    }

    try {
      localStorage.setItem("filterState", JSON.stringify(formData));
      const filteredCourses = await fetchCourses(formData);
      if (filteredCourses.length > 0) {
        // Save filteredCourses in localStorage
        localStorage.setItem(
          "filteredCourses",
          JSON.stringify(filteredCourses)
        );

        // Update courses if setCourses is passed as a prop (from CourseTable)
        if (setCourses) {
          setCourses(filteredCourses);
        } else {
          // Navigate to the courses page without updating the parent state
          navigate("/courses", {
            state: {
              courses: filteredCourses,
              academicYear: formData.academicYear,
            },
          });
        }
      } else {
        toast.error("No courses found for the selected filters.");
      }
    } catch (error) {
      console.error("Error fetching courses:", error);
      toast.error("Failed to fetch courses. Please try again later.");
    }
  };

  const getSemesters = () => {
    if (!formData.program) return [];
    if (formData.program === "B.Tech") {
      return Array.from({ length: 8 }, (_, i) => i + 1); // 1 to 8
    }
    if (formData.program === "M.Tech") {
      return Array.from({ length: 4 }, (_, i) => i + 1); // 1 to 4
    }
    return [];
  };

  const getAcademicYears = () => {
    return Array.from({ length: 6 }, (_, i) => {
      const startYear = currentYear - i;
      const endYear = startYear + 1;
      return `${startYear}-${endYear.toString().slice(-2)}`;
    }); // Generate in YYYY-YY format
  };

  return (
    <>
      <Navbar />
      <div className="filter-container">
        <div className="filter-form">
          <select
            name="department"
            value={formData.department}
            onChange={handleInputChange}
          >
            <option value="">Select Department</option>
            <option value="COMPS">COMPS</option>
            <option value="IT">IT</option>
          </select>
          <select
            name="program"
            value={formData.program}
            onChange={handleInputChange}
          >
            <option value="">Select Program</option>
            <option value="B.Tech">B.Tech</option>
            <option value="M.Tech">M.Tech</option>
          </select>
          <select
            name="semester"
            value={formData.semester}
            onChange={handleInputChange}
          >
            <option value="">Select Semester</option>
            {getSemesters().map((sem) => (
              <option key={sem} value={sem}>
                Semester {sem}
              </option>
            ))}
          </select>
          <select
            name="scheme"
            value={formData.scheme}
            onChange={handleInputChange}
          >
            <option value="">Select Scheme</option>
            <option value="SVU 2020">SVU 2020</option>
            <option value="SVU 2023">SVU 2023</option>
          </select>
          <select
            name="academicYear"
            value={formData.academicYear}
            onChange={handleInputChange}
          >
            <option value="">Select Academic Year</option>
            {getAcademicYears().map((year) => (
              <option key={year} value={year}>
                {year}
              </option>
            ))}
          </select>
          <button onClick={handleApplyFilter}>Apply Filter</button>
        </div>
      </div>
    </>
  );
};

export default FilterPage;
