/**
 * parent/AttendanceHistory.tsx
 *
 * Read-only attendance history for the parent's linked children. Uses
 * /api/users/children to fetch the parent's students (the same endpoint
 * that the existing `parent/Attendance.tsx` page uses), then feeds the
 * list into the shared AttendanceHistoryView.
 *
 * If the parent has no linked children, the page shows an empty state.
 *
 * The four tabs (class / hostel / transport / club) are all available —
 * the backend's parent scoping rule (parent can only see students in
 * `parent_students`) is enforced server-side, so a 403 from a tab means
 * the child simply doesn't have records in that context.
 */

import { useEffect, useState } from 'react';
import { Users } from 'lucide-react';
import api from '../../store/api';
import AttendanceHistoryView, { StudentOption } from '../../components/AttendanceHistoryView';
import { useAuthStore } from '../../store/auth';

export default function ParentAttendanceHistory() {
  const { user } = useAuthStore();
  const [children, setChildren] = useState<StudentOption[]>([]);
  const [loading, setLoading] = useState(true);
  const [loadError, setLoadError] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;
    const load = async () => {
      setLoadError(null);
      try {
        // Reuse the existing children endpoint — see parent/Attendance.tsx
        const res = await api.get('/users/children');
        if (cancelled) return;
        const list = (res.data || []).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() || `Student ${s.id}`,
          class_name: s.class_name || s.grade,
        }));
        setChildren(list);
      } catch (err: any) {
        if (!cancelled) setLoadError(err?.message || 'Failed to load linked students');
      } 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 your linked students…</p>
      </div>
    );
  }

  if (loadError) {
    return (
      <div className="p-6">
        <div className="bg-rose-500/10 text-rose-600 border border-rose-500/20 rounded-lg p-4 text-sm font-semibold">
          {loadError}
        </div>
      </div>
    );
  }

  if (children.length === 0) {
    return (
      <div className="p-6">
        <div className="py-24 text-center bg-card border-2 border-dashed border-border rounded-[3rem]">
          <Users size={64} className="mx-auto text-text-muted/20 mb-6" />
          <h3 className="text-2xl font-black text-text mb-2 uppercase tracking-tighter">No Associated Learners</h3>
          <p className="text-text-muted font-medium max-w-xs mx-auto">
            You have no students linked to your guardian registry at this time.
            {user?.role === 'parent' && ' Contact the school to link your child(ren).'}
          </p>
        </div>
      </div>
    );
  }

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