const { useState, useEffect, useMemo } = React;

/**
 * Global hook to fetch and filter courses + batches based on:
 * 1. Winter/Summer Term rules
 * 2. Faculty Allocations & Roles
 */
window.useCourseFilter = function(exams, selectedExamId, currentUser, requiredAllocType = null) {
  const [allCourses, setAllCourses] = useState([]);
  const [allocations, setAllocations] = useState([]);
  const [allBatches, setAllBatches] = useState([]);
  const [allDepartments, setAllDepartments] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!currentUser) return;

    const fetchAll = async () => {
      setLoading(true);
      try {
        const isAdmin = currentUser.role.includes('Administrator') || currentUser.role.includes('Principal');
        
        // 1. Fetch all courses, batches, and departments in the institute
        const [cRes, bRes, dRes] = await Promise.all([
          fetch('/api/courses'),
          fetch('/api/batches'),
          fetch('/api/departments')
        ]);
        const cData = await cRes.json();
        const bData = await bRes.json();
        const dData = await dRes.json();
        
        setAllCourses(Array.isArray(cData) ? cData : []);
        setAllBatches(Array.isArray(bData) ? bData : []);
        setAllDepartments(Array.isArray(dData) ? dData : []);

        // 2. Fetch allocations ONLY if the user is a regular Faculty or HOD acting as Faculty
        if (!isAdmin) {
          const aRes = await fetch(`/api/attendance/my-allocations/${currentUser.id}`);
          const aData = await aRes.json();
          setAllocations(aData.allocations || []);
        } else {
          setAllocations([]);
        }
      } catch (err) {
        console.error('Failed to fetch course filter data', err);
      } finally {
        setLoading(false);
      }
    };
    fetchAll();
  }, [currentUser]);

  // Derived Filtered Courses
  const filteredCourses = useMemo(() => {
    if (!selectedExamId || allCourses.length === 0) return [];
    
    const exam = exams.find(e => String(e.id) === String(selectedExamId));
    if (!exam) return [];

    const isSummer = (exam.season && exam.season.toLowerCase().includes('summer')) || 
                     (exam.name && exam.name.toLowerCase().includes('summer'));
    const isAdmin = currentUser?.role.includes('Administrator') || currentUser?.role.includes('Principal');

    return allCourses.filter(c => {
      // Rule 1 removed: We now show all courses (Even/Odd) regardless of Winter/Summer 
      // so ATKT students can be assigned to previous semester courses.

      // Rule 2: Role Based Visiblity
      if (isAdmin) return true;

      // Faculty / HOD: Must have an explicit allocation for THIS exam and THIS course
      // If a requiredAllocType is passed (e.g. 'Practical'), they must have THAT specific type
      const hasAllocation = allocations.some(a => 
        String(a.exam_id) === String(selectedExamId) && 
        String(a.course_id) === String(c.id) &&
        (!requiredAllocType || a.allocation_type === requiredAllocType || a.allocation_type === 'Theory') 
      );
      
      return hasAllocation;
    });
  }, [allCourses, allocations, selectedExamId, exams, currentUser, requiredAllocType]);

  // Derived Filtered Batches
  // Call this function passing the selected courseId to get the batches allotted to this teacher
  const getFilteredBatches = (courseId, allocType) => {
    const isAdmin = currentUser?.role.includes('Administrator') || currentUser?.role.includes('Principal');
    
    // Admins see all batches
    if (isAdmin) return allBatches; 

    if (!courseId) return [];
    
    // Get unique batches assigned to this user for this course & term & type
    const assignedBatches = allocations
      .filter(a => 
        String(a.exam_id) === String(selectedExamId) && 
        String(a.course_id) === String(courseId) &&
        a.allocation_type === allocType &&
        a.Batch
      )
      .map(a => a.Batch);
      
    // Deduplicate batches by ID
    const uniqueMap = {};
    assignedBatches.forEach(b => uniqueMap[b.id] = b);
    return Object.values(uniqueMap);
  };

  return { filteredCourses, getFilteredBatches, departments: allDepartments, loading };
};
