import { Link } from "@inertiajs/react";
import { useState, type ReactNode } from "react";
import Shell from "../components/Shell";
import StudentAvatar from "../components/StudentAvatar";
import StudentEditor from "../components/StudentEditor";
import {
    Badge,
    Button,
    ButtonLink,
    Dialog,
    Empty,
    Errors,
    Field,
    Icon,
    Panel,
    SaveForm,
    Table,
} from "../components/ui";
import {
    person,
    type Credit,
    type Enrollment,
    type Grade,
    type Student,
} from "../types";

type ProfileEnrollment = Enrollment & {
    is_current: boolean;
    period_state: "current" | "upcoming" | "past";
    can_review: boolean;
};
type ProfileCredit = Credit & { transcript_url: string | null };
interface StudentFile {
    id: number;
    title: string;
    category: string;
    original_name: string;
    size_bytes: number;
    uploaded_by: string;
    created_at: string;
    download_url: string;
}
interface Props {
    student: Student;
    enrollments: ProfileEnrollment[];
    grades: Grade[];
    credits: ProfileCredit[];
    documents: StudentFile[];
    can_manage: boolean;
    can_restrict: boolean;
    memberships: {
        id: number;
        section_name: string;
        branch_name: string;
        confirmed_at: string;
        ended_at: string | null;
        end_reason: string | null;
    }[];
}
const tabs = [
    "Overview",
    "Current records",
    "Grades",
    "Enrollment history",
    "Files",
] as const;
type Tab = (typeof tabs)[number];
const categories: Record<string, string> = {
    admission: "Admission",
    identity: "Identity",
    report_card: "Report card",
    transcript: "Transcript",
    other: "Other",
};
const date = (value?: string | null) =>
    value
        ? new Intl.DateTimeFormat("en-PH", {
              day: "numeric",
              month: "short",
              year: "numeric",
              timeZone: "UTC",
          }).format(new Date(value))
        : "Not recorded";
function Detail({ label, children }: { label: string; children?: ReactNode }) {
    return (
        <div>
            <dt>{label}</dt>
            <dd>
                {children === null ||
                children === undefined ||
                children === "" ? (
                    <span className="muted">Not recorded</span>
                ) : (
                    children
                )}
            </dd>
        </div>
    );
}

function GradeChanges({ grade }: { grade: Grade }) {
    return grade.corrections?.length ? (
        <details className="grade-changes">
            <summary>Grade changes ({grade.corrections.length})</summary>
            {grade.corrections.map((c) => (
                <p key={c.id}>
                    {c.old_grade} → {c.new_grade} · {date(c.created_at)}
                    <span className="cell-detail">{c.reason}</span>
                </p>
            ))}
        </details>
    ) : null;
}
function OfficialGrades({ grades }: { grades: Grade[] }) {
    if (!grades.length)
        return (
            <Empty title="No official grades yet">
                Grades will appear here when the subject teacher finalizes them.
            </Empty>
        );
    return (
        <>
            <div className="student-grade-table">
                <Table
                    columns={[
                        "Subject / teacher",
                        "Academic period",
                        "Official grade",
                        "Result",
                        "Finalized",
                    ]}
                >
                    {grades.map((g) => (
                        <tr key={g.id}>
                            <td>
                                <strong>
                                    {g.course?.subject.code} ·{" "}
                                    {g.course?.subject.name}
                                </strong>
                                <span className="cell-detail">
                                    {g.course?.teacher?.name} ·{" "}
                                    {g.course?.section}
                                </span>
                                <GradeChanges grade={g} />
                            </td>
                            <td>
                                {g.course?.period.name}
                                <span className="cell-detail">
                                    {g.course?.branch.name}
                                </span>
                            </td>
                            <td>
                                <strong className="official-grade">
                                    {g.official_grade}
                                </strong>
                                <span className="cell-detail">
                                    {g.course?.policy_snapshot.scale ===
                                    "numeric"
                                        ? "Numeric scale"
                                        : "Percentage scale"}
                                </span>
                            </td>
                            <td>
                                <Badge tone={g.passed ? "success" : "danger"}>
                                    {g.passed ? "Passed" : "Failed"}
                                </Badge>
                            </td>
                            <td>{date(g.finalized_at)}</td>
                        </tr>
                    ))}
                </Table>
            </div>
            <div className="student-grade-cards">
                {grades.map((g) => (
                    <article className="student-grade-card" key={g.id}>
                        <h3>
                            {g.course?.subject.code} · {g.course?.subject.name}
                        </h3>
                        <div className="profile-grade-result">
                            <div>
                                <span className="small muted">
                                    Official grade
                                </span>
                                <strong className="mobile-official-grade">
                                    {g.official_grade}
                                </strong>
                                <span className="small muted">
                                    {g.course?.policy_snapshot.scale ===
                                    "numeric"
                                        ? "Numeric scale"
                                        : "Percentage scale"}
                                </span>
                            </div>
                            <Badge tone={g.passed ? "success" : "danger"}>
                                {g.passed ? "Passed" : "Failed"}
                            </Badge>
                        </div>
                        <dl className="student-details">
                            <Detail label="Academic period">
                                {g.course?.period.name}
                            </Detail>
                            <Detail label="Branch">
                                {g.course?.branch.name}
                            </Detail>
                            <Detail label="Subject teacher">
                                {g.course?.teacher?.name}
                            </Detail>
                            <Detail label="Section">{g.course?.section}</Detail>
                            <Detail label="Finalized">
                                {date(g.finalized_at)}
                            </Detail>
                        </dl>
                        <GradeChanges grade={g} />
                    </article>
                ))}
            </div>
        </>
    );
}

