//app/admin/pages/course/courselist.jsx

'use client';

import React, { useState, useEffect, useRef } from "react";
import { Plus, Edit, Trash2, Upload, Download, X, Search, ChevronDown, ChevronUp, Menu } from "lucide-react";
import { useRouter } from "next/navigation";
import dynamic from 'next/dynamic';
import Pagination from '../../components/Pagination';
import Swal from 'sweetalert2';

const AddCourse = dynamic(() => import('./AddCourse'), { ssr: false });

const CourseList = () => {
  const [courses, setCourses] = useState([]);
  const [subjects, setSubjects] = useState([]);
  const [countries, setCountries] = useState([]);
  const [universities, setUniversities] = useState([]);
  const [selectedCourse, setSelectedCourse] = useState(null);
  const [editModalOpen, setEditModalOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [fetchingCourses, setFetchingCourses] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage] = useState(15);
  const [totalItems, setTotalItems] = useState(0);
  const [searchTerm, setSearchTerm] = useState('');
  const [levels, setLevels] = useState([]);
  
  // Import modal states
  const [importModalOpen, setImportModalOpen] = useState(false);
  const [importFile, setImportFile] = useState(null);
  const [importing, setImporting] = useState(false);
  const [importResults, setImportResults] = useState(null);
  
  // Filter states
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');
  const [qualificationFilter, setQualificationFilter] = useState('');
  const [popularFilter, setPopularFilter] = useState('');
  const [countryPopularFilter, setCountryPopularFilter] = useState('');
  const [subjectFilter, setSubjectFilter] = useState('');
  const [countryFilter, setCountryFilter] = useState('');
  const [universityFilter, setUniversityFilter] = useState('');
  const [menuVisibilityFilter, setMenuVisibilityFilter] = useState(''); // NEW: Menu visibility filter
  const [isFilterOpen, setIsFilterOpen] = useState(false);
  
  // Applied filters state
  const [appliedSearchTerm, setAppliedSearchTerm] = useState('');
  const [appliedStartDate, setAppliedStartDate] = useState('');
  const [appliedEndDate, setAppliedEndDate] = useState('');
  const [appliedQualificationFilter, setAppliedQualificationFilter] = useState('');
  const [appliedPopularFilter, setAppliedPopularFilter] = useState('');
  const [appliedCountryPopularFilter, setAppliedCountryPopularFilter] = useState('');
  const [appliedSubjectFilter, setAppliedSubjectFilter] = useState('');
  const [appliedCountryFilter, setAppliedCountryFilter] = useState('');
  const [appliedUniversityFilter, setAppliedUniversityFilter] = useState('');
  const [appliedMenuVisibilityFilter, setAppliedMenuVisibilityFilter] = useState(''); // NEW

  // University search dropdown states
  const [universitySearchTerm, setUniversitySearchTerm] = useState('');
  const [isUniversityDropdownOpen, setIsUniversityDropdownOpen] = useState(false);
  const [filteredUniversities, setFilteredUniversities] = useState([]);

  // Load all courses state
  const [isLoadingAll, setIsLoadingAll] = useState(false);
  const [allCoursesLoaded, setAllCoursesLoaded] = useState(false);

  // Refs for dropdown handling
  const universityDropdownRef = useRef(null);
  const universityInputRef = useRef(null);

  const router = useRouter();

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (
        universityDropdownRef.current && 
        !universityDropdownRef.current.contains(event.target) &&
        universityInputRef.current && 
        !universityInputRef.current.contains(event.target)
      ) {
        setIsUniversityDropdownOpen(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  // Fetch countries and universities on mount
  useEffect(() => {
    fetchCountries();
    fetchUniversities();
  }, []);

  // Filter universities based on search term
  useEffect(() => {
    if (universitySearchTerm.trim() === '') {
      setFilteredUniversities(universities);
    } else {
      const filtered = universities.filter(university =>
        university.name?.toLowerCase().includes(universitySearchTerm.toLowerCase()) ||
        university.country?.toLowerCase().includes(universitySearchTerm.toLowerCase()) ||
        university.city?.toLowerCase().includes(universitySearchTerm.toLowerCase())
      );
      setFilteredUniversities(filtered);
    }
  }, [universitySearchTerm, universities]);

  // Fetch countries function
  const fetchCountries = async () => {
    try {
      const response = await fetch('/api/internal/country', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        }
      });
      
      if (response.ok) {
        const data = await response.json();
        setCountries(data.data || []);
      } else {
        console.error('Failed to fetch countries');
      }
    } catch (error) {
      console.error('Error fetching countries:', error);
    }
  };

  // Fetch universities function
  const fetchUniversities = async () => {
    try {
      const response = await fetch('/api/internal/new/getuniversity', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        }
      });
      
      if (response.ok) {
        const data = await response.json();
        setUniversities(data.data || []);
        setFilteredUniversities(data.data || []);
      } else {
        console.error('Failed to fetch universities');
      }
    } catch (error) {
      console.error('Error fetching universities:', error);
      // Fallback: Try alternative endpoint if the above doesn't work
      try {
        const fallbackResponse = await fetch('/api/internal/universities', {
          method: 'GET',
        });
        if (fallbackResponse.ok) {
          const fallbackData = await fallbackResponse.json();
          const unis = fallbackData.data || fallbackData || [];
          setUniversities(unis);
          setFilteredUniversities(unis);
        }
      } catch (fallbackError) {
        console.error('Fallback university fetch also failed:', fallbackError);
      }
    }
  };

  // Update pagination when total items change
  useEffect(() => {
    const pages = Math.ceil(totalItems / itemsPerPage);
    if (currentPage > pages && pages > 0) {
      setCurrentPage(1);
    }
  }, [totalItems, currentPage, itemsPerPage]);

  // Reset to first page when applied filters change
  useEffect(() => {
    setCurrentPage(1);
  }, [
    appliedSearchTerm, 
    appliedStartDate, 
    appliedEndDate, 
    appliedQualificationFilter, 
    appliedPopularFilter, 
    appliedCountryPopularFilter, 
    appliedSubjectFilter, 
    appliedCountryFilter,
    appliedUniversityFilter,
    appliedMenuVisibilityFilter // NEW
  ]);

  // Fetch universities and subjects on mount
  useEffect(() => {
    const fetchdata = async () => {
      try {
        const [levels, subjects] = await Promise.all([
          fetch('/api/frontend/getpostlevel', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            }
          }),
          fetch('/api/frontend/getsubject', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            }
          }),
        ]);

        if(!levels.ok || !subjects.ok) throw new Error('Failed to fetch data')

        const levelData = await levels.json();
        const subjectsData = await subjects.json();

        setLevels(levelData.data);
        setSubjects(subjectsData.data);
      } catch (error) {
        console.error('Error fetching levels and subjects:', error);
      }
    }

    fetchdata()
  }, [])
 
  // Fetch courses when page or applied filters change
  useEffect(() => {
    fetchCourses();
  }, [
    currentPage, 
    appliedSearchTerm, 
    appliedStartDate, 
    appliedEndDate, 
    appliedQualificationFilter, 
    appliedPopularFilter, 
    appliedCountryPopularFilter, 
    appliedSubjectFilter, 
    appliedCountryFilter,
    appliedUniversityFilter,
    appliedMenuVisibilityFilter // NEW
  ]);

  async function fetchCourses() {
    try {
      setFetchingCourses(true);
      const params = new URLSearchParams({
        page: currentPage.toString(),
        limit: itemsPerPage.toString()
      });
      
      if (appliedSearchTerm) {
        params.append('search', appliedSearchTerm);
      }
      if (appliedStartDate) {
        params.append('start_date', appliedStartDate);
      }
      if (appliedEndDate) {
        params.append('end_date', appliedEndDate);
      }
      if (appliedQualificationFilter) {
        params.append('qualification', appliedQualificationFilter);
      }
      if (appliedPopularFilter) {
        params.append('popular', appliedPopularFilter);
      }
      if (appliedCountryPopularFilter) {
        params.append('country_popular', appliedCountryPopularFilter);
      }
      if (appliedSubjectFilter) {
        params.append('subject', appliedSubjectFilter);
      }
      if (appliedCountryFilter) {
        params.append('country', appliedCountryFilter);
      }
      if (appliedUniversityFilter) {
        params.append('university_id', appliedUniversityFilter);
      }
      // NEW: Add menu visibility filter
      if (appliedMenuVisibilityFilter !== '') {
        params.append('showInMenu', appliedMenuVisibilityFilter === 'true' ? '1' : '0');
      }

      const res = await fetch(`/api/internal/course?${params.toString()}`);
      const data = await res.json();
      
      if (data.success) {
        setCourses(data.data);
        setTotalItems(data.pagination?.totalItems || data.total || data.data.length);
      } else {
        setCourses([]);
        setTotalItems(0);
      }
    } catch (err) {
      console.error('Error fetching courses:', err);
      setCourses([]);
      setTotalItems(0);
      Swal.fire({
        icon: 'error',
        title: 'Error!',
        text: 'Failed to load courses',
        confirmButtonColor: '#0B6D76',
        confirmButtonText: 'OK'
      });
    } finally {
      setFetchingCourses(false);
    }
  }

  // NEW: Handle menu visibility toggle
  const handleToggleMenuVisibility = async (courseId, currentStatus) => {
    try {
      const response = await fetch(`/api/internal/course/${courseId}/menu-toggle`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ show_in_menu: !currentStatus }),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || errorData.message || 'Failed to update menu visibility');
      }

      const result = await response.json();
      
      // Update the course in the local state
      setCourses(prev =>
        prev.map(course => 
          course.id === courseId ? {
            ...course,
            show_in_menu: result.data.show_in_menu
          } : course
        )
      );
      
      Swal.fire({
        icon: 'success',
        title: 'Success',
        text: result.message || `Menu visibility ${!currentStatus ? 'enabled' : 'disabled'} successfully`,
        confirmButtonColor: '#0B6D76',
        timer: 2000,
        showConfirmButton: false
      });
    } catch (error) {
      console.error('Error updating menu visibility:', error);
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: 'Failed to update menu visibility',
        confirmButtonColor: '#0B6D76'
      });
    }
  };

  const handleSearch = () => {
    setAppliedSearchTerm(searchTerm);
    setAppliedStartDate(startDate);
    setAppliedEndDate(endDate);
    setAppliedQualificationFilter(qualificationFilter);
    setAppliedPopularFilter(popularFilter);
    setAppliedCountryPopularFilter(countryPopularFilter);
    setAppliedSubjectFilter(subjectFilter);
    setAppliedCountryFilter(countryFilter);
    setAppliedUniversityFilter(universityFilter);
    setAppliedMenuVisibilityFilter(menuVisibilityFilter); // NEW
    setCurrentPage(1);
  };

  const clearFilters = () => {
    setSearchTerm('');
    setStartDate('');
    setEndDate('');
    setQualificationFilter('');
    setPopularFilter('');
    setCountryPopularFilter('');
    setSubjectFilter('');
    setCountryFilter('');
    setUniversityFilter('');
    setMenuVisibilityFilter(''); // NEW
    setUniversitySearchTerm('');
    setAppliedSearchTerm('');
    setAppliedStartDate('');
    setAppliedEndDate('');
    setAppliedQualificationFilter('');
    setAppliedPopularFilter('');
    setAppliedCountryPopularFilter('');
    setAppliedSubjectFilter('');
    setAppliedCountryFilter('');
    setAppliedUniversityFilter('');
    setAppliedMenuVisibilityFilter(''); // NEW
    setCurrentPage(1);
  };

  // University dropdown handlers
  const handleUniversitySelect = (universityId) => {
    setUniversityFilter(universityId);
    setIsUniversityDropdownOpen(false);
    setUniversitySearchTerm('');
  };

  const clearUniversityFilter = () => {
    setUniversityFilter('');
    setUniversitySearchTerm('');
  };

  const toggleUniversityDropdown = () => {
    setIsUniversityDropdownOpen(!isUniversityDropdownOpen);
    if (!isUniversityDropdownOpen) {
      setUniversitySearchTerm('');
    }
  };

  const getSelectedUniversityName = () => {
    if (!universityFilter) return '';
    const selectedUni = universities.find(u => String(u.id) === String(universityFilter));
    return selectedUni ? `${selectedUni.name} ${selectedUni.country ? `(${selectedUni.country})` : ''}` : '';
  };

  // Function to load all courses at once
  const loadAllCourses = async () => {
    try {
      setIsLoadingAll(true);
      const params = new URLSearchParams({
        page: '1',
        limit: '10000'
      });
      
      if (appliedSearchTerm) params.append('search', appliedSearchTerm);
      if (appliedStartDate) params.append('start_date', appliedStartDate);
      if (appliedEndDate) params.append('end_date', appliedEndDate);
      if (appliedQualificationFilter) params.append('qualification', appliedQualificationFilter);
      if (appliedPopularFilter) params.append('popular', appliedPopularFilter);
      if (appliedCountryPopularFilter) params.append('country_popular', appliedCountryPopularFilter);
      if (appliedSubjectFilter) params.append('subject', appliedSubjectFilter);
      if (appliedCountryFilter) params.append('country', appliedCountryFilter);
      if (appliedUniversityFilter) params.append('university_id', appliedUniversityFilter);
      if (appliedMenuVisibilityFilter !== '') params.append('showInMenu', appliedMenuVisibilityFilter === 'true' ? '1' : '0'); // NEW
      
      const res = await fetch(`/api/internal/course?${params.toString()}`);
      const data = await res.json();
      
      if (data.success) {
        setCourses(data.data);
        setTotalItems(data.data.length);
        setAllCoursesLoaded(true);
        
        Swal.fire({
          icon: 'success',
          title: 'Success!',
          text: `Loaded all ${data.data.length} courses`,
          confirmButtonColor: '#0B6D76',
          timer: 2000,
          showConfirmButton: false
        });
      }
    } catch (error) {
      console.error('Error loading all courses:', error);
      Swal.fire({
        icon: 'error',
        title: 'Error!',
        text: 'Failed to load all courses',
        confirmButtonColor: '#0B6D76'
      });
    } finally {
      setIsLoadingAll(false);
    }
  };

  // Function to reset to paginated view
  const resetToPaginatedView = () => {
    setAllCoursesLoaded(false);
    fetchCourses();
  };

  const hasActiveFilters = appliedSearchTerm || appliedStartDate || appliedEndDate || appliedQualificationFilter || appliedPopularFilter || appliedCountryPopularFilter || appliedSubjectFilter || appliedCountryFilter || appliedUniversityFilter || appliedMenuVisibilityFilter; // Updated

  const handleDelete = async (id) => {
    try {
      const result = await Swal.fire({
        title: 'Are you sure?',
        text: "You won't be able to revert this!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#3085d6',
        confirmButtonText: 'Yes, delete it!',
        cancelButtonText: 'Cancel'
      });

      if (result.isConfirmed) {
        const res = await fetch(`/api/internal/course/${id}`, {
          method: 'DELETE'
        });
        
        if (res.ok) {
          setCourses(prev => prev.filter(c => c.id !== id));
          Swal.fire({
            icon: 'success',
            title: 'Deleted!',
            text: 'Course has been deleted successfully.',
            confirmButtonColor: '#0B6D76',
            confirmButtonText: 'OK'
          });
        } else {
          throw new Error('Failed to delete course');
        }
      }
    } catch (error) {
      Swal.fire({
        icon: 'error',
        title: 'Error!',
        text: 'Error deleting course: ' + error.message,
        confirmButtonColor: '#0B6D76',
        confirmButtonText: 'OK'
      });
    }
  };

  const handleTogglePopular = async (course) => {
    try {
      const res = await fetch(`/api/internal/new/togglepopular/${course.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ popular: !course.popular })
      });
      
      if (res.ok) {
        setCourses(prev =>
          prev.map(c => (c.id === course.id ? { ...c, popular: !c.popular } : c))
        );
        
        Swal.fire({
          icon: 'success',
          title: 'Updated!',
          text: `Course popularity ${!course.popular ? 'enabled' : 'disabled'} successfully.`,
          confirmButtonColor: '#0B6D76',
          confirmButtonText: 'OK',
          timer: 2000,
          showConfirmButton: false
        });
      } else {
        throw new Error('Failed to update popular status');
      }
    } catch (error) {
      Swal.fire({
        icon: 'error',
        title: 'Error!',
        text: 'Error updating popular status: ' + error.message,
        confirmButtonColor: '#0B6D76',
        confirmButtonText: 'OK'
      });
    }
  };

  // Handle country popular toggle
  const handleToggleCountryPopular = async (course) => {
    try {
      const res = await fetch(`/api/internal/new/togglepopular/${course.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ country_popular: !course.country_popular })
      });
      
      if (res.ok) {
        setCourses(prev =>
          prev.map(c => (c.id === course.id ? { ...c, country_popular: !c.country_popular } : c))
        );
        
        Swal.fire({
          icon: 'success',
          title: 'Updated!',
          text: `Course country popularity ${!course.country_popular ? 'enabled' : 'disabled'} successfully.`,
          confirmButtonColor: '#0B6D76',
          confirmButtonText: 'OK',
          timer: 2000,
          showConfirmButton: false
        });
      } else {
        throw new Error('Failed to update country popular status');
      }
    } catch (error) {
      Swal.fire({
        icon: 'error',
        title: 'Error!',
        text: 'Error updating country popular status: ' + error.message,
        confirmButtonColor: '#0B6D76',
        confirmButtonText: 'OK'
      });
    }
  };

  const handleEdit = (course) => {
    setSelectedCourse(course);
    setEditModalOpen(true);
  };

  const handleEditSubmit = async (updatedData) => {
    setLoading(true);
    try {
      const res = await fetch(`/api/internal/course/${selectedCourse.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(updatedData),
      });
      
      if (res.ok) {
        await Swal.fire({
          icon: 'success',
          title: 'Success!',
          text: 'Course updated successfully!',
          confirmButtonColor: '#0B6D76',
          confirmButtonText: 'OK'
        });
        
        setEditModalOpen(false);
        setSelectedCourse(null);
        fetchCourses();
      } else {
        const err = await res.json();
        throw new Error(err.message || 'Failed to update course');
      }
    } catch (error) {
      Swal.fire({
        icon: 'error',
        title: 'Error!',
        text: 'Error updating course: ' + error.message,
        confirmButtonColor: '#0B6D76',
        confirmButtonText: 'OK'
      });
    } finally {
      setLoading(false);
    }
  };

  // Import functionality
  const handleImportClick = () => {
    setImportModalOpen(true);
    setImportResults(null);
    setImportFile(null);
  };

  const handleFileSelect = (e) => {
    const file = e.target.files[0];
    if (file) {
      const validTypes = [
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'application/vnd.oasis.opendocument.spreadsheet'
      ];
      
      if (!validTypes.includes(file.type) && !file.name.match(/\.(xlsx|xls|ods)$/)) {
        Swal.fire({
          icon: 'error',
          title: 'Invalid File',
          text: 'Please select an Excel file (.xlsx, .xls)',
          confirmButtonColor: '#0B6D76'
        });
        return;
      }
      
      setImportFile(file);
    }
  };

  const handleImportSubmit = async () => {
    if (!importFile) {
      Swal.fire({
        icon: 'warning',
        title: 'No File Selected',
        text: 'Please select an Excel file to import',
        confirmButtonColor: '#0B6D76'
      });
      return;
    }

    setImporting(true);
    try {
      const formData = new FormData();
      formData.append('file', importFile);

      const response = await fetch('/api/internal/course/import', {
        method: 'POST',
        body: formData,
      });

      const result = await response.json();

      if (result.success) {
        setImportResults(result);
        
        Swal.fire({
          icon: 'success',
          title: 'Import Successful!',
          html: `
            <div class="text-left">
              <p><strong>Total:</strong> ${result.results.total} rows</p>
              <p><strong>Successful:</strong> ${result.results.successful} (${result.results.created} created, ${result.results.updated} updated)</p>
              <p><strong>Failed:</strong> ${result.results.failed}</p>
              ${result.results.failed > 0 ? '<p class="text-red-600 mt-2">Check the import results for failed rows.</p>' : ''}
            </div>
          `,
          confirmButtonColor: '#0B6D76'
        });

        fetchCourses();
      } else {
        throw new Error(result.error || 'Import failed');
      }
    } catch (error) {
      console.error('Import error:', error);
      Swal.fire({
        icon: 'error',
        title: 'Import Failed',
        text: error.message,
        confirmButtonColor: '#0B6D76'
      });
    } finally {
      setImporting(false);
    }
  };

  const closeImportModal = () => {
    setImportModalOpen(false);
    setImportFile(null);
    setImportResults(null);
  };

  return (
    <>
    <title>List of all Courses - University Page</title>
    <meta name="description" content="List of all Courses - University Page" />
    <div className="space-y-6 p-6 bg-gradient-to-br from-blue-50 to-indigo-100 min-h-screen">
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-2xl font-bold text-gray-900">Course Management</h1>
        <div className="flex gap-3">
          <button
            onClick={() => setIsFilterOpen(!isFilterOpen)}
            className={`px-4 py-2 rounded-lg transition-colors flex items-center gap-2 ${
              isFilterOpen 
                ? 'bg-[#0B6D76] text-white' 
                : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
            }`}
          >
            🔍 Filters
            {hasActiveFilters && (
              <span className="ml-1 px-2 py-1 bg-white text-[#0B6D76] text-xs rounded-full">
                {[
                  appliedSearchTerm, 
                  appliedStartDate, 
                  appliedEndDate, 
                  appliedQualificationFilter, 
                  appliedPopularFilter, 
                  appliedCountryPopularFilter, 
                  appliedSubjectFilter, 
                  appliedCountryFilter,
                  appliedUniversityFilter,
                  appliedMenuVisibilityFilter // NEW
                ].filter(Boolean).length}
              </span>
            )}
          </button>
          
          {/* Import Button */}
          <button
            onClick={handleImportClick}
            className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors flex items-center gap-2"
          >
            <Upload className="w-4 h-4" />
            Import Excel
          </button>
          
          <button
            onClick={() => router.push('/admin/course/add')}
            className="px-4 py-2 bg-[#0B6D76] text-white rounded-lg hover:bg-[#09545c] transition-colors flex items-center gap-2"
          >
            <Plus className="w-4 h-4" />
            Add Course
          </button>
        </div>
      </div>

      {/* Filter Section */}
      {isFilterOpen && (
        <div className="bg-white rounded-2xl shadow-xl p-6 mb-6 relative">
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Search Courses</label>
              <input
                type="text"
                placeholder="Search by course name, university, or subject..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                onKeyDown={(e) => e.key === "Enter" && handleSearch()}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
              />
            </div>
            
            {/* University Filter with Search */}
            <div className="relative">
              <label className="block text-sm font-medium text-gray-700 mb-2">University</label>
              <div className="relative">
                <div 
                  ref={universityInputRef}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent cursor-pointer flex justify-between items-center bg-white"
                  onClick={toggleUniversityDropdown}
                >
                  <span className={`truncate ${universityFilter ? "text-gray-900" : "text-gray-500"}`}>
                    {universityFilter ? getSelectedUniversityName() : "Select University"}
                  </span>
                  <div className="flex items-center gap-2 flex-shrink-0">
                    {universityFilter && (
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          clearUniversityFilter();
                        }}
                        className="text-gray-400 hover:text-gray-600"
                      >
                        <X className="w-4 h-4" />
                      </button>
                    )}
                    {isUniversityDropdownOpen ? (
                      <ChevronUp className="w-4 h-4 text-gray-500" />
                    ) : (
                      <ChevronDown className="w-4 h-4 text-gray-500" />
                    )}
                  </div>
                </div>
                
                {/* University Dropdown with Search */}
                {isUniversityDropdownOpen && (
                  <div 
                    ref={universityDropdownRef}
                    className="absolute z-50 mt-1 w-full bg-white border border-gray-300 rounded-lg shadow-lg"
                    style={{
                      maxHeight: '300px',
                      overflow: 'hidden',
                      display: 'flex',
                      flexDirection: 'column'
                    }}
                  >
                    {/* Search Bar */}
                    <div className="sticky top-0 bg-white border-b border-gray-200 p-2">
                      <div className="relative">
                        <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
                        <input
                          type="text"
                          placeholder="Search universities..."
                          value={universitySearchTerm}
                          onChange={(e) => setUniversitySearchTerm(e.target.value)}
                          className="w-full pl-9 pr-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#0B6D76]"
                          autoFocus
                          onClick={(e) => e.stopPropagation()}
                        />
                      </div>
                    </div>
                    
                    {/* University List */}
                    <div 
                      className="overflow-y-auto flex-1"
                      style={{ maxHeight: '250px' }}
                    >
                      <div 
                        className="px-3 py-2 text-sm text-gray-500 cursor-pointer hover:bg-gray-50 border-b border-gray-100"
                        onClick={() => handleUniversitySelect('')}
                      >
                        Clear selection
                      </div>
                      
                      {filteredUniversities.length === 0 ? (
                        <div className="px-3 py-4 text-center text-gray-500 text-sm">
                          No universities found
                        </div>
                      ) : (
                        filteredUniversities.map((university) => (
                          <div
                            key={university.id}
                            className={`px-3 py-2 cursor-pointer hover:bg-gray-50 border-b border-gray-100 last:border-b-0 ${
                              universityFilter === String(university.id) ? 'bg-blue-50 text-[#0B6D76]' : ''
                            }`}
                            onClick={() => handleUniversitySelect(university.id)}
                          >
                            <div className="font-medium truncate">{university.name}</div>
                            <div className="text-xs text-gray-500 truncate">
                              {university.city && `${university.city}, `}
                              {university.country}
                            </div>
                          </div>
                        ))
                      )}
                    </div>
                  </div>
                )}
              </div>
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Country</label>
              <select
                value={countryFilter}
                onChange={(e) => setCountryFilter(e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
              >
                <option value="">All Countries</option>
                {countries.map((country) => (
                  <option key={country.id} value={country.country}>
                    {country.country}
                  </option>
                ))}
              </select>
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Start Date</label>
              <input
                type="date"
                value={startDate}
                onChange={(e) => setStartDate(e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
              />
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">End Date</label>
              <input
                type="date"
                value={endDate}
                onChange={(e) => setEndDate(e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
              />
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Qualification</label>
              <select
                value={qualificationFilter}
                onChange={(e) => setQualificationFilter(e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
              >
                <option value="">Select Qualification</option>
                {levels.map((level) => (
                  <option key={level.id} value={level.id}>
                    {level.title}
                  </option>
                ))}
              </select>
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Popular Status</label>
              <select
                value={popularFilter}
                onChange={(e) => setPopularFilter(e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
              >
                <option value="">All Status</option>
                <option value="true">Popular</option>
                <option value="false">Not Popular</option>
              </select>
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Country Popular Status</label>
              <select
                value={countryPopularFilter}
                onChange={(e) => setCountryPopularFilter(e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
              >
                <option value="">All Status</option>
                <option value="true">Country Popular</option>
                <option value="false">Not Country Popular</option>
              </select>
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Subject</label>
              <select
                value={subjectFilter}
                onChange={(e) => setSubjectFilter(e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
              >
                <option value="">All Subjects</option>
                {subjects.map((subject) => (
                  <option key={subject.id} value={subject.id}>
                    {subject.name}
                  </option>
                ))}
              </select>
            </div>

            {/* NEW: Menu Visibility Filter */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Menu Visibility</label>
              <select
                value={menuVisibilityFilter}
                onChange={(e) => setMenuVisibilityFilter(e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
              >
                <option value="">All</option>
                <option value="true">Visible in Menu</option>
                <option value="false">Hidden in Menu</option>
              </select>
            </div>
          </div>
          
          <div className="flex justify-between items-center mt-4 pt-4 border-t border-gray-200">
            <div className="flex gap-2">
              <button
                onClick={handleSearch}
                className="px-4 py-2 bg-[#0B6D76] text-white rounded-lg hover:bg-[#094F56] transition-colors flex items-center gap-2"
              >
                🔍 Search
              </button>
              {hasActiveFilters && (
                <button
                  onClick={clearFilters}
                  className="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors"
                >
                  Clear Filters
                </button>
              )}
              <button
                onClick={loadAllCourses}
                disabled={isLoadingAll}
                className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
              >
                {isLoadingAll ? '⏳ Loading...' : '📚 Load All Courses'}
              </button>
            </div>
            
            {/* Active Filters Display */}
            {hasActiveFilters && (
              <div className="text-sm text-gray-600 flex flex-wrap gap-2">
                Active filters: 
                {appliedSearchTerm && <span className="px-2 py-1 bg-blue-100 text-blue-800 rounded">Search: "{appliedSearchTerm}"</span>}
                {appliedUniversityFilter && (
                  <span className="px-2 py-1 bg-purple-100 text-purple-800 rounded">
                    University: {universities.find(u => String(u.id) === String(appliedUniversityFilter))?.name || appliedUniversityFilter}
                  </span>
                )}
                {appliedCountryFilter && <span className="px-2 py-1 bg-teal-100 text-teal-800 rounded">Country: {appliedCountryFilter}</span>}
                {appliedStartDate && <span className="px-2 py-1 bg-green-100 text-green-800 rounded">Start: {appliedStartDate}</span>}
                {appliedEndDate && <span className="px-2 py-1 bg-purple-100 text-purple-800 rounded">End: {appliedEndDate}</span>}
                {appliedQualificationFilter && <span className="px-2 py-1 bg-orange-100 text-orange-800 rounded">Qualification: {appliedQualificationFilter}</span>}
                {appliedPopularFilter && <span className="px-2 py-1 bg-pink-100 text-pink-800 rounded">Popular: {appliedPopularFilter === 'true' ? 'Yes' : 'No'}</span>}
                {appliedCountryPopularFilter && <span className="px-2 py-1 bg-yellow-100 text-yellow-800 rounded">Country Popular: {appliedCountryPopularFilter === 'true' ? 'Yes' : 'No'}</span>}
                {appliedSubjectFilter && (
                  <span className="px-2 py-1 bg-indigo-100 text-indigo-800 rounded">
                    Subject: {subjects.find(s => String(s.id) === String(appliedSubjectFilter))?.name || appliedSubjectFilter}
                  </span>
                )}
                {/* NEW: Menu visibility filter display */}
                {appliedMenuVisibilityFilter !== '' && (
                  <span className="px-2 py-1 bg-indigo-100 text-indigo-800 rounded">
                    Menu: {appliedMenuVisibilityFilter === 'true' ? 'Visible' : 'Hidden'}
                  </span>
                )}
              </div>
            )}
          </div>
        </div>
      )}

      {/* Success Message */}
      {courses.length > 0 && (
        <div className="bg-green-50 border border-green-200 rounded-lg p-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center">
              <div className="flex-shrink-0">
                <svg className="h-5 w-2 text-green-400" viewBox="0 0 20 20" fill="currentColor">
                  <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                </svg>
              </div>
              <div className="ml-3">
                <p className="text-sm font-medium text-green-800">
                  Showing {courses.length} courses
                  {!allCoursesLoaded && totalItems > courses.length && (
                    <span className="ml-2 text-green-600">
                      (of {totalItems} total available)
                    </span>
                  )}
                  {allCoursesLoaded && (
                    <span className="ml-2 text-green-600">
                      (all courses loaded)
                    </span>
                  )}
                </p>
              </div>
            </div>
            <div className="text-right">
              {!allCoursesLoaded ? (
                <p className="text-sm font-medium text-green-800">
                  Page {currentPage} of {Math.ceil(totalItems / itemsPerPage)}
                </p>
              ) : (
                <p className="text-sm font-medium text-green-600">
                  All courses loaded
                </p>
              )}
            </div>
          </div>
        </div>
      )}

      {/* Table Section */}
      <div className="bg-white rounded-2xl shadow-xl p-6">
        {fetchingCourses ? (
          <div className="text-center py-12">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-[#0B6D76] mx-auto mb-4"></div>
            <div className="text-gray-500 text-lg">Loading courses...</div>
          </div>
        ) : (
          <>
            <div className="overflow-x-auto">
              <table className="w-full max-w-[1400px]">
                <thead>
                  <tr className="bg-gradient-to-r from-blue-50 to-indigo-50">
                    <th className="px-6 py-4 text-left text-sm font-semibold text-gray-900 rounded-l-xl">Course Name</th>
                    <th className="px-6 py-4 text-left text-sm font-semibold text-gray-900">University Name</th>
                    <th className="px-6 py-4 text-left text-sm font-semibold text-gray-900">Country</th>
                    <th className="px-6 py-4 text-left text-sm font-semibold text-gray-900">Subject</th>
                    <th className="px-6 py-4 text-left text-sm font-semibold text-gray-900">Qualification</th>
                    <th className="px-6 py-4 text-center text-sm font-semibold text-gray-900">Popular</th>
                    <th className="px-6 py-4 text-center text-sm font-semibold text-gray-900">Country Popular</th>
                    <th className="px-6 py-4 text-center text-sm font-semibold text-gray-900">Menu Visible</th> {/* NEW: Menu column */}
                    <th className="px-6 py-4 text-center text-sm font-semibold text-gray-900">Created At</th>
                    <th className="px-6 py-4 text-center text-gray-900 rounded-r-xl">Action</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-200">
                  {courses.map((course) => (
                    <tr key={course.id} className="hover:bg-gray-50 transition-colors">
                      <td className="px-6 py-4 font-medium text-gray-900">{course.name}</td>
                      <td className="px-6 py-4 text-gray-600">
                        {course.university || 'Not Available'}
                      </td>
                      <td className="px-6 py-4 text-gray-600">
                        {course.university_country || 'Not Available'}
                      </td>
                      <td className="px-6 py-4 text-gray-600">
                        {course.subject_name || 'Not Available'}
                      </td>
                      <td className="px-6 py-4 text-gray-600">{course.qualification || course.qualification || '-'}</td>
                      
                      {/* Popular Toggle */}
                      <td className="px-6 py-4 text-center">
                        <label className="inline-flex items-center cursor-pointer">
                          <input
                            type="checkbox"
                            checked={!!course.popular}
                            onChange={() => handleTogglePopular(course)}
                            className="sr-only peer"
                          />
                          <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-[#0B6D76] rounded-full peer peer-checked:bg-[#0B6D76] transition-all duration-200 relative">
                            <div className="absolute left-1 top-1 bg-white w-4 h-4 rounded-full transition-transform duration-200 peer-checked:translate-x-5"></div>
                          </div>
                          <span className={`ml-2 text-sm font-medium ${course.popular ? 'text-[#0B6D76]' : 'text-gray-400'}`}>{course.popular ? 'On' : 'Off'}</span>
                        </label>
                      </td>
                      
                      {/* Country Popular Toggle */}
                      <td className="px-6 py-4 text-center">
                        <label className="inline-flex items-center cursor-pointer">
                          <input
                            type="checkbox"
                            checked={!!course.country_popular}
                            onChange={() => handleToggleCountryPopular(course)}
                            className="sr-only peer"
                          />
                          <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-[#0B6D76] rounded-full peer peer-checked:bg-[#0B6D76] transition-all duration-200 relative">
                            <div className="absolute left-1 top-1 bg-white w-4 h-4 rounded-full transition-transform duration-200 peer-checked:translate-x-5"></div>
                          </div>
                          <span className={`ml-2 text-sm font-medium ${course.country_popular ? 'text-[#0B6D76]' : 'text-gray-400'}`}>{course.country_popular ? 'On' : 'Off'}</span>
                        </label>
                      </td>

                      {/* NEW: Menu Visibility Toggle */}
                      <td className="px-6 py-4 text-center">
                        <label className="inline-flex items-center cursor-pointer">
                          <input
                            type="checkbox"
                            checked={course.show_in_menu !== undefined ? course.show_in_menu : true}
                            onChange={() => handleToggleMenuVisibility(course.id, course.show_in_menu)}
                            className="sr-only peer"
                          />
                          <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-[#0B6D76] rounded-full peer peer-checked:bg-[#0B6D76] transition-all duration-200 relative">
                            <div className="absolute left-1 top-1 bg-white w-4 h-4 rounded-full transition-transform duration-200 peer-checked:translate-x-5"></div>
                          </div>
                          <span className={`ml-2 text-sm font-medium ${(course.show_in_menu !== undefined ? course.show_in_menu : true) ? 'text-[#0B6D76]' : 'text-gray-400'}`}>
                            {(course.show_in_menu !== undefined ? course.show_in_menu : true) ? 'Visible' : 'Hidden'}
                          </span>
                        </label>
                      </td>
                      
                      <td className="px-6 py-4 text-center text-gray-500">
                        {new Date(course.created_at).toLocaleDateString()}
                      </td>
                      <td className="px-6 py-4 text-center">
                        <button
                          onClick={() => handleEdit(course)}
                          className="p-2 text-green-600 hover:bg-green-100 rounded-lg transition-colors mr-2"
                          title="Edit Course"
                        >
                          <Edit className="w-4 h-4" />
                        </button>
                        <button
                          onClick={() => handleDelete(course.id)}
                          className="p-2 text-red-600 hover:bg-red-100 rounded-lg transition-colors"
                          title="Delete Course"
                        >
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            {courses.length === 0 && (
              <div className="text-center py-12">
                <div className="text-gray-500 text-lg">
                  {hasActiveFilters ? 'No courses found matching your filters.' : 'No courses found'}
                </div>
                <p className="text-gray-400 mt-2">
                  {hasActiveFilters ? 'Try adjusting your search criteria or clear filters' : 'Try adding a new course'}
                </p>
                {hasActiveFilters && (
                  <button
                    onClick={clearFilters}
                    className="mt-4 px-4 py-2 bg-[#0B6D76] text-white rounded-lg hover:bg-[#09545c] transition-colors"
                  >
                    Clear all filters
                  </button>
                )}
              </div>
            )}
          </>
        )}
      </div>

      {/* Pagination Component */}
      {!allCoursesLoaded && Math.ceil(totalItems / itemsPerPage) > 1 && (
        <div className="bg-white rounded-2xl shadow-xl p-6">
          <div className="text-center mb-4">
            <p className="text-gray-600 mb-2">
              Currently showing page {currentPage} of {Math.ceil(totalItems / itemsPerPage)}
            </p>
            <p className="text-sm text-gray-500">
              Showing {courses.length} courses per page. Use pagination below or load all courses at once.
            </p>
          </div>
          <Pagination
            currentPage={currentPage}
            totalPages={Math.ceil(totalItems / itemsPerPage)}
            onPageChange={setCurrentPage}
            totalItems={totalItems}
          />
        </div>
      )}
      
      {/* All Courses Loaded Message */}
      {allCoursesLoaded && (
        <div className="bg-blue-50 border border-blue-200 rounded-lg p-4 text-center">
          <p className="text-blue-800 font-medium">
            🎉 All {courses.length} courses have been loaded and are now visible!
          </p>
          <p className="text-blue-600 text-sm mt-1">
            No more pagination needed - you can see everything at once.
          </p>
          <button
            onClick={resetToPaginatedView}
            className="mt-3 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          >
            🔄 Back to Paginated View
          </button>
        </div>
      )}

      {/* Edit Modal */}
      {editModalOpen && selectedCourse && (
        <div className="fixed inset-0 bg-black/30 backdrop-blur-sm flex items-center justify-center z-50">
          <div className="bg-white max-w-4xl w-full rounded-xl shadow-xl p-6 overflow-y-auto max-h-[90vh]">
            <h2 className="text-xl font-bold mb-4 text-center">Edit Course: {selectedCourse.name}</h2>
            <AddCourse
              initialData={selectedCourse}
              onSubmit={handleEditSubmit}
              loading={loading}
              onCancel={() => {
                setEditModalOpen(false);
                setSelectedCourse(null);
              }}
            />
          </div>
        </div>
      )}

      {/* Import Modal */}
      {importModalOpen && (
        <div className="fixed inset-0 bg-black/30 backdrop-blur-sm flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-2xl shadow-xl p-6 w-full max-w-2xl max-h-[90vh] overflow-y-auto">
            <div className="flex justify-between items-center mb-6">
              <h2 className="text-xl font-bold text-gray-900">Import Courses from Excel</h2>
              <button
                onClick={closeImportModal}
                className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            <div className="space-y-6">
              {/* Instructions */}
              <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                <h3 className="font-semibold text-blue-800 mb-2">Instructions:</h3>
                <ul className="text-sm text-blue-700 space-y-1 list-disc list-inside">
                  <li>Download the template file to see the required format</li>
                  <li>Ensure university names and course categories match existing records</li>
                  <li>Duplicate entries will be updated instead of creating new ones</li>
                  <li>Required fields: Program Name, University Name, Course Category, Study Level</li>
                </ul>
              </div>

              {/* File Upload */}
              <div className="space-y-4">
                <label className="block text-sm font-medium text-gray-700">
                  Select Excel File
                </label>
                <div className="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-gray-400 transition-colors">
                  <input
                    type="file"
                    accept=".xlsx,.xls,.ods"
                    onChange={handleFileSelect}
                    className="hidden"
                    id="file-upload"
                  />
                  <label
                    htmlFor="file-upload"
                    className="cursor-pointer block"
                  >
                    <Upload className="w-12 h-12 text-gray-400 mx-auto mb-3" />
                    <p className="text-gray-600 mb-1">
                      {importFile ? importFile.name : 'Click to select Excel file'}
                    </p>
                    <p className="text-sm text-gray-500">
                      Supports .xlsx, .xls, .ods files
                    </p>
                  </label>
                </div>
              </div>

              {/* Import Results */}
              {importResults && (
                <div className={`p-4 rounded-lg ${
                  importResults.results.failed > 0 ? 'bg-yellow-50 border border-yellow-200' : 'bg-green-50 border border-green-200'
                }`}>
                  <h3 className="font-semibold mb-2">Import Results:</h3>
                  <p><strong>Total:</strong> {importResults.results.total} rows</p>
                  <p><strong>Successful:</strong> {importResults.results.successful} 
                    ({importResults.results.created} created, {importResults.results.updated} updated)
                  </p>
                  <p><strong>Failed:</strong> {importResults.results.failed}</p>
                  
                  {importResults.results.failed > 0 && (
                    <div className="mt-3">
                      <h4 className="font-medium text-sm mb-2">Failed Rows:</h4>
                      <div className="max-h-40 overflow-y-auto text-sm">
                        {importResults.results.failedRows.slice(0, 10).map((row, index) => (
                          <div key={index} className="border-b border-gray-200 py-1">
                            <span className="font-medium">Row {row.rowNumber}:</span> {row.reason}
                          </div>
                        ))}
                        {importResults.results.failedRows.length > 10 && (
                          <p className="text-sm text-gray-600 mt-1">
                            ... and {importResults.results.failedRows.length - 10} more failures
                          </p>
                        )}
                      </div>
                    </div>
                  )}
                </div>
              )}

              {/* Action Buttons */}
              <div className="flex justify-end gap-3 pt-4 border-t border-gray-200">
                <button
                  onClick={closeImportModal}
                  className="px-4 py-2 text-gray-700 hover:bg-gray-100 rounded-lg transition-colors"
                  disabled={importing}
                >
                  Cancel
                </button>
                <button
                  onClick={handleImportSubmit}
                  disabled={!importFile || importing}
                  className="px-4 py-2 bg-[#0B6D76] text-white rounded-lg hover:bg-[#09545c] transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
                >
                  {importing ? (
                    <>
                      <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                      Importing...
                    </>
                  ) : (
                    <>
                      <Upload className="w-4 h-4" />
                      Import Courses
                    </>
                  )}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
    </>
  );
};

export default CourseList;