/**
 * teacher/AttendanceHistory.tsx
 *
 * Wrapper for AttendanceHistoryView scoped to staff (admin, principal,
 * teacher). Loads the full student list (role=student) and feeds it
 * into the shared view.
 */

import { useEffect, useState } from 'react';
import api from '../../store/api';
import AttendanceHistoryView, { StudentOption } from '../../components/AttendanceHistoryView';

export default function TeacherAttendanceHistory() {
  const [students, setStudents] = useState<StudentOption[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let cancelled = false;
    const load = async () => {
      try {
        const res = await api.get('/users', { params: { limit: 1000 } });
        if (cancelled) return;
        const data = Array.isArray(res.data) ? res.data : (res.data?.users || []);
        // Filter out parents
        const filtered = data.filter((u: any) => u.role !== 'parent');
        const list = filtered.map((s: any) => ({
          id: s.id,
          first_name: s.first_name,
          last_name: s.last_name,
          full_name: `${s.first_name || ''} ${s.last_name || ''}`.trim() || s.username || `User ${s.id}`,
          class_name: s.class_name,
          role: s.role
        }));
        setStudents(list);
      } catch (err) {
        console.error('Failed to load students', err);
      } finally {
        if (!cancelled) setLoading(false);
      }
    };
    load();
    return () => { cancelled = true; };
  }, []);

  if (loading) {
    return (
      <div className="p-6 text-center text-text-muted py-24">
        <div className="w-8 h-8 border-4 border-primary border-t-transparent rounded-full animate-spin mx-auto"></div>
        <p className="mt-2">Loading students…</p>
      </div>
    );
  }

  return (
    <AttendanceHistoryView
      studentOptions={students}
      tabs={['class', 'hostel', 'transport', 'club', 'staff']}
    />
  );
}