function EnrollmentActions({ enrollment }: { enrollment: ProfileEnrollment }) {
    return (
        enrollment.can_review && (
            <div className="actions">
                {enrollment.status === "enrolled" && enrollment.cor_number && (
                    <a
                        className="button secondary"
                        href={`/enrollments/${enrollment.id}/cor`}
                    >
                        View COR
                    </a>
                )}
                <ButtonLink href={`/enrollments/${enrollment.id}`} secondary>
                    View enrollment
                </ButtonLink>
            </div>
        )
    );
}

function Subjects({ enrollment }: { enrollment: Enrollment }) {
    if (!enrollment.courses.length)
        return <p className="muted">No subjects selected yet.</p>;
    return (
        <>
            <div className="student-subject-table">
                <Table
                    columns={[
                        "Subject",
                        "Units",
                        "Section / schedule",
                        "Teacher",
                    ]}
                >
                    {enrollment.courses.map((course) => (
                        <tr key={course.id}>
                            <td>
                                <strong>{course.subject.code}</strong>
                                <span className="cell-detail">
                                    {course.subject.name}
                                </span>
                            </td>
                            <td>{course.subject.units}</td>
                            <td>
                                {course.section}
                                <span className="cell-detail">
                                    {course.schedule || "Schedule not recorded"}
                                </span>
                            </td>
                            <td>{course.teacher?.name || "Not assigned"}</td>
                        </tr>
                    ))}
                </Table>
            </div>
            <div className="student-subject-cards">
                {enrollment.courses.map((course) => (
                    <article className="student-subject-card" key={course.id}>
                        <h3>
                            {course.subject.code} · {course.subject.name}
                        </h3>
                        <dl className="student-details">
                            <Detail label="Units">
                                {course.subject.units}
                            </Detail>
                            <Detail label="Section">{course.section}</Detail>
                            <Detail label="Schedule">{course.schedule}</Detail>
                            <Detail label="Subject teacher">
                                {course.teacher?.name}
                            </Detail>
                        </dl>
                    </article>
                ))}
            </div>
        </>
    );
}

