import React, { useEffect, useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { Add, CalendarToday, FilterList, MenuBook, People, Search } from '@mui/icons-material';
import useTimetableStore from '../../stores/timetableStore';
import { useUser } from '../../contexts/UserContext';

const ClassesPage: React.FC = () => {
  const navigate = useNavigate();
  const { profile } = useUser();
  const {
    classes,
    totalCount,
    classesLoading,
    classesError,
    currentPage,
    pageSize,
    filterSubject,
    filterSchoolYear,
    filterAcademicTerm,
    searchQuery,
    fetchClasses,
    setFilterSubject,
    setFilterSchoolYear,
    setFilterAcademicTerm,
    setSearchQuery,
    setPage,
    clearFilters,
  } = useTimetableStore();

  const [showFilters, setShowFilters] = useState(false);

  useEffect(() => {
    fetchClasses({
      subject: filterSubject || undefined,
      school_year: filterSchoolYear || undefined,
      academic_term: filterAcademicTerm || undefined,
      search: searchQuery || undefined,
      skip: currentPage * pageSize,
      limit: pageSize,
    });
  }, [filterSubject, filterSchoolYear, filterAcademicTerm, searchQuery, currentPage, pageSize]);

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    setPage(0);
    fetchClasses({
      subject: filterSubject || undefined,
      school_year: filterSchoolYear || undefined,
      academic_term: filterAcademicTerm || undefined,
      search: searchQuery || undefined,
      skip: 0,
      limit: pageSize,
    });
  };

  const totalPages = Math.ceil(totalCount / pageSize);

  return (
    <div className="container mx-auto px-4 py-6 max-w-7xl">
      {/* Header */}
      <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4 mb-6">
        <div>
          <h1 className="text-3xl font-bold text-gray-900">Classes</h1>
          <p className="text-gray-600 mt-1">
            Manage classes, timetables, and student enrollments
          </p>
        </div>
        {(profile?.role === 'teacher' || profile?.role === 'admin') && (
          <button
            onClick={() => navigate('/timetable/classes/create')}
            className="inline-flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          >
            <Add size={20} />
            Create Class
          </button>
        )}
      </div>

      {/* Search and Filters */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-4 mb-6">
        <form onSubmit={handleSearch} className="flex flex-col md:flex-row gap-4">
          <div className="flex-1 relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" size={20} />
            <input
              type="text"
              placeholder="Search classes by name or subject..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            />
          </div>
          <button
            type="button"
            onClick={() => setShowFilters(!showFilters)}
            className="inline-flex items-center gap-2 px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
          >
            <FilterList size={20} />
            Filters
          </button>
          <button
            type="submit"
            className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          >
            Search
          </button>
        </form>

        {showFilters && (
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mt-4 pt-4 border-t border-gray-200">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Subject</label>
              <select
                value={filterSubject || ''}
                onChange={(e) => setFilterSubject(e.target.value || null)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
              >
                <option value="">All Subjects</option>
                <option value="Mathematics">Mathematics</option>
                <option value="Science">Science</option>
                <option value="English">English</option>
                <option value="History">History</option>
                <option value="Geography">Geography</option>
                <option value="Art">Art</option>
                <option value="Music">Music</option>
                <option value="Physical Education">Physical Education</option>
                <option value="Computer Science">Computer Science</option>
                <option value="Foreign Language">Foreign Language</option>
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">School Year</label>
              <select
                value={filterSchoolYear || ''}
                onChange={(e) => setFilterSchoolYear(e.target.value || null)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
              >
                <option value="">All Years</option>
                <option value="2025-2026">2025-2026</option>
                <option value="2024-2025">2024-2025</option>
                <option value="2023-2024">2023-2024</option>
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Term</label>
              <select
                value={filterAcademicTerm || ''}
                onChange={(e) => setFilterAcademicTerm(e.target.value || null)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
              >
                <option value="">All Terms</option>
                <option value="Fall">Fall</option>
                <option value="Spring">Spring</option>
                <option value="Summer">Summer</option>
                <option value="Full Year">Full Year</option>
              </select>
            </div>
          </div>
        )}
      </div>

      {/* Error Message */}
      {classesError && (
        <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg mb-6">
          {classesError}
        </div>
      )}

      {/* Classes Grid */}
      {classesLoading ? (
        <div className="flex justify-center items-center py-12">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
        </div>
      ) : classes.length === 0 ? (
        <div className="text-center py-12 bg-gray-50 rounded-xl">
          <MenuBook className="mx-auto h-12 w-12 text-gray-400 mb-4" />
          <h3 className="text-lg font-medium text-gray-900">No classes found</h3>
          <p className="text-gray-600 mt-1">
            {searchQuery || filterSubject || filterSchoolYear
              ? 'Try adjusting your filters'
              : 'Create your first class to get started'}
          </p>
        </div>
      ) : (
        <>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {classes.map((cls) => (
              <Link
                key={cls.id}
                to={`/timetable/classes/${cls.id}`}
                className="bg-white rounded-xl shadow-sm border border-gray-200 p-6 hover:shadow-md hover:border-blue-300 transition-all"
              >
                <div className="flex items-start justify-between mb-4">
                  <div className="p-2 bg-blue-50 rounded-lg">
                    <MenuBook className="text-blue-600" size={24} />
                  </div>
                  <span className="px-2 py-1 bg-gray-100 text-gray-600 text-xs font-medium rounded-full">
                    {cls.subject}
                  </span>
                </div>
                <h3 className="text-lg font-semibold text-gray-900 mb-1">{cls.name}</h3>
                <p className="text-gray-500 text-sm mb-4">
                  {cls.school_year} • {cls.academic_term}
                </p>
                <div className="flex items-center gap-4 text-sm text-gray-600">
                  <span className="flex items-center gap-1">
                    <People size={16} />
                    {cls.student_count} students
                  </span>
                  <span className="flex items-center gap-1">
                    <CalendarToday size={16} />
                    {cls.timetable_count} timetables
                  </span>
                </div>
              </Link>
            ))}
          </div>

          {/* Pagination */}
          {totalPages > 1 && (
            <div className="flex justify-center items-center gap-2 mt-8">
              <button
                onClick={() => setPage(currentPage - 1)}
                disabled={currentPage === 0}
                className="px-3 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                Previous
              </button>
              <span className="text-gray-600">
                Page {currentPage + 1} of {totalPages}
              </span>
              <button
                onClick={() => setPage(currentPage + 1)}
                disabled={currentPage >= totalPages - 1}
                className="px-3 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                Next
              </button>
            </div>
          )}
        </>
      )}
    </div>
  );
};

export default ClassesPage;
