import React, { useState, useEffect } from "react";
import { useLocation, useParams, useNavigate } from "react-router-dom";
import { fetchFaculties, saveAppointment, updateCourseStatus } from "../api";
import "./CourseForm.css";

const CourseForm = () => {
  const { id } = useParams();
  const location = useLocation();
  const navigate = useNavigate();
  const { course } = location.state || {};

  const [options, setOptions] = useState({
    faculties: [], // List of all faculties
  });

  const [suggestions, setSuggestions] = useState({}); // To hold suggestions for each field
  const [formData, setFormData] = useState({
    oralsPracticals: "",
    assessment: "",
    reassessment: "",
    paperSetting: "",
    moderation: "",
    pwdPaperSetter: "",
  });

  const [errors, setErrors] = useState({});

  // Fetch faculty list on mount
  useEffect(() => {
    const fetchOptionsAndFaculties = async () => {
      try {
        const facultiesData = await fetchFaculties(); // Fetch faculty names from backend
        setOptions((prev) => ({ ...prev, faculties: facultiesData }));
      } catch (error) {
        console.error("Failed to fetch faculties:", error);
      }
    };

    fetchOptionsAndFaculties();
  }, []);

  // Handle input changes for form fields
  const handleInputChange = (e) => {
    const { name, value } = e.target;

    setFormData({ ...formData, [name]: value });

    // Filter suggestions for the current field
    if (options.faculties.length > 0) {
      const filteredSuggestions = options.faculties.filter((faculty) =>
        faculty.name.toLowerCase().includes(value.toLowerCase())
      );
      setSuggestions((prev) => ({
        ...prev,
        [name]: filteredSuggestions,
      }));
    }
  };

  // Validate the form
  const validateForm = () => {
    const newErrors = {};
    Object.keys(formData).forEach((field) => {
      if (!formData[field]) {
        newErrors[field] = "This field is required";
      }
    });
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // Handle form submission
  const handleSubmit = async (e) => {
    e.preventDefault(); // Prevent default form submission behavior
    if (validateForm()) {
      try {
        const groupedTasks = {};

        // Group tasks by facultyId
        Object.entries(formData).forEach(([field, value]) => {
          const assignedFaculty = options.faculties.find(
            (faculty) => faculty.name === value
          );
          if (assignedFaculty) {
            if (!groupedTasks[assignedFaculty.facultyId]) {
              groupedTasks[assignedFaculty.facultyId] = {
                facultyId: assignedFaculty.facultyId,
                courseId: course?.courseId || id,
                tasks: [],
              };
            }
            groupedTasks[assignedFaculty.facultyId].tasks.push(field);
          }
        });

        const payload = Object.values(groupedTasks); // Convert the grouped tasks into an array
        console.log("Saving appointment with payload:", payload);
        await saveAppointment(payload); // Save to backend
        await updateCourseStatus(course?.courseId || id);
        console.log("Form submitted successfully:", payload);

        const filteredCourses = JSON.parse(localStorage.getItem("filteredCourses")) || [];

        // Redirect to courses page after successful submission
        navigate("/courses", {
          state: {
            courses: filteredCourses,
            updatedCourse: {
              ...course,
              status: "Submitted",
            },
          },
        });

        
      } catch (error) {
        console.error("Failed to save appointment:", error);
      }
    }
  };

  return (
    <div className="form-container">
      <h2>Course Info</h2>
      <form onSubmit={handleSubmit}>
        <label>
          Course ID:
          <input type="text" value={course?.courseId || id} readOnly />
        </label>
        <label>
          Course Name:
          <input type="text" value={course?.name || ""} readOnly />
        </label>
        {[
          { name: "oralsPracticals", label: "Orals/Practicals" },
          { name: "assessment", label: "Assessment" },
          { name: "reassessment", label: "Reassessment" },
          { name: "paperSetting", label: "Paper Setting" },
          { name: "moderation", label: "Moderation" },
          { name: "pwdPaperSetter", label: "PwD Paper Setter" },
        ].map(({ name, label }) => (
          <div key={name} className={errors[name] ? "error" : ""}>
            <label>
              {label}:
              <input
                type="text"
                name={name}
                value={formData[name]}
                onChange={handleInputChange}
                placeholder={`Search faculty for ${label}`}
              />
              <ul className="suggestions">
                {(suggestions[name] || []).map((faculty) => (
                  <li
                    key={faculty.facultyId}
                    onClick={() => {
                      setFormData({ ...formData, [name]: faculty.name });
                      setSuggestions((prev) => ({ ...prev, [name]: [] })); // Clear suggestions for this field
                    }}
                  >
                    {faculty.name}
                  </li>
                ))}
              </ul>
            </label>
            {errors[name] && <span className="error-message">{errors[name]}</span>}
          </div>
        ))}
        <button type="submit">Submit</button>
      </form>
    </div>
  );
};

export default CourseForm;