export default function StudentProfile({
    student,
    enrollments,
    grades,
    credits,
    documents,
    can_manage,
    can_restrict,
    memberships,
}: Props) {
    const [tab, setTab] = useState<Tab>("Overview");
    const [edit, setEdit] = useState(false);
    const [photo, setPhoto] = useState(false);
    const [upload, setUpload] = useState(false);
    const [period, setPeriod] = useState("");
    const current = enrollments.filter((e) => e.is_current);
    const openRecords = enrollments.filter(
        (e) =>
            e.status !== "cancelled" &&
            (e.is_current ||
                e.status === "draft" ||
                e.period_state === "upcoming"),
    );
    const periods = [
        ...new Map(
            grades
                .filter((g) => g.course)
                .map((g) => [g.course!.period.id, g.course!.period]),
        ).values(),
    ];
    const visibleGrades = grades.filter(
        (g) => !period || String(g.course?.academic_period_id) === period,
    );
    const cors = enrollments.filter(
        (e) => e.status === "enrolled" && e.cor_number && e.can_review,
    );
    const transcripts = credits.filter((c) => c.transcript_url);
    return (
        <Shell title={`${person(student)} · Student record`}>
            <Link href="/students" className="back-link">
                <Icon name="chevron-left" /> All students
            </Link>
            <section
                className="panel student-hero"
                aria-label="Student identity"
            >
                <div className="student-photo-block">
                    <StudentAvatar student={student} large />
                    {can_manage && (
                        <Button variant="ghost" onClick={() => setPhoto(true)}>
                            {student.photo_url ? "Change photo" : "Add photo"}
                        </Button>
                    )}
                </div>
                <div className="student-identity">
                    <span className="overline">Student record</span>
                    <h1>{person(student)}</h1>
                    <p className="student-number">
                        Student no. <strong>{student.student_number}</strong>
                    </p>
                    <div className="actions">
                        <Badge tone={current.length ? "success" : "neutral"}>
                            {current.length
                                ? "Currently enrolled"
                                : "No current enrollment"}
                        </Badge>
                        <span className="muted">
                            {student.homeBranch?.name} · Home branch
                        </span>
                    </div>
                </div>
                {can_manage && (
                    <Button variant="secondary" onClick={() => setEdit(true)}>
                        Edit details
                    </Button>
                )}
            </section>
            {(can_restrict || student.is_blacklisted) && (
                <Panel title="Enrollment restriction">
                    <p>
                        {student.is_blacklisted
                            ? `Blacklisted: ${student.blacklist_reason}`
                            : "No enrollment blacklist is recorded."}
                    </p>
                    {can_restrict && (
                        <details className="accordion">
                            <summary>
                                {student.is_blacklisted
                                    ? "Clear blacklist"
                                    : "Block enrollment"}
                            </summary>
                            <div>
                                <SaveForm
                                    url={`/students/${student.id}/restriction`}
                                    label={
                                        student.is_blacklisted
                                            ? "Clear blacklist"
                                            : "Record blacklist"
                                    }
                                >
                                    <input
                                        type="hidden"
                                        name="is_blacklisted"
                                        value={
                                            student.is_blacklisted ? "0" : "1"
                                        }
                                    />
                                    <Field label="Restriction reason">
                                        <textarea
                                            name="reason"
                                            required
                                            minLength={5}
                                            maxLength={2000}
                                        />
                                    </Field>
                                </SaveForm>
                            </div>
                        </details>
                    )}
                </Panel>
            )}
            <div
                className="tabs student-tabs"
                role="tablist"
                aria-label="Student record sections"
            >
                {tabs.map((label, index) => (
                    <button
                        key={label}
                        id={`student-tab-${index}`}
                        role="tab"
                        aria-selected={tab === label}
                        aria-controls={`student-panel-${index}`}
                        tabIndex={tab === label ? 0 : -1}
                        onClick={() => setTab(label)}
                        onKeyDown={(event) => {
                            const next =
                                event.key === "ArrowRight"
                                    ? (index + 1) % tabs.length
                                    : event.key === "ArrowLeft"
                                      ? (index + tabs.length - 1) % tabs.length
                                      : event.key === "Home"
                                        ? 0
                                        : event.key === "End"
                                          ? tabs.length - 1
                                          : null;
                            if (next !== null) {
                                event.preventDefault();
                                setTab(tabs[next]);
                                document
                                    .getElementById(`student-tab-${next}`)
                                    ?.focus();
                            }
                        }}
                    >
                        {label}
                    </button>
                ))}
            </div>
            <div
                role="tabpanel"
                id={`student-panel-${tabs.indexOf(tab)}`}
                aria-labelledby={`student-tab-${tabs.indexOf(tab)}`}
                tabIndex={0}
                className="profile-content"
            >
                {tab === "Overview" && (
                    <div className="two-columns">
                        <div className="form-stack">
                            <Panel title="Personal details">
                                <dl className="student-details">
                                    <Detail label="Student number">
                                        {student.student_number}
                                    </Detail>
                                    <Detail label="Full name">
                                        {person(student)}
                                    </Detail>
                                    <Detail label="Birth date">
                                        {student.birth_date
                                            ? date(student.birth_date)
                                            : null}
                                    </Detail>
                                    <Detail label="Home branch">
                                        {student.homeBranch?.name}
                                    </Detail>
                                    <Detail label="Email">
                                        {student.email}
                                    </Detail>
                                    <Detail label="Phone">
                                        {student.phone}
                                    </Detail>
                                    <Detail label="Address">
                                        {student.address}
                                    </Detail>
                                    <Detail label="Record created">
                                        {date(student.created_at)}
                                    </Detail>
                                </dl>
                            </Panel>
                            <Panel title="Parent or guardian">
                                <dl className="student-details">
                                    <Detail label="Name">
                                        {student.guardian_name}
                                    </Detail>
                                    <Detail label="Phone">
                                        {student.guardian_phone}
                                    </Detail>
                                </dl>
                            </Panel>
                        </div>
                        <div className="form-stack">
                            <Panel title="Academic overview">
                                <p>
                                    Current Section:{" "}
                                    <strong>
                                        {memberships.find((m) => !m.ended_at)
                                            ?.section_name ||
                                            "No current Section"}
                                    </strong>
                                </p>
                                {current.length ? (
                                    current.map((e) => (
                                        <div
                                            className="profile-summary"
                                            key={e.id}
                                        >
                                            <Badge tone="success">
                                                Current enrollment
                                            </Badge>
                                            <h3>{e.curriculum.program.name}</h3>
                                            <p>
                                                {e.period.name} · Year{" "}
                                                {e.year_level}
                                            </p>
                                            <p className="muted">
                                                {e.branch.name} ·{" "}
                                                {e.courses.length}{" "}
                                                {e.courses.length === 1
                                                    ? "subject"
                                                    : "subjects"}
                                            </p>
                                            <EnrollmentActions enrollment={e} />
                                        </div>
                                    ))
                                ) : (
                                    <p className="muted">
                                        There is no finalized enrollment in an
                                        active academic period.
                                    </p>
                                )}
                                <div className="profile-quick-links">
                                    <Button
                                        variant="secondary"
                                        onClick={() =>
                                            setTab("Current records")
                                        }
                                    >
                                        View current records
                                    </Button>
                                    <Button
                                        variant="ghost"
                                        onClick={() => setTab("Grades")}
                                    >
                                        View official grades
                                    </Button>
                                </div>
                            </Panel>
                            <Panel title="Assigned curricula">
                                {student.assignments?.length ? (
                                    student.assignments.map((a) => (
                                        <div
                                            className="profile-summary"
                                            key={a.curriculum_id}
                                        >
                                            <strong>
                                                {a.curriculum.program.name}
                                            </strong>
                                            <p className="muted">
                                                {a.curriculum.version}
                                            </p>
                                        </div>
                                    ))
                                ) : (
                                    <p className="muted">
                                        No curriculum assigned yet.
                                    </p>
                                )}
                            </Panel>
                            <Panel title="Section history">
                                {memberships.length ? (
                                    memberships.map((m) => (
                                        <div
                                            className="profile-summary"
                                            key={m.id}
                                        >
                                            <strong>{m.section_name}</strong>
                                            <p>
                                                {m.branch_name} · Joined{" "}
                                                {date(m.confirmed_at)}
                                            </p>
                                            <p>
                                                {m.ended_at
                                                    ? `Ended ${date(m.ended_at)}: ${m.end_reason}`
                                                    : "Current membership"}
                                            </p>
                                        </div>
                                    ))
                                ) : (
                                    <p className="muted">
                                        No Section membership recorded.
                                    </p>
                                )}
                                <p className="small muted">
                                    Ending Section membership keeps enrollment
                                    records, subjects and grades.
                                </p>
                            </Panel>
                            <Panel title="Student portal">
                                <p>
                                    {student.portal_status === "active"
                                        ? "Student account is active."
                                        : student.portal_status === "inactive"
                                          ? "Student account is inactive."
                                          : "No student account is linked yet."}
                                </p>
                                <p className="small muted">
                                    Account access is managed in Users and
                                    access.
                                </p>
                            </Panel>
                        </div>
                    </div>
                )}
                {tab === "Current records" && (
                    <>
                        <div className="page-heading">
                            <div>
                                <h2>Current records</h2>
                                <p>
                                    Active enrollments, upcoming periods and
                                    enrollment drafts.
                                </p>
                            </div>
                        </div>
                        {openRecords.length ? (
                            openRecords.map((e) => (
                                <Panel key={e.id} title={e.period.name}>
                                    <div className="profile-record-heading">
                                        <div>
                                            <h3>{e.curriculum.program.name}</h3>
                                            <p className="muted">
                                                {e.branch.name} · Year{" "}
                                                {e.year_level} ·{" "}
                                                {e.curriculum.version}
                                            </p>
                                        </div>
                                        <Badge
                                            tone={
                                                e.status === "draft"
                                                    ? "warning"
                                                    : "success"
                                            }
                                        >
                                            {e.status === "draft"
                                                ? "Enrollment draft"
                                                : e.period_state === "upcoming"
                                                  ? "Upcoming enrollment"
                                                  : "Enrolled"}
                                        </Badge>
                                    </div>
                                    <Subjects enrollment={e} />
                                    <EnrollmentActions enrollment={e} />
                                </Panel>
                            ))
                        ) : (
                            <Panel>
                                <Empty title="No current records">
                                    Current subjects will appear after
                                    enrollment is finalized for an active or
                                    upcoming period.
                                </Empty>
                            </Panel>
                        )}
                    </>
                )}
                {tab === "Grades" && (
                    <>
                        <Panel title="Official grades">
                            <div className="toolbar">
                                <Field label="Academic period">
                                    <select
                                        value={period}
                                        onChange={(e) =>
                                            setPeriod(e.target.value)
                                        }
                                    >
                                        <option value="">All periods</option>
                                        {periods.map((p) => (
                                            <option key={p.id} value={p.id}>
                                                {p.name}
                                            </option>
                                        ))}
                                    </select>
                                </Field>
                            </div>
                            <p className="small muted">
                                Final grades published by the subject teacher.
                                Each subject retains its own grading scale.
                            </p>
                            <OfficialGrades grades={visibleGrades} />
                        </Panel>
                        <Panel title="Transfer credits">
                            <p className="small muted">
                                Source grades stay separate from local grades
                                and do not contribute to local grade
                                calculations.
                            </p>
                            {credits.length ? (
                                <Table
                                    columns={[
                                        "Local subject",
                                        "Source school / subject",
                                        "Source grade",
                                        "Status",
                                    ]}
                                >
                                    {credits.map((c) => (
                                        <tr key={c.id}>
                                            <td>
                                                <strong>
                                                    {c.subject.code} ·{" "}
                                                    {c.subject.name}
                                                </strong>
                                                <span className="cell-detail">
                                                    {c.curriculum.program.name}{" "}
                                                    · {c.curriculum.version}
                                                </span>
                                            </td>
                                            <td>
                                                {c.source_school}
                                                <span className="cell-detail">
                                                    {c.source_subject}
                                                </span>
                                            </td>
                                            <td>{c.source_grade}</td>
                                            <td>
                                                <Badge
                                                    tone={
                                                        c.status === "approved"
                                                            ? "success"
                                                            : "warning"
                                                    }
                                                >
                                                    {c.status === "approved"
                                                        ? "Credited"
                                                        : "Pending review"}
                                                </Badge>
                                                {c.status === "approved" && (
                                                    <>
                                                        <small>
                                                            {c.credited_units ??
                                                                c.subject
                                                                    .units}{" "}
                                                            credits ·{" "}
                                                            {c.completes_subject !==
                                                            false
                                                                ? "Subject completed"
                                                                : "Partial credits · Subject still required"}
                                                        </small>
                                                        {c.reason && (
                                                            <small>
                                                                {c.reason}
                                                            </small>
                                                        )}
                                                    </>
                                                )}
                                            </td>
                                        </tr>
                                    ))}
                                </Table>
                            ) : (
                                <p className="muted">
                                    No transfer credits recorded.
                                </p>
                            )}
                        </Panel>
                    </>
                )}
                {tab === "Enrollment history" && (
                    <>
                        <div className="page-heading">
                            <div>
                                <h2>Enrollment history</h2>
                                <p>
                                    Academic records across permitted branches,
                                    from most recent to oldest.
                                </p>
                            </div>
                        </div>
                        {enrollments.length ? (
                            enrollments.map((e) => (
                                <Panel key={e.id} title={e.period.name}>
                                    <div className="profile-record-heading">
                                        <div>
                                            <h3>{e.curriculum.program.name}</h3>
                                            <p className="muted">
                                                {e.period.school_year} ·{" "}
                                                {e.branch.name} · Year{" "}
                                                {e.year_level}
                                            </p>
                                        </div>
                                        <Badge
                                            tone={
                                                e.status === "enrolled"
                                                    ? "success"
                                                    : "warning"
                                            }
                                        >
                                            {e.status === "enrolled"
                                                ? "Enrolled"
                                                : e.status === "cancelled"
                                                  ? "Removed from batch"
                                                  : "Draft"}
                                        </Badge>
                                    </div>
                                    <dl className="student-details">
                                        <Detail label="Curriculum">
                                            {e.curriculum.version}
                                        </Detail>
                                        <Detail label="Enrollment finalized">
                                            {e.finalized_at
                                                ? date(e.finalized_at)
                                                : "Not finalized"}
                                        </Detail>
                                        <Detail label="COR number">
                                            {e.cor_number}
                                        </Detail>
                                        <Detail label="Subjects">
                                            {e.courses.length}
                                        </Detail>
                                    </dl>
                                    <details className="profile-subjects">
                                        <summary>
                                            View subjects ({e.courses.length})
                                        </summary>
                                        <Subjects enrollment={e} />
                                    </details>
                                    <EnrollmentActions enrollment={e} />
                                </Panel>
                            ))
                        ) : (
                            <Panel>
                                <Empty title="No enrollment history">
                                    Enrollment records will appear here as the
                                    student progresses through the school.
                                </Empty>
                            </Panel>
                        )}
                    </>
                )}
                {tab === "Files" && (
                    <>
                        <Panel
                            title="Student documents"
                            action={
                                can_manage && (
                                    <Button
                                        icon="upload"
                                        onClick={() => setUpload(true)}
                                    >
                                        Upload document
                                    </Button>
                                )
                            }
                        >
                            <p className="small muted">
                                Private records available to authorized staff in
                                the permitted branch.
                            </p>
                            {documents.length ? (
                                documents.map((file) => (
                                    <div
                                        className="record-item student-file"
                                        key={file.id}
                                    >
                                        <div>
                                            <strong>{file.title}</strong>
                                            <p className="small muted">
                                                {categories[file.category] ??
                                                    file.category}{" "}
                                                · {file.original_name} ·{" "}
                                                {file.size_bytes >= 1048576
                                                    ? `${(file.size_bytes / 1048576).toFixed(1)} MB`
                                                    : `${Math.max(1, Math.ceil(file.size_bytes / 1024))} KB`}
                                            </p>
                                            <p className="small muted">
                                                Added {date(file.created_at)} by{" "}
                                                {file.uploaded_by}
                                            </p>
                                        </div>
                                        <a
                                            className="button secondary"
                                            href={file.download_url}
                                        >
                                            <Icon name="download" />
                                            Download
                                        </a>
                                    </div>
                                ))
                            ) : (
                                <Empty title="No student documents yet">
                                    Admission records, report cards and other
                                    student files can be kept here.
                                </Empty>
                            )}
                        </Panel>
                        <Panel title="Certificates of registration">
                            {cors.length ? (
                                cors.map((e) => (
                                    <div className="record-item" key={e.id}>
                                        <div>
                                            <strong>{e.cor_number}</strong>
                                            <p className="muted">
                                                {e.period.name} ·{" "}
                                                {e.branch.name}
                                            </p>
                                        </div>
                                        <a
                                            className="button secondary"
                                            href={`/enrollments/${e.id}/cor`}
                                        >
                                            View COR
                                        </a>
                                    </div>
                                ))
                            ) : (
                                <p className="muted">
                                    No issued CORs available.
                                </p>
                            )}
                        </Panel>
                        <Panel title="Transfer transcript evidence">
                            {transcripts.length ? (
                                transcripts.map((c) => (
                                    <div className="record-item" key={c.id}>
                                        <div>
                                            <strong>{c.source_school}</strong>
                                            <p className="muted">
                                                {c.source_subject} →{" "}
                                                {c.subject.code}
                                            </p>
                                        </div>
                                        <a
                                            className="button secondary"
                                            href={c.transcript_url!}
                                        >
                                            <Icon name="download" />
                                            Download transcript
                                        </a>
                                    </div>
                                ))
                            ) : (
                                <p className="muted">
                                    No transfer transcripts recorded.
                                </p>
                            )}
                        </Panel>
                    </>
                )}
            </div>
            {edit && (
                <StudentEditor
                    student={student}
                    onClose={() => setEdit(false)}
                />
            )}
            {photo && (
                <Dialog title="Student photo" onClose={() => setPhoto(false)}>
                    <Errors />
                    <SaveForm
                        url={`/students/${student.id}/photo`}
                        label="Save photo"
                        onSuccess={() => setPhoto(false)}
                    >
                        <Field
                            label="Photo"
                            hint="JPEG, PNG or WebP. Up to 4 MB and 4096 × 4096 pixels."
                        >
                            <input
                                name="photo"
                                type="file"
                                required
                                accept="image/jpeg,image/png,image/webp"
                            />
                        </Field>
                    </SaveForm>
                </Dialog>
            )}
            {upload && (
                <Dialog
                    title="Upload student document"
                    onClose={() => setUpload(false)}
                >
                    <Errors />
                    <SaveForm
                        url={`/students/${student.id}/documents`}
                        label="Upload document"
                        onSuccess={() => setUpload(false)}
                    >
                        <Field label="Document title">
                            <input name="title" required maxLength={160} />
                        </Field>
                        <Field label="Category">
                            <select name="category" required>
                                {Object.entries(categories).map(
                                    ([value, label]) => (
                                        <option key={value} value={value}>
                                            {label}
                                        </option>
                                    ),
                                )}
                            </select>
                        </Field>
                        <Field
                            label="File"
                            hint="PDF, Word, text, JPEG, PNG or WebP. Up to 10 MB."
                        >
                            <input
                                name="file"
                                type="file"
                                required
                                accept=".pdf,.doc,.docx,.txt,.jpg,.jpeg,.png,.webp"
                            />
                        </Field>
                    </SaveForm>
                </Dialog>
            )}
        </Shell>
    );
}
