import {
  mdiAccountGroupOutline,
  mdiCalendarCheckOutline,
  mdiClipboardCheckOutline,
  mdiSchoolOutline,
} from '@mdi/js';
import axios from 'axios';
import Head from 'next/head';
import Link from 'next/link';
import React, { ReactElement, useCallback, useEffect, useMemo, useState } from 'react';
import BaseButton from '../components/BaseButton';
import CardBox from '../components/CardBox';
import LayoutAuthenticated from '../layouts/Authenticated';
import SectionMain from '../components/SectionMain';
import SectionTitleLineWithButton from '../components/SectionTitleLineWithButton';
import { getPageTitle } from '../config';
import { useAppSelector } from '../stores/hooks';

type AttendanceStatus = 'present' | 'absent' | 'late' | 'excused';

type SectionOption = {
  id: string;
  name: string;
  section_code?: string | null;
  status?: string | null;
  subjectName?: string | null;
  termName?: string | null;
  className?: string | null;
  teacherName?: string | null;
};

type RosterEntry = {
  studentId: string;
  displayName: string;
  studentNumber?: string | null;
  source?: string | null;
  lastStatus?: AttendanceStatus | null;
};

type RecentSession = {
  id: string;
  session_start: string;
  session_end?: string | null;
  status: string;
  notes?: string | null;
  summary: Record<AttendanceStatus, number>;
  totalRecords: number;
};

type WorkflowResponse = {
  sections: SectionOption[];
  selectedSectionId: string | null;
  roster: RosterEntry[];
  rosterSource: string | null;
  recentSessions: RecentSession[];
  summary: {
    totalSections: number;
    totalStudents: number;
    recentSessionsCount: number;
  };
};

type RosterFormRow = {
  status: AttendanceStatus;
  minutesLate: string;
  comment: string;
};

const STATUS_OPTIONS: { value: AttendanceStatus; label: string; tone: string }[] = [
  { value: 'present', label: 'Present', tone: 'border-emerald-200 bg-emerald-50 text-emerald-700' },
  { value: 'late', label: 'Late', tone: 'border-amber-200 bg-amber-50 text-amber-700' },
  { value: 'absent', label: 'Absent', tone: 'border-rose-200 bg-rose-50 text-rose-700' },
  { value: 'excused', label: 'Excused', tone: 'border-sky-200 bg-sky-50 text-sky-700' },
];

const EMPTY_WORKFLOW: WorkflowResponse = {
  sections: [],
  selectedSectionId: null,
  roster: [],
  rosterSource: null,
  recentSessions: [],
  summary: {
    totalSections: 0,
    totalStudents: 0,
    recentSessionsCount: 0,
  },
};

const todayIso = () => new Date().toISOString().slice(0, 10);

const combineDateAndTime = (date: string, time: string) => new Date(`${date}T${time}:00`);

const formatSectionLabel = (section: SectionOption) => {
  const meta = [section.subjectName, section.className].filter(Boolean).join(' • ');
  return meta ? `${section.name} — ${meta}` : section.name;
};

const formatSessionDate = (date: string) =>
  new Intl.DateTimeFormat('en-US', {
    month: 'short',
    day: 'numeric',
    hour: 'numeric',
    minute: '2-digit',
  }).format(new Date(date));

const buildDefaultRows = (roster: RosterEntry[]) =>
  roster.reduce<Record<string, RosterFormRow>>((acc, student) => {
    acc[student.studentId] = {
      status: student.lastStatus ?? 'present',
      minutesLate: student.lastStatus === 'late' ? '5' : '',
      comment: '',
    };

    return acc;
  }, {});

const StatCard = ({ icon, label, value, accent }: { icon: string; label: string; value: string; accent: string }) => (
  <div className="rounded-3xl border border-white/70 bg-white/85 p-4 shadow-sm backdrop-blur">
    <div className="mb-3 inline-flex rounded-2xl p-2" style={{ backgroundColor: accent }}>
      <span className="text-white">
        <svg viewBox="0 0 24 24" width="18" height="18" className="inline-block">
          <path fill="currentColor" d={icon} />
        </svg>
      </span>
    </div>
    <p className="text-sm text-slate-500">{label}</p>
    <p className="text-2xl font-semibold text-slate-900">{value}</p>
  </div>
);

