import { useState, useEffect, useMemo } from 'react';
import api from '../../store/api';
import { 
  GraduationCap, Users, CheckCircle2, AlertCircle, 
  Info, ArrowRight, RefreshCw, UserCheck, UserX, 
  Calendar, Search, Filter, AlertTriangle, ShieldCheck,
  TrendingUp, Clock
} from 'lucide-react';
import { Avatar } from '../../components/Avatar';

interface Student {
  student_id: number;
  first_name: string;
  last_name: string;
  email: string;
  enrollment_id: number;
  class_id: number;
  roll_number: string;
  academic_year: string;
  class_name: string;
  class_section: string;
}

interface ClassItem {
  id: number;
  name: string;
  section: string;
  capacity: number;
}

type RolloverMode = 'term' | 'year';
type ExceptionAction = 'promote' | 'repeat' | 'transfer' | 'graduate';

export default function AcademicRollover() {
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [processing, setProcessing] = useState(false);
  const [successResult, setSuccessResult] = useState<any | null>(null);
  const [errorMsg, setErrorMsg] = useState<string | null>(null);

  // Transition mode: 'term' (mid-year term update) or 'year' (full grade promotion)
  const [rolloverMode, setRolloverMode] = useState<RolloverMode>('term');

  // Loaded database settings
  const [currentYear, setCurrentYear] = useState('');
  const [currentTerm, setCurrentTerm] = useState('');
  const [nextYear, setNextYear] = useState('');
  const [nextTerm, setNextTerm] = useState('');
  const [termStartDate, setTermStartDate] = useState('');
  const [termEndDate, setTermEndDate] = useState('');
  const [classes, setClasses] = useState<ClassItem[]>([]);
  const [students, setStudents] = useState<Student[]>([]);

  // Current tab flow: 'classes' | 'students' | 'confirm'
  const [activeTab, setActiveTab] = useState<'classes' | 'students' | 'confirm'>('students');
  
  // Year Rollover mappings & exceptions state
  const [classMappings, setClassMappings] = useState<Record<number, number | 'graduate'>>({});
  const [studentExceptions, setStudentExceptions] = useState<Record<number, ExceptionAction>>({});

  // Student Exceptions Tab Search/Filters
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedClassFilter, setSelectedClassFilter] = useState<string>('all');
  const [selectedActionFilter, setSelectedActionFilter] = useState<string>('all');

  useEffect(() => {
    loadData(true);
  }, []);

  // Sync tab selection when mode changes to prevent getting stuck in Class tab in Term mode
  useEffect(() => {
    if (rolloverMode === 'term' && activeTab === 'classes') {
      setActiveTab('students');
    }
  }, [rolloverMode, activeTab]);

  const loadData = async (initial = false) => {
    if (initial) setLoading(true);
    else setRefreshing(true);
    
    setErrorMsg(null);
    setSuccessResult(null);

    try {
      const res = await api.get('/academic-rollover/data');
      const { 
        currentAcademicYear, 
        currentTerm: loadedTerm,
        termStartDate: loadedStart,
        termEndDate: loadedEnd,
        classes: loadedClasses, 
        students: loadedStudents 
      } = res.data;
      
      setCurrentYear(currentAcademicYear);
      setCurrentTerm(loadedTerm);
      setTermStartDate(loadedStart || '');
      setTermEndDate(loadedEnd || '');

      // Guess next year (current + 1)
      const nextY = (parseInt(currentAcademicYear, 10) + 1).toString();
      setNextYear(nextY);

      // Guess next term
      if (loadedTerm === 'Term 1') setNextTerm('Term 2');
      else if (loadedTerm === 'Term 2') setNextTerm('Term 3');
      else setNextTerm('Term 1');
      
      setClasses(loadedClasses);
      setStudents(loadedStudents);

      // Initialize year rollover class mappings by trying to guess the next class
      const initialMappings: Record<number, number | 'graduate'> = {};
      loadedClasses.forEach((c: ClassItem) => {
        initialMappings[c.id] = guessNextClass(c, loadedClasses);
      });
      setClassMappings(initialMappings);
      setStudentExceptions({});
    } catch (err: any) {
      setErrorMsg(err.response?.data?.error || 'Failed to load rollover metadata. Please verify database availability.');
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  // Guess next class based on number increment
  const guessNextClass = (currentClass: ClassItem, all: ClassItem[]): number | 'graduate' => {
    const match = currentClass.name.match(/\d+/);
    if (!match) return 'graduate';
    
    const currentNum = parseInt(match[0], 10);
    const nextNum = currentNum + 1;
    const nextNameGuess = currentClass.name.replace(String(currentNum), String(nextNum));

    // Try finding matching name + section
    const found = all.find(c => 
      c.name.toLowerCase() === nextNameGuess.toLowerCase() && 
      c.section.toLowerCase() === currentClass.section.toLowerCase()
    );
    if (found) return found.id;

    // Fallback name only
    const foundByName = all.find(c => c.name.toLowerCase() === nextNameGuess.toLowerCase());
    if (foundByName) return foundByName.id;

    return 'graduate';
  };

  const handleClassMappingChange = (currentClassId: number, nextClassId: number | 'graduate') => {
    setClassMappings(prev => ({ ...prev, [currentClassId]: nextClassId }));
  };

  const handleStudentActionChange = (studentId: number, action: ExceptionAction) => {
    setStudentExceptions(prev => ({ ...prev, [studentId]: action }));
  };

  const handleAutoMapAll = () => {
    const updated: Record<number, number | 'graduate'> = {};
    classes.forEach(c => {
      updated[c.id] = guessNextClass(c, classes);
    });
    setClassMappings(updated);
  };

  const handleBulkGraduateForm4s = () => {
    const updated = { ...studentExceptions };
    students.forEach(s => {
      if (s.class_name.toLowerCase().startsWith('form 4')) {
        updated[s.student_id] = 'graduate';
      }
    });
    setStudentExceptions(updated);
  };

  // Filtered student list
  const filteredStudents = useMemo(() => {
    return students.filter(s => {
      const matchesSearch = `${s.first_name} ${s.last_name}`.toLowerCase().includes(searchQuery.toLowerCase()) ||
                            s.email.toLowerCase().includes(searchQuery.toLowerCase()) ||
                            s.roll_number.toLowerCase().includes(searchQuery.toLowerCase());
      
      const matchesClass = selectedClassFilter === 'all' || s.class_name === selectedClassFilter;
      
      const currentAction = studentExceptions[s.student_id] || 'promote';
      const matchesAction = selectedActionFilter === 'all' || currentAction === selectedActionFilter;

      return matchesSearch && matchesClass && matchesAction;
    });
  }, [students, searchQuery, selectedClassFilter, selectedActionFilter, studentExceptions]);

  // Available exceptions actions
  const availableActions = useMemo(() => {
    return rolloverMode === 'term'
      ? ['promote', 'transfer', 'graduate'] // promote acts as 'Continue' in Term mode
      : ['promote', 'repeat', 'transfer', 'graduate'];
  }, [rolloverMode]);

  // Calculations for transition review summary
  const summaryStats = useMemo(() => {
    let promoted = 0;
    let repeated = 0;
    let transferred = 0;
    let graduated = 0;
    let continuing = 0; // Term mode specific

    students.forEach(s => {
      const action = studentExceptions[s.student_id] || 'promote';
      if (rolloverMode === 'term') {
        if (action === 'transfer') {
          transferred++;
        } else if (action === 'graduate') {
          graduated++;
        } else {
          continuing++;
        }
      } else {
        // year mode
        if (action === 'repeat') {
          repeated++;
        } else if (action === 'transfer') {
          transferred++;
        } else if (action === 'graduate') {
          graduated++;
        } else {
          // promote
          const target = classMappings[s.class_id];
          if (target === 'graduate' || !target) {
            graduated++;
          } else {
            promoted++;
          }
        }
      }
    });

    return { promoted, repeated, transferred, graduated, continuing };
  }, [students, studentExceptions, classMappings, rolloverMode]);

  // Execute transition
  const handleRunRollover = async () => {
    const promptMsg = rolloverMode === 'term' 
      ? `Are you sure you want to transition to ${nextTerm}? Flagged students will be processed and active term dates will be updated.`
      : `Are you absolutely sure you want to run the full academic rollover to ${nextYear}? This operation will archive all current active enrollments and cannot be undone.`;

    if (!window.confirm(promptMsg)) {
      return;
    }

    setProcessing(true);
    setErrorMsg(null);
    setSuccessResult(null);

    try {
      const exceptionsList = Object.entries(studentExceptions).map(([id, act]) => ({
        studentId: Number(id),
        action: act
      }));

      const payload: any = {
        mode: rolloverMode,
        nextTerm,
        termStartDate,
        termEndDate,
        studentExceptions: exceptionsList
      };

      if (rolloverMode === 'year') {
        const mappedList = Object.entries(classMappings).map(([curr, next]) => ({
          currentClassId: Number(curr),
          nextClassId: next
        }));

        payload.nextAcademicYear = nextYear;
        payload.classMappings = mappedList;
      }

      const res = await api.post('/academic-rollover/run', payload);

      setSuccessResult(res.data);
      // Reload updated years/terms from settings
      loadData();
    } catch (err: any) {
      setErrorMsg(err.response?.data?.error || 'Transition failed. Check database locks and configurations.');
    } finally {
      setProcessing(false);
    }
  };

  return (
    <div className="space-y-8 animate-in fade-in duration-500 pb-16">
      
      {/* Header */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
        <div>
          <div className="flex items-center gap-3 mb-1">
            <h1 className="text-3xl font-black text-text tracking-tight uppercase">Academic Rollover</h1>
            <div className="bg-primary/10 text-primary border border-primary/20 px-3 py-1 rounded-full text-[0.65rem] font-black uppercase tracking-wider">
              Year & Term Progression
            </div>
          </div>
          <p className="text-text-muted text-sm font-medium">
            Manage term transitions or process full end-of-year grade promotions and rollover, complete with student flagging exceptions.
          </p>
        </div>
        <button
          onClick={() => loadData(false)}
          disabled={loading || refreshing}
          className="flex items-center gap-2 px-4 py-2 border border-border bg-card hover:bg-background-alt text-text rounded-xl font-bold text-sm transition-all shadow-sm disabled:opacity-50"
        >
          <RefreshCw size={14} className={refreshing ? 'animate-spin' : ''} /> 
          {refreshing ? 'Refreshing...' : 'Refresh Registry'}
        </button>
      </div>

      {/* Mode Selection Control */}
      <div className="flex items-center gap-4">
        <span className="text-xs font-black text-text-muted uppercase tracking-wider">Transition Type:</span>
        <div className="flex bg-card border border-border p-1.5 rounded-2xl max-w-md flex-1 md:flex-initial">
          <button
            onClick={() => { setRolloverMode('term'); setSuccessResult(null); }}
            className={`flex-1 md:flex-initial px-6 py-2 rounded-xl text-xs font-black uppercase tracking-wider transition-all ${rolloverMode === 'term' ? 'bg-primary text-white shadow-md shadow-primary/15' : 'text-text-muted hover:text-text hover:bg-background-alt'}`}
          >
            Term Transition
          </button>
          <button
            onClick={() => { setRolloverMode('year'); setSuccessResult(null); }}
            className={`flex-1 md:flex-initial px-6 py-2 rounded-xl text-xs font-black uppercase tracking-wider transition-all ${rolloverMode === 'year' ? 'bg-primary text-white shadow-md shadow-primary/15' : 'text-text-muted hover:text-text hover:bg-background-alt'}`}
          >
            Academic Year Rollover
          </button>
        </div>
      </div>

      {successResult && (
        <div className="bg-emerald-500/10 border border-emerald-500/20 text-emerald-600 rounded-3xl p-6 flex flex-col md:flex-row items-center gap-4">
          <CheckCircle2 size={40} className="text-emerald-500 flex-shrink-0" />
          <div className="flex-1">
            <h3 className="font-bold text-lg text-emerald-800">Transition Executed Successfully!</h3>
            <p className="text-sm mt-1 text-emerald-600/90">{successResult.message}</p>
            <div className="grid grid-cols-4 gap-4 mt-4 bg-emerald-500/5 rounded-2xl p-3 border border-emerald-500/10 text-center">
              {rolloverMode === 'term' ? (
                <>
                  <div className="col-span-2">
                    <p className="text-[0.65rem] font-bold text-emerald-800/60 uppercase">Term Activated</p>
                    <p className="text-xl font-black">{successResult.stats?.nextTerm}</p>
                  </div>
                  <div>
                    <p className="text-[0.65rem] font-bold text-emerald-800/60 uppercase">Transferred Out</p>
                    <p className="text-xl font-black">{successResult.stats?.transferred}</p>
                  </div>
                  <div>
                    <p className="text-[0.65rem] font-bold text-emerald-800/60 uppercase">Graduated</p>
                    <p className="text-xl font-black">{successResult.stats?.graduated}</p>
                  </div>
                </>
              ) : (
                <>
                  <div>
                    <p className="text-[0.65rem] font-bold text-emerald-800/60 uppercase">Promoted</p>
                    <p className="text-xl font-black">{successResult.stats?.promoted}</p>
                  </div>
                  <div>
                    <p className="text-[0.65rem] font-bold text-emerald-800/60 uppercase">Repeated</p>
                    <p className="text-xl font-black">{successResult.stats?.repeated}</p>
                  </div>
                  <div>
                    <p className="text-[0.65rem] font-bold text-emerald-800/60 uppercase">Transferred</p>
                    <p className="text-xl font-black">{successResult.stats?.transferred}</p>
                  </div>
                  <div>
                    <p className="text-[0.65rem] font-bold text-emerald-800/60 uppercase">Graduated</p>
                    <p className="text-xl font-black">{successResult.stats?.graduated}</p>
                  </div>
                </>
              )}
            </div>
          </div>
        </div>
      )}

      {errorMsg && (
        <div className="bg-rose-500/10 border border-rose-500/20 text-rose-600 rounded-3xl p-6 flex items-center gap-4">
          <AlertCircle size={32} className="text-rose-500 flex-shrink-0" />
          <div>
            <h3 className="font-bold">Execution Blocked</h3>
            <p className="text-sm mt-1">{errorMsg}</p>
          </div>
        </div>
      )}

      {/* Main Rollover Setup Card */}
      <div className="bg-card border border-border rounded-[2.5rem] shadow-sm overflow-hidden">
        
        {/* Top parameters bar */}
        <div className="p-6 border-b border-border bg-background-alt/30 grid grid-cols-1 md:grid-cols-3 gap-6 items-center">
          <div>
            <span className="block text-[0.65rem] font-black uppercase tracking-widest text-text-muted mb-1">Active Year & Term</span>
            <div className="flex items-center gap-2">
              <Calendar size={16} className="text-primary" />
              <span className="text-lg font-black text-text">{currentYear} ({currentTerm})</span>
            </div>
          </div>
          
          {rolloverMode === 'year' ? (
            <>
              <div className="flex items-center gap-2">
                <ArrowRight size={20} className="text-text-muted/40 hidden md:block" />
                <div className="flex-1">
                  <span className="block text-[0.65rem] font-black uppercase tracking-widest text-text-muted mb-1">Next Academic Year</span>
                  <input 
                    type="text"
                    value={nextYear}
                    onChange={e => setNextYear(e.target.value)}
                    placeholder="e.g. 2027"
                    className="w-full bg-background border border-border rounded-xl px-3 py-2 text-sm font-bold text-text focus:outline-none"
                  />
                </div>
              </div>
              <div className="flex items-center gap-2">
                <div className="flex-1">
                  <span className="block text-[0.65rem] font-black uppercase tracking-widest text-text-muted mb-1">Rollover Reset Term</span>
                  <select
                    value={nextTerm}
                    onChange={e => setNextTerm(e.target.value)}
                    className="w-full bg-background border border-border rounded-xl px-2 py-2 text-sm font-bold text-text focus:outline-none"
                  >
                    <option value="Term 1">Term 1</option>
                    <option value="Term 2">Term 2</option>
                    <option value="Term 3">Term 3</option>
                  </select>
                </div>
              </div>
            </>
          ) : (
            <>
              <div className="flex items-center gap-2">
                <ArrowRight size={20} className="text-text-muted/40 hidden md:block" />
                <div className="flex-1">
                  <span className="block text-[0.65rem] font-black uppercase tracking-widest text-text-muted mb-1">Next Target Term</span>
                  <select
                    value={nextTerm}
                    onChange={e => setNextTerm(e.target.value)}
                    className="w-full bg-background border border-border rounded-xl px-2 py-2.5 text-sm font-bold text-text focus:outline-none"
                  >
                    <option value="Term 1">Term 1</option>
                    <option value="Term 2">Term 2</option>
                    <option value="Term 3">Term 3</option>
                  </select>
                </div>
              </div>
              <div className="bg-amber-500/5 border border-amber-500/10 rounded-2xl p-3 flex gap-2.5 items-start">
                <Info size={18} className="text-amber-500 flex-shrink-0 mt-0.5" />
                <div className="text-xs text-text-muted">
                  <p className="font-bold text-amber-800">Mid-Year Term Transition</p>
                  <p className="mt-0.5">Students stay in current classes. Flagged withdrawals will be processed.</p>
                </div>
              </div>
            </>
          )}
        </div>

        {/* Tab Selection */}
        <div className="flex border-b border-border">
          {rolloverMode === 'year' && (
            <button
              onClick={() => setActiveTab('classes')}
              className={`flex-1 py-4 text-center font-bold text-sm border-b-2 transition-all ${activeTab === 'classes' ? 'border-primary text-primary bg-primary/5' : 'border-transparent text-text-muted hover:text-text'}`}
            >
              1. Class Transitions Map ({classes.length})
            </button>
          )}
          <button
            onClick={() => setActiveTab('students')}
            className={`flex-1 py-4 text-center font-bold text-sm border-b-2 transition-all ${activeTab === 'students' ? 'border-primary text-primary bg-primary/5' : 'border-transparent text-text-muted hover:text-text'}`}
          >
            {rolloverMode === 'term' ? '1. Student Flags & Exceptions' : '2. Student Flags & Exceptions'} ({students.length})
          </button>
          <button
            onClick={() => setActiveTab('confirm')}
            className={`flex-1 py-4 text-center font-bold text-sm border-b-2 transition-all ${activeTab === 'confirm' ? 'border-primary text-primary bg-primary/5' : 'border-transparent text-text-muted hover:text-text'}`}
          >
            {rolloverMode === 'term' ? '2. Finalize & Transition' : '3. Finalize & Rollover'}
          </button>
        </div>

        {/* Tab 1 Content: Class Mappings (Year mode only) */}
        {rolloverMode === 'year' && activeTab === 'classes' && (
          <div className="p-6 space-y-6">
            <div className="flex justify-between items-center gap-4">
              <div>
                <h3 className="font-black text-lg text-text uppercase tracking-tight">Grade Mappings</h3>
                <p className="text-xs text-text-muted mt-0.5">Map current cohorts to their target classes/forms. Non-mapped classes default to Graduation.</p>
              </div>
              <button
                onClick={handleAutoMapAll}
                className="px-4 py-2 bg-primary/10 text-primary hover:bg-primary/20 border border-primary/20 rounded-xl font-bold text-xs transition-colors"
              >
                Auto-Detect Next Grades
              </button>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {classes.map(cls => (
                <div key={cls.id} className="bg-background border border-border rounded-2xl p-4 flex items-center justify-between gap-4 hover:border-primary/50 transition-colors">
                  <div className="min-w-0">
                    <span className="text-[0.65rem] font-bold text-text-muted uppercase">Current Class</span>
                    <p className="font-black text-text text-base truncate">{cls.name} - {cls.section}</p>
                  </div>
                  <ArrowRight size={16} className="text-text-muted/30 flex-shrink-0" />
                  <div className="flex-1 max-w-[200px]">
                    <span className="block text-[0.65rem] font-bold text-text-muted uppercase mb-1">Target Class</span>
                    <select
                      value={classMappings[cls.id] || ''}
                      onChange={e => handleClassMappingChange(cls.id, e.target.value === 'graduate' ? 'graduate' : Number(e.target.value))}
                      className="w-full bg-card border border-border rounded-lg px-2.5 py-1.5 text-xs font-bold text-text"
                    >
                      <option value="graduate">🎓 Graduate / Exit</option>
                      {classes.map(c => (
                        <option key={c.id} value={c.id}>➡️ {c.name} - {c.section}</option>
                      ))}
                    </select>
                  </div>
                </div>
              ))}
            </div>
            
            <div className="flex justify-end pt-4">
              <button
                onClick={() => setActiveTab('students')}
                className="px-6 py-2.5 bg-primary text-white hover:bg-primary-dark rounded-xl font-bold text-sm shadow-md transition-all"
              >
                Next: Verify Students
              </button>
            </div>
          </div>
        )}

        {/* Tab 2 Content: Student Exceptions */}
        {activeTab === 'students' && (
          <div className="space-y-4">
            
            {/* Search and Filters */}
            <div className="p-4 bg-background-alt/30 border-b border-border flex flex-wrap items-center gap-3">
              <div className="relative flex-1 min-w-[260px]">
                <Search className="absolute left-3.5 top-1/2 -translate-y-1/2 text-text-muted" size={16} />
                <input
                  type="text"
                  value={searchQuery}
                  onChange={e => setSearchQuery(e.target.value)}
                  placeholder="Search student by name, email, or roll..."
                  className="w-full pl-10 pr-4 py-2 bg-background border border-border rounded-xl text-sm text-text focus:outline-none focus:border-primary transition-all placeholder:text-text-muted/50"
                />
              </div>

              <div className="flex items-center gap-2">
                <Filter size={14} className="text-text-muted" />
                <select
                  value={selectedClassFilter}
                  onChange={e => setSelectedClassFilter(e.target.value)}
                  className="px-3 py-2 bg-background border border-border rounded-xl text-xs font-bold text-text"
                >
                  <option value="all">All Classes</option>
                  {Array.from(new Set(students.map(s => s.class_name))).map(name => (
                    <option key={name} value={name}>{name}</option>
                  ))}
                </select>

                <select
                  value={selectedActionFilter}
                  onChange={e => setSelectedActionFilter(e.target.value)}
                  className="px-3 py-2 bg-background border border-border rounded-xl text-xs font-bold text-text"
                >
                  <option value="all">All Flags</option>
                  <option value="promote">{rolloverMode === 'term' ? 'Continuing' : 'Promoting'}</option>
                  {rolloverMode === 'year' && <option value="repeat">Repeating</option>}
                  <option value="transfer">Transferring</option>
                  <option value="graduate">Graduating</option>
                </select>

                {students.some(s => s.class_name.toLowerCase().startsWith('form 4')) && (
                  <button
                    onClick={handleBulkGraduateForm4s}
                    className="px-3.5 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-xl font-black text-xs transition-all flex items-center gap-1.5 shadow-sm shadow-blue-600/10 hover:scale-105 active:scale-95"
                  >
                    🎓 Bulk Graduate Form 4s
                  </button>
                )}
              </div>
            </div>

            {/* Students Table */}
            <div className="overflow-x-auto">
              <table className="w-full text-left text-sm">
                <thead>
                  <tr className="bg-background-alt/30 border-b border-border text-xs uppercase tracking-wider text-text-muted font-bold">
                    <th className="px-6 py-3">Student</th>
                    <th className="px-6 py-3">Current Class</th>
                    <th className="px-6 py-3">Transition Action</th>
                    <th className="px-6 py-3">Flags / Overrides</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-border/50">
                  {filteredStudents.length === 0 ? (
                    <tr>
                      <td colSpan={4} className="px-6 py-12 text-center text-text-muted">
                        <Users size={32} className="mx-auto mb-2 opacity-20" />
                        <p className="text-xs font-bold uppercase tracking-widest">No students matched filters</p>
                      </td>
                    </tr>
                  ) : (
                    filteredStudents.map((student) => {
                      const action = studentExceptions[student.student_id] || 'promote';
                      const targetClassId = classMappings[student.class_id];
                      const targetClassName = targetClassId === 'graduate'
                        ? 'Graduate'
                        : classes.find(c => c.id === targetClassId)?.name || 'Unassigned';

                      return (
                        <tr key={student.student_id} className="hover:bg-background-alt/30 transition-colors">
                          <td className="px-6 py-3.5">
                            <div className="flex items-center gap-3">
                              <div className="w-8 h-8 rounded-lg bg-primary/10 overflow-hidden flex items-center justify-center font-bold text-xs text-primary">
                                <Avatar 
                                  src={`https://api.dicebear.com/9.x/initials/svg?seed=${student.student_id}`}
                                  firstName={student.first_name}
                                  lastName={student.last_name}
                                />
                              </div>
                              <div>
                                <p className="font-bold text-text text-sm">{student.first_name} {student.last_name}</p>
                                <p className="text-[0.65rem] text-text-muted">Roll: {student.roll_number}</p>
                              </div>
                            </div>
                          </td>
                          <td className="px-6 py-3.5">
                            <span className="font-semibold text-text text-xs bg-background-alt border border-border px-2.5 py-1 rounded-md">
                              {student.class_name} - {student.class_section}
                            </span>
                          </td>
                          <td className="px-6 py-3.5">
                            <div className="flex items-center gap-1.5">
                              {action === 'promote' && (
                                <span className="inline-flex items-center gap-1 text-[0.7rem] font-bold text-emerald-600 bg-emerald-500/10 px-2 py-0.5 rounded-full border border-emerald-500/25">
                                  {rolloverMode === 'term' ? 'Continuing in Class' : `Promoting ➡️ ${targetClassName}`}
                                </span>
                              )}
                              {action === 'repeat' && (
                                <span className="inline-flex items-center gap-1 text-[0.7rem] font-bold text-amber-600 bg-amber-500/10 px-2 py-0.5 rounded-full border border-amber-500/25">
                                  Repeating (Stay)
                                </span>
                              )}
                              {action === 'transfer' && (
                                <span className="inline-flex items-center gap-1 text-[0.7rem] font-bold text-rose-600 bg-rose-500/10 px-2 py-0.5 rounded-full border border-rose-500/25">
                                  Transferring Out
                                </span>
                              )}
                              {action === 'graduate' && (
                                <span className="inline-flex items-center gap-1 text-[0.7rem] font-bold text-blue-600 bg-blue-500/10 px-2 py-0.5 rounded-full border border-blue-500/25">
                                  Graduating
                                </span>
                              )}
                            </div>
                          </td>
                          <td className="px-6 py-3.5">
                            <div className="flex gap-1">
                              {availableActions.map(act => (
                                <button
                                  key={act}
                                  onClick={() => handleStudentActionChange(student.student_id, act as ExceptionAction)}
                                  className={`px-2.5 py-1.5 text-[0.65rem] font-black uppercase rounded-lg border transition-all ${
                                    action === act 
                                      ? act === 'promote' ? 'bg-emerald-500 border-emerald-500 text-white shadow-sm shadow-emerald-500/15'
                                        : act === 'repeat' ? 'bg-amber-500 border-amber-500 text-white shadow-sm shadow-amber-500/15'
                                        : act === 'transfer' ? 'bg-rose-500 border-rose-500 text-white shadow-sm shadow-rose-500/15'
                                        : 'bg-blue-500 border-blue-500 text-white shadow-sm shadow-blue-500/15'
                                      : 'bg-background border-border text-text-muted hover:text-text hover:bg-background-alt'
                                  }`}
                                >
                                  {act === 'promote' ? (rolloverMode === 'term' ? 'Continue' : 'Promote') : act === 'repeat' ? 'Repeat' : act === 'transfer' ? 'Transfer' : 'Graduate'}
                                </button>
                              ))}
                            </div>
                          </td>
                        </tr>
                      );
                    })
                  )}
                </tbody>
              </table>
            </div>

            <div className="p-6 border-t border-border flex justify-between">
              {rolloverMode === 'year' ? (
                <button
                  onClick={() => setActiveTab('classes')}
                  className="px-5 py-2.5 border border-border bg-card hover:bg-background-alt text-text rounded-xl font-bold text-sm transition-all"
                >
                  Back: Class Map
                </button>
              ) : (
                <div />
              )}
              <button
                onClick={() => setActiveTab('confirm')}
                className="px-6 py-2.5 bg-primary text-white hover:bg-primary-dark rounded-xl font-bold text-sm shadow-md active:scale-95 transition-all"
              >
                Next: Review & Run
              </button>
            </div>

          </div>
        )}

        {/* Tab 3 Content: Confirmation */}
        {activeTab === 'confirm' && (
          <div className="p-6 space-y-8">
            
            <div>
              <h3 className="font-black text-lg text-text uppercase tracking-tight">Review Transition Summary</h3>
              <p className="text-xs text-text-muted mt-0.5">Please review the statistics below before advancing the school year/term.</p>
            </div>

            {/* Stat Cards */}
            <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
              {rolloverMode === 'term' ? (
                <>
                  <div className="bg-emerald-500/5 border border-emerald-500/20 rounded-2xl p-4 col-span-2">
                    <span className="text-[0.65rem] font-bold text-emerald-600 uppercase">Continuing Students</span>
                    <p className="text-3xl font-black text-emerald-600 mt-1">{summaryStats.continuing}</p>
                    <p className="text-[0.65rem] text-text-muted mt-1">Advancing to target {nextTerm}</p>
                  </div>
                </>
              ) : (
                <>
                  <div className="bg-emerald-500/5 border border-emerald-500/20 rounded-2xl p-4">
                    <span className="text-[0.65rem] font-bold text-emerald-600 uppercase">Promoted Students</span>
                    <p className="text-3xl font-black text-emerald-600 mt-1">{summaryStats.promoted}</p>
                    <p className="text-[0.65rem] text-text-muted mt-1">Advancing to next grade/form</p>
                  </div>

                  <div className="bg-amber-500/5 border border-amber-500/20 rounded-2xl p-4">
                    <span className="text-[0.65rem] font-bold text-amber-600 uppercase">Repeat Cohort</span>
                    <p className="text-3xl font-black text-amber-600 mt-1">{summaryStats.repeated}</p>
                    <p className="text-[0.65rem] text-text-muted mt-1">Retained in current forms</p>
                  </div>
                </>
              )}

              <div className="bg-rose-500/5 border border-rose-500/20 rounded-2xl p-4">
                <span className="text-[0.65rem] font-bold text-rose-600 uppercase">Transferred Out</span>
                <p className="text-3xl font-black text-rose-600 mt-1">{summaryStats.transferred}</p>
                <p className="text-[0.65rem] text-text-muted mt-1">Departing school registry</p>
              </div>

              <div className="bg-blue-500/5 border border-blue-500/20 rounded-2xl p-4">
                <span className="text-[0.65rem] font-bold text-blue-600 uppercase">Graduates</span>
                <p className="text-3xl font-black text-blue-600 mt-1">{summaryStats.graduated}</p>
                <p className="text-[0.65rem] text-text-muted mt-1">Completing final studies</p>
              </div>
            </div>

            {/* Term Start / End Date inputs */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 bg-background border border-border p-5 rounded-3xl">
              <div>
                <span className="block text-[0.65rem] font-black uppercase tracking-widest text-text-muted mb-1">New Term Start Date ({nextTerm})</span>
                <input 
                  type="date"
                  value={termStartDate}
                  onChange={e => setTermStartDate(e.target.value)}
                  className="w-full bg-card border border-border rounded-xl px-3 py-2 text-xs font-bold text-text focus:outline-none"
                />
              </div>
              <div>
                <span className="block text-[0.65rem] font-black uppercase tracking-widest text-text-muted mb-1">New Term End Date ({nextTerm})</span>
                <input 
                  type="date"
                  value={termEndDate}
                  onChange={e => setTermEndDate(e.target.value)}
                  className="w-full bg-card border border-border rounded-xl px-3 py-2 text-xs font-bold text-text focus:outline-none"
                />
              </div>
            </div>

            {/* Double Confirmation Warning Panel */}
            <div className="bg-rose-500/5 border border-rose-500/20 rounded-3xl p-6 space-y-4">
              <div className="flex items-center gap-3">
                <AlertTriangle className="text-rose-500" size={24} />
                <h4 className="font-bold text-rose-800 text-sm uppercase">Critical Action Warning</h4>
              </div>
              <div className="text-xs text-rose-700/90 leading-relaxed space-y-2">
                {rolloverMode === 'term' ? (
                  <>
                    <p>• Executing this transition will set the active academic term to <b>{nextTerm}</b> (active year remains <b>{currentYear}</b>).</p>
                    <p>• Students flagged as <b>Transfer</b> or <b>Graduate</b> will have their current enrollment records terminated mid-year.</p>
                    <p>• All other students will continue with active enrollment status in their current classes.</p>
                  </>
                ) : (
                  <>
                    <p>• Executing this rollover will set the active academic year to <b>{nextYear}</b> (and resets active term to <b>{nextTerm}</b>).</p>
                    <p>• All active class enrollments for <b>{currentYear}</b> will be marked as inactive, completed, or graduated.</p>
                    <p>• Students marked for promotion or repeat will receive new active enrollments for the <b>{nextYear}</b> year.</p>
                  </>
                )}
                <p>• Old attendance data, exams, and grades will be safely preserved but locked under history logs.</p>
              </div>
            </div>

            <div className="flex justify-between items-center pt-4 border-t border-border">
              <button
                onClick={() => setActiveTab('students')}
                className="px-5 py-2.5 border border-border bg-card hover:bg-background-alt text-text rounded-xl font-bold text-sm transition-all"
              >
                Back: Student Flags
              </button>
              
              <button
                disabled={processing}
                onClick={handleRunRollover}
                className="flex items-center gap-2 px-8 py-3 bg-rose-600 hover:bg-rose-700 text-white rounded-xl font-black text-sm shadow-lg active:scale-95 disabled:opacity-50 transition-all"
              >
                {processing ? (
                  <>
                    <RefreshCw size={16} className="animate-spin" /> Processing...
                  </>
                ) : (
                  <>
                    <ShieldCheck size={16} /> Execute {rolloverMode === 'term' ? 'Term Transition' : 'Year Rollover'}
                  </>
                )}
              </button>
            </div>

          </div>
        )}

      </div>

    </div>
  );
}