const AttendanceHubPage = () => {
  const { currentUser } = useAppSelector((state) => state.auth);
  const [workflow, setWorkflow] = useState<WorkflowResponse>(EMPTY_WORKFLOW);
  const [selectedSectionId, setSelectedSectionId] = useState('');
  const [attendanceDate, setAttendanceDate] = useState(todayIso());
  const [startTime, setStartTime] = useState('08:30');
  const [endTime, setEndTime] = useState('09:15');
  const [notes, setNotes] = useState('');
  const [sessionStatus, setSessionStatus] = useState<'open' | 'closed'>('closed');
  const [rows, setRows] = useState<Record<string, RosterFormRow>>({});
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');
  const [successMessage, setSuccessMessage] = useState('');
  const [savedSessionId, setSavedSessionId] = useState('');

  const loadWorkflow = useCallback(async (courseSectionId?: string) => {
    setIsLoading(true);
    setErrorMessage('');

    try {
      const { data } = await axios.get<WorkflowResponse>('/attendance_sessions/workflow/overview', {
        params: courseSectionId ? { courseSectionId } : undefined,
      });

      setWorkflow(data);
      setRows(buildDefaultRows(data.roster));

      if (data.selectedSectionId && data.selectedSectionId !== courseSectionId) {
        setSelectedSectionId(data.selectedSectionId);
      }
    } catch (error) {
      console.error('Attendance workflow load failed', error);
      setErrorMessage('We could not load the attendance workflow. Please refresh and try again.');
    } finally {
      setIsLoading(false);
    }
  }, []);

  useEffect(() => {
    void loadWorkflow();
  }, [loadWorkflow]);

  useEffect(() => {
    if (!selectedSectionId || selectedSectionId === workflow.selectedSectionId) {
      return;
    }

    void loadWorkflow(selectedSectionId);
  }, [loadWorkflow, selectedSectionId, workflow.selectedSectionId]);

  const selectedSection = useMemo(
    () => workflow.sections.find((section) => section.id === (selectedSectionId || workflow.selectedSectionId)) ?? null,
    [selectedSectionId, workflow.sections, workflow.selectedSectionId],
  );

  const totalMarkedPresent = useMemo(
    () => Object.values(rows).filter((row) => row.status === 'present').length,
    [rows],
  );

  const totalFlagged = useMemo(
    () => Object.values(rows).filter((row) => row.status !== 'present').length,
    [rows],
  );

  const setBulkStatus = (status: AttendanceStatus) => {
    setRows((currentRows) =>
      Object.entries(currentRows).reduce<Record<string, RosterFormRow>>((acc, [studentId, row]) => {
        acc[studentId] = {
          ...row,
          status,
          minutesLate: status === 'late' ? row.minutesLate || '5' : '',
        };

        return acc;
      }, {}),
    );
  };

  const updateRow = (studentId: string, nextValue: Partial<RosterFormRow>) => {
    setRows((currentRows) => ({
      ...currentRows,
      [studentId]: {
        ...currentRows[studentId],
        ...nextValue,
      },
    }));
  };

  const saveSession = async () => {
    setErrorMessage('');
    setSuccessMessage('');
    setSavedSessionId('');

    if (!selectedSectionId && !workflow.selectedSectionId) {
      setErrorMessage('Choose a course section before saving attendance.');
      return;
    }

    if (workflow.roster.length === 0) {
      setErrorMessage('This section has no students yet. Link a roster first or choose a section with attendance history.');
      return;
    }

    if (combineDateAndTime(attendanceDate, endTime) <= combineDateAndTime(attendanceDate, startTime)) {
      setErrorMessage('Session end time must be later than the start time.');
      return;
    }

    const recordInputs = workflow.roster.map((student) => {
      const row = rows[student.studentId];
      const minutesLate = row?.status === 'late' && row.minutesLate ? Number(row.minutesLate) : 0;

      return {
        studentId: student.studentId,
        attendance_status: row?.status ?? 'present',
        minutes_late: Number.isNaN(minutesLate) ? 0 : minutesLate,
        comment: row?.comment?.trim() || '',
      };
    });

    setIsSaving(true);

    try {
      const activeSectionId = selectedSectionId || workflow.selectedSectionId;
      const { data } = await axios.post('/attendance_sessions/workflow/submit', {
        courseSectionId: activeSectionId,
        sessionDate: attendanceDate,
        startTime,
        endTime,
        notes,
        status: sessionStatus,
        records: recordInputs,
      });

      setSavedSessionId(data.sessionId);
      setSuccessMessage(`Attendance saved for ${data.summary.total} students. ${data.summary.present} present, ${data.summary.flagged} need follow-up.`);
      setNotes('');
      await loadWorkflow(activeSectionId || undefined);
    } catch (error: unknown) {
      console.error('Attendance workflow save failed', error);
      const message = axios.isAxiosError(error) ? error.response?.data : null;
      setErrorMessage(typeof message === 'string' ? message : 'Unable to save attendance right now.');
    } finally {
      setIsSaving(false);
    }
  };

  return (
    <>
      <Head>
        <title>{getPageTitle('Attendance Hub')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiClipboardCheckOutline} title="Attendance hub" main>
          <div className="flex flex-wrap gap-3">
            <BaseButton href="/attendance_sessions/attendance_sessions-list" color="whiteDark" label="All sessions" />
            <BaseButton href="/attendance_records/attendance_records-list" color="info" label="Attendance records" />
          </div>
        </SectionTitleLineWithButton>

        <CardBox className="mb-6 overflow-hidden border-0 bg-gradient-to-br from-slate-950 via-sky-900 to-cyan-700 text-white shadow-2xl">
          <div className="grid gap-8 lg:grid-cols-[1.5fr,1fr]">
            <div>
              <div className="mb-4 inline-flex items-center rounded-full border border-white/20 bg-white/10 px-4 py-2 text-sm font-medium text-cyan-50">
                Daily teacher workflow
              </div>
              <h2 className="max-w-2xl text-3xl font-semibold leading-tight md:text-4xl">
                Take attendance in one focused flow instead of bouncing between generic CRUD screens.
              </h2>
              <p className="mt-4 max-w-2xl text-sm leading-7 text-sky-100 md:text-base">
                Pick a section, mark the roster, save the session, and immediately review the latest attendance trend. This first slice is tuned for busy school mornings.
              </p>
              <div className="mt-6 flex flex-wrap items-center gap-3 text-sm text-sky-100">
                <span className="rounded-full border border-white/15 bg-white/10 px-3 py-1">{currentUser?.firstName || 'Staff'} signed in</span>
                <span className="rounded-full border border-white/15 bg-white/10 px-3 py-1">{currentUser?.app_role?.name || 'School staff'}</span>
                {selectedSection?.teacherName ? (
                  <span className="rounded-full border border-white/15 bg-white/10 px-3 py-1">Lead teacher: {selectedSection.teacherName}</span>
                ) : null}
              </div>
            </div>
            <div className="grid gap-4 sm:grid-cols-3 lg:grid-cols-1">
              <StatCard icon={mdiSchoolOutline} label="Sections ready" value={String(workflow.summary.totalSections)} accent="#0f766e" />
              <StatCard icon={mdiAccountGroupOutline} label="Students in roster" value={String(workflow.summary.totalStudents)} accent="#0284c7" />
              <StatCard icon={mdiCalendarCheckOutline} label="Recent sessions" value={String(workflow.summary.recentSessionsCount)} accent="#7c3aed" />
            </div>
          </div>
        </CardBox>

        {errorMessage ? (
          <div className="mb-6 rounded-2xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700">
            {errorMessage}
          </div>
        ) : null}

        {successMessage ? (
          <div className="mb-6 rounded-2xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-700">
            <div className="flex flex-wrap items-center justify-between gap-3">
              <span>{successMessage}</span>
              {savedSessionId ? (
                <Link className="inline-flex items-center gap-2 font-semibold text-emerald-700 hover:text-emerald-800" href={`/attendance_sessions/${savedSessionId}`}>
                  Open saved session
                  <span aria-hidden="true">→</span>
                </Link>
              ) : null}
            </div>
          </div>
        ) : null}

        <div className="grid gap-6 xl:grid-cols-[1.2fr,1.8fr]">
          <CardBox className="border-slate-200 bg-white shadow-sm">
            <div className="mb-6 flex items-start justify-between gap-4">
              <div>
                <p className="text-sm font-semibold uppercase tracking-[0.2em] text-sky-600">Step 1</p>
                <h3 className="mt-2 text-2xl font-semibold text-slate-900">Build today&apos;s attendance session</h3>
                <p className="mt-2 text-sm leading-6 text-slate-500">
                  Choose a course section and capture the attendance snapshot that becomes the source of truth for follow-up.
                </p>
              </div>
              <div className="rounded-2xl bg-sky-50 px-4 py-3 text-right text-sm text-sky-700">
                <div className="font-semibold">{totalMarkedPresent} present</div>
                <div>{totalFlagged} flagged</div>
              </div>
            </div>

            <div className="space-y-5">
              <div>
                <label className="mb-2 block text-sm font-semibold text-slate-700" htmlFor="courseSectionId">
                  Course section
                </label>
                <select
                  id="courseSectionId"
                  className="h-12 w-full rounded-2xl border border-slate-200 bg-white px-4 text-sm text-slate-900 shadow-sm outline-none transition focus:border-sky-400 focus:ring-4 focus:ring-sky-100"
                  value={selectedSectionId || workflow.selectedSectionId || ''}
                  onChange={(event) => setSelectedSectionId(event.target.value)}
                >
                  <option value="">Select a section</option>
                  {workflow.sections.map((section) => (
                    <option key={section.id} value={section.id}>
                      {formatSectionLabel(section)}
                    </option>
                  ))}
                </select>
                {selectedSection ? (
                  <p className="mt-2 text-sm text-slate-500">
                    {selectedSection.section_code || 'Section code pending'}
                    {selectedSection.termName ? ` • ${selectedSection.termName}` : ''}
                    {selectedSection.status ? ` • ${selectedSection.status}` : ''}
                  </p>
                ) : null}
              </div>

              <div className="grid gap-4 md:grid-cols-2">
                <div>
                  <label className="mb-2 block text-sm font-semibold text-slate-700" htmlFor="attendanceDate">
                    Session date
                  </label>
                  <input
                    id="attendanceDate"
                    type="date"
                    className="h-12 w-full rounded-2xl border border-slate-200 px-4 text-sm text-slate-900 shadow-sm outline-none transition focus:border-sky-400 focus:ring-4 focus:ring-sky-100"
                    value={attendanceDate}
                    onChange={(event) => setAttendanceDate(event.target.value)}
                  />
                </div>
                <div>
                  <label className="mb-2 block text-sm font-semibold text-slate-700" htmlFor="sessionStatus">
                    Session state
                  </label>
                  <select
                    id="sessionStatus"
                    className="h-12 w-full rounded-2xl border border-slate-200 px-4 text-sm text-slate-900 shadow-sm outline-none transition focus:border-sky-400 focus:ring-4 focus:ring-sky-100"
                    value={sessionStatus}
                    onChange={(event) => setSessionStatus(event.target.value as 'open' | 'closed')}
                  >
                    <option value="closed">Closed after save</option>
                    <option value="open">Keep open</option>
                  </select>
                </div>
              </div>

              <div className="grid gap-4 md:grid-cols-2">
                <div>
                  <label className="mb-2 block text-sm font-semibold text-slate-700" htmlFor="startTime">
                    Start time
                  </label>
                  <input
                    id="startTime"
                    type="time"
                    className="h-12 w-full rounded-2xl border border-slate-200 px-4 text-sm text-slate-900 shadow-sm outline-none transition focus:border-sky-400 focus:ring-4 focus:ring-sky-100"
                    value={startTime}
                    onChange={(event) => setStartTime(event.target.value)}
                  />
                </div>
                <div>
                  <label className="mb-2 block text-sm font-semibold text-slate-700" htmlFor="endTime">
                    End time
                  </label>
                  <input
                    id="endTime"
                    type="time"
                    className="h-12 w-full rounded-2xl border border-slate-200 px-4 text-sm text-slate-900 shadow-sm outline-none transition focus:border-sky-400 focus:ring-4 focus:ring-sky-100"
                    value={endTime}
                    onChange={(event) => setEndTime(event.target.value)}
                  />
                </div>
              </div>

              <div>
                <label className="mb-2 block text-sm font-semibold text-slate-700" htmlFor="notes">
                  Notes for this session
                </label>
                <textarea
                  id="notes"
                  rows={4}
                  className="w-full rounded-2xl border border-slate-200 px-4 py-3 text-sm text-slate-900 shadow-sm outline-none transition focus:border-sky-400 focus:ring-4 focus:ring-sky-100"
                  placeholder="Examples: quiz day, substitute teacher, assembly started late..."
                  value={notes}
                  onChange={(event) => setNotes(event.target.value)}
                />
              </div>

              <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
                <div className="flex flex-wrap items-center justify-between gap-3">
                  <div>
                    <p className="text-sm font-semibold text-slate-900">Quick mark</p>
                    <p className="text-sm text-slate-500">Set the whole roster before adjusting individual students.</p>
                  </div>
                  <div className="flex flex-wrap gap-2">
                    <BaseButton color="success" label="All present" onClick={() => setBulkStatus('present')} />
                    <BaseButton color="warning" label="All late" onClick={() => setBulkStatus('late')} />
                  </div>
                </div>
              </div>

              <div className="flex flex-wrap gap-3">
                <BaseButton color="info" label={isSaving ? 'Saving...' : 'Save attendance session'} onClick={saveSession} disabled={isSaving || isLoading} />
                <BaseButton color="whiteDark" label="Reset roster" onClick={() => setRows(buildDefaultRows(workflow.roster))} disabled={isLoading} />
              </div>
            </div>
          </CardBox>

          <div className="space-y-6">
            <CardBox className="border-slate-200 bg-white shadow-sm">
              <div className="mb-6 flex items-start justify-between gap-4">
                <div>
                  <p className="text-sm font-semibold uppercase tracking-[0.2em] text-sky-600">Step 2</p>
                  <h3 className="mt-2 text-2xl font-semibold text-slate-900">Mark the roster</h3>
                  <p className="mt-2 text-sm leading-6 text-slate-500">
                    Default everything to present, then only update students who need a note or follow-up.
                  </p>
                </div>
                {workflow.rosterSource ? (
                  <span className="rounded-full border border-slate-200 bg-slate-50 px-3 py-1 text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">
                    Roster from {workflow.rosterSource}
                  </span>
                ) : null}
              </div>

              {isLoading ? (
                <div className="rounded-2xl border border-dashed border-slate-200 bg-slate-50 px-6 py-12 text-center text-sm text-slate-500">
                  Loading roster…
                </div>
              ) : workflow.roster.length === 0 ? (
                <div className="rounded-2xl border border-dashed border-slate-200 bg-slate-50 px-6 py-12 text-center">
                  <p className="text-lg font-semibold text-slate-900">No students are linked to this section yet.</p>
                  <p className="mt-2 text-sm leading-6 text-slate-500">
                    The hub looks for class enrollments first, then falls back to existing attendance history, submissions, and grades to build a usable roster.
                  </p>
                </div>
              ) : (
                <div className="space-y-4">
                  {workflow.roster.map((student) => {
                    const row = rows[student.studentId] ?? { status: 'present', minutesLate: '', comment: '' };

                    return (
                      <div key={student.studentId} className="rounded-3xl border border-slate-200 p-4 shadow-sm transition hover:border-sky-200 hover:bg-slate-50/80">
                        <div className="flex flex-col gap-4 xl:flex-row xl:items-start xl:justify-between">
                          <div>
                            <p className="text-lg font-semibold text-slate-900">{student.displayName}</p>
                            <p className="mt-1 text-sm text-slate-500">
                              {student.studentNumber || 'Student profile'}
                              {student.source ? ` • sourced from ${student.source}` : ''}
                            </p>
                          </div>
                          <div className="flex flex-wrap gap-2">
                            {STATUS_OPTIONS.map((option) => {
                              const isActive = row.status === option.value;

                              return (
                                <button
                                  key={option.value}
                                  type="button"
                                  onClick={() =>
                                    updateRow(student.studentId, {
                                      status: option.value,
                                      minutesLate: option.value === 'late' ? row.minutesLate || '5' : '',
                                    })
                                  }
                                  className={`rounded-full border px-4 py-2 text-sm font-semibold transition ${
                                    isActive
                                      ? option.tone
                                      : 'border-slate-200 bg-white text-slate-500 hover:border-slate-300 hover:text-slate-900'
                                  }`}
                                >
                                  {option.label}
                                </button>
                              );
                            })}
                          </div>
                        </div>

                        <div className="mt-4 grid gap-4 md:grid-cols-2">
                          <div>
                            <label className="mb-2 block text-sm font-semibold text-slate-700" htmlFor={`comment-${student.studentId}`}>
                              Follow-up note
                            </label>
                            <input
                              id={`comment-${student.studentId}`}
                              type="text"
                              value={row.comment}
                              onChange={(event) => updateRow(student.studentId, { comment: event.target.value })}
                              placeholder="Optional note for parent call, counselor, or teacher"
                              className="h-11 w-full rounded-2xl border border-slate-200 px-4 text-sm text-slate-900 shadow-sm outline-none transition focus:border-sky-400 focus:ring-4 focus:ring-sky-100"
                            />
                          </div>
                          <div>
                            <label className="mb-2 block text-sm font-semibold text-slate-700" htmlFor={`minutes-${student.studentId}`}>
                              Minutes late
                            </label>
                            <input
                              id={`minutes-${student.studentId}`}
                              type="number"
                              min={0}
                              value={row.minutesLate}
                              onChange={(event) => updateRow(student.studentId, { minutesLate: event.target.value })}
                              placeholder="0"
                              disabled={row.status !== 'late'}
                              className="h-11 w-full rounded-2xl border border-slate-200 px-4 text-sm text-slate-900 shadow-sm outline-none transition focus:border-sky-400 focus:ring-4 focus:ring-sky-100 disabled:cursor-not-allowed disabled:bg-slate-100 disabled:text-slate-400"
                            />
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}
            </CardBox>

            <CardBox className="border-slate-200 bg-white shadow-sm">
              <div className="mb-6 flex items-start justify-between gap-4">
                <div>
                  <p className="text-sm font-semibold uppercase tracking-[0.2em] text-sky-600">Step 3</p>
                  <h3 className="mt-2 text-2xl font-semibold text-slate-900">Review recent sessions</h3>
                  <p className="mt-2 text-sm leading-6 text-slate-500">
                    After each save, the newest attendance snapshot appears here so staff can quickly verify what changed.
                  </p>
                </div>
                <Link href="/attendance_sessions/attendance_sessions-list" className="text-sm font-semibold text-sky-700 hover:text-sky-900">
                  Open all sessions
                </Link>
              </div>

              {workflow.recentSessions.length === 0 ? (
                <div className="rounded-2xl border border-dashed border-slate-200 bg-slate-50 px-6 py-12 text-center text-sm text-slate-500">
                  No attendance sessions have been saved for this section yet.
                </div>
              ) : (
                <div className="space-y-4">
                  {workflow.recentSessions.map((session) => (
                    <div key={session.id} className="rounded-3xl border border-slate-200 p-4 shadow-sm">
                      <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
                        <div>
                          <div className="flex flex-wrap items-center gap-2">
                            <span className="rounded-full bg-slate-100 px-3 py-1 text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">
                              {session.status}
                            </span>
                            <span className="inline-flex items-center gap-2 text-sm text-slate-500">
                              <span aria-hidden="true">🕒</span>
                              {formatSessionDate(session.session_start)}
                            </span>
                          </div>
                          <p className="mt-3 text-base font-semibold text-slate-900">{session.notes || 'Attendance session saved without notes'}</p>
                          <p className="mt-2 text-sm text-slate-500">{session.totalRecords} students recorded</p>
                        </div>
                        <div className="flex flex-wrap items-center gap-2">
                          {STATUS_OPTIONS.map((option) => (
                            <span key={option.value} className={`rounded-full border px-3 py-1 text-xs font-semibold uppercase tracking-[0.18em] ${option.tone}`}>
                              {option.label}: {session.summary[option.value] || 0}
                            </span>
                          ))}
                          <Link href={`/attendance_sessions/${session.id}`} className="inline-flex items-center gap-2 rounded-full border border-slate-200 px-4 py-2 text-sm font-semibold text-slate-700 transition hover:border-slate-300 hover:text-slate-900">
                            View details
                            <span aria-hidden="true">→</span>
                          </Link>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </CardBox>
          </div>
        </div>

        <CardBox className="mt-6 border-slate-200 bg-white shadow-sm">
          <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
            <div>
              <p className="text-sm font-semibold uppercase tracking-[0.2em] text-sky-600">What this first slice covers</p>
              <h3 className="mt-2 text-2xl font-semibold text-slate-900">Create → confirm → review</h3>
              <p className="mt-2 text-sm leading-6 text-slate-500">
                This hub intentionally focuses on the highest-frequency teacher action. Once you confirm the flow, the next layer can add student and parent-facing attendance visibility.
              </p>
            </div>
            <div className="flex flex-wrap gap-3">
              <BaseButton href="/assignments/assignments-list" color="whiteDark" label="Assignments" />
              <BaseButton href="/announcements/announcements-list" color="whiteDark" label="Announcements" />
            </div>
          </div>
        </CardBox>
      </SectionMain>
    </>
  );
};

AttendanceHubPage.getLayout = function getLayout(page: ReactElement) {
  return <LayoutAuthenticated permission={'READ_ATTENDANCE_SESSIONS'}>{page}</LayoutAuthenticated>;
};

export default AttendanceHubPage;
