import { usePage } from "@inertiajs/react";
import { useEffect, useState } from "react";
import Shell from "../components/Shell";
import {
    Alert,
    Badge,
    Button,
    ButtonLink,
    Field,
    Heading,
    Panel,
    SaveForm,
    Table,
} from "../components/ui";
import {
    money,
    person,
    type Course,
    type Enrollment,
    type Grade,
    type Options,
    type Section,
    type Shared,
} from "../types";
import type {
    Application,
    Eligibility,
    Evaluation,
    PlanRow,
    PreCor,
    Quote,
} from "../enrollment-workflow";

function TransferEditor({
    application,
    can_credit,
    options,
}: {
    application: Application;
    can_credit: boolean;
    options: Options;
}) {
    const blank = (): Evaluation => ({
        source_school: "",
        source_subject: "",
        source_grade: "",
        source_credits: "3",
        subject_id: null,
        decision: "pending",
        credited_units: "0",
        completes_subject: false,
        reason: "",
    });
    const [rows, setRows] = useState<Evaluation[]>(
        application.evaluations.length ? application.evaluations : [blank()],
    );
    useEffect(() => {
        setRows(
            application.evaluations.length
                ? application.evaluations
                : [blank()],
        );
    }, [application.evaluations]);
    const change = (index: number, patch: Partial<Evaluation>) =>
        setRows(rows.map((r, i) => (i === index ? { ...r, ...patch } : r)));
    const subjects =
        options.curricula.find(
            (c) => c.id === application.enrollment?.curriculum_id,
        )?.subjects ?? [];
    return (
        <Panel title="Transfer evaluation">
            <p>
                Record past subjects, then map each accepted subject to this
                Course’s plan.{" "}
                {can_credit
                    ? "The Registrar records the credit decision and reason."
                    : "Proposed credits require Registrar approval."}
            </p>
            <SaveForm
                url={`/enrollment-applications/${application.id}/transfer`}
                label={
                    can_credit
                        ? "Save transfer decisions"
                        : "Save proposed transfer evaluation"
                }
                reset={false}
            >
                <input type="hidden" name="rows" value={JSON.stringify(rows)} />
                {rows.map((r, i) => (
                    <fieldset key={r.id ?? `new-${i}`}>
                        <legend>
                            Past subject {i + 1}
                            {r.approved_at ? " · Decision recorded" : ""}
                        </legend>
                        <fieldset
                            disabled={!!r.approved_at}
                            className="plain-fieldset"
                        >
                            <div className="form-grid">
                                <Field label="Previous school">
                                    <input
                                        value={r.source_school ?? ""}
                                        onChange={(e) =>
                                            change(i, {
                                                source_school: e.target.value,
                                            })
                                        }
                                        maxLength={160}
                                    />
                                </Field>
                                <Field label="Past subject">
                                    <input
                                        required
                                        value={r.source_subject}
                                        onChange={(e) =>
                                            change(i, {
                                                source_subject: e.target.value,
                                            })
                                        }
                                        maxLength={160}
                                    />
                                </Field>
                                <Field label="Previous grade">
                                    <input
                                        value={r.source_grade ?? ""}
                                        onChange={(e) =>
                                            change(i, {
                                                source_grade: e.target.value,
                                            })
                                        }
                                        maxLength={80}
                                    />
                                </Field>
                                <Field label="Previous credits">
                                    <input
                                        type="number"
                                        required
                                        min="0"
                                        max="100"
                                        step="0.01"
                                        value={r.source_credits}
                                        onChange={(e) =>
                                            change(i, {
                                                source_credits: e.target.value,
                                            })
                                        }
                                    />
                                </Field>
                                <Field label="Credit decision">
                                    <select
                                        value={r.decision}
                                        onChange={(e) =>
                                            change(i, {
                                                decision: e.target.value,
                                            })
                                        }
                                    >
                                        <option value="pending">
                                            Pending review
                                        </option>
                                        <option value="credit">
                                            Credit subject
                                        </option>
                                        <option value="not_credit">
                                            Do not credit
                                        </option>
                                    </select>
                                </Field>
                                <Field label="Equivalent Course subject">
                                    <select
                                        value={r.subject_id ?? ""}
                                        required={r.decision === "credit"}
                                        onChange={(e) =>
                                            change(i, {
                                                subject_id:
                                                    Number(e.target.value) ||
                                                    null,
                                            })
                                        }
                                    >
                                        <option value="">
                                            Choose equivalent subject
                                        </option>
                                        {subjects.map((s) => (
                                            <option
                                                key={s.subject_id}
                                                value={s.subject_id}
                                            >
                                                {s.subject.code} ·{" "}
                                                {s.subject.name} ·{" "}
                                                {s.subject.units} credits
                                            </option>
                                        ))}
                                    </select>
                                </Field>
                                <Field label="Approved / proposed credits">
                                    <input
                                        type="number"
                                        required
                                        min="0"
                                        max="30"
                                        step="0.01"
                                        value={r.credited_units}
                                        onChange={(e) =>
                                            change(i, {
                                                credited_units: e.target.value,
                                            })
                                        }
                                    />
                                </Field>
                            </div>
                            <label className="checkbox">
                                <input
                                    type="checkbox"
                                    disabled={
                                        !can_credit || r.decision !== "credit"
                                    }
                                    checked={r.completes_subject}
                                    onChange={(e) =>
                                        change(i, {
                                            completes_subject: e.target.checked,
                                        })
                                    }
                                />
                                Mark subject completed even with partial credits
                                (Registrar only; reason required)
                            </label>
                            <Field label="Decision reason">
                                <textarea
                                    value={r.reason ?? ""}
                                    required={
                                        can_credit && r.decision !== "pending"
                                    }
                                    onChange={(e) =>
                                        change(i, { reason: e.target.value })
                                    }
                                    maxLength={2000}
                                />
                            </Field>
                        </fieldset>
                        {!r.id && rows.length > 1 && (
                            <Button
                                type="button"
                                variant="ghost"
                                onClick={() =>
                                    setRows(rows.filter((_, n) => n !== i))
                                }
                            >
                                Remove unsaved row
                            </Button>
                        )}
                    </fieldset>
                ))}
                <Button
                    type="button"
                    variant="secondary"
                    onClick={() => setRows([...rows, blank()])}
                >
                    Add past subject
                </Button>
            </SaveForm>
        </Panel>
    );
}

export function QuoteTable({ quote }: { quote: Quote }) {
    return (
        <>
            <div className="phase-table">
                <Table
                    columns={["Subject / class", "Credit allocation", "Amount"]}
                >
                    {quote.subjects.map((s) => (
                        <tr key={s.class_id}>
                            <td>
                                <strong>
                                    {s.code} · {s.name}
                                </strong>
                                <small>
                                    {s.class_code} · {s.teacher}
                                </small>
                                <small>
                                    {s.schedule} · {s.credits} academic credits
                                </small>
                            </td>
                            <td>
                                {s.unit_lines.map((u, i) => (
                                    <small key={i}>
                                        {u.unit_type}: {u.credits} credits ·{" "}
                                        {money(u.rate_cents)}{" "}
                                        {u.pricing_mode === "fixed"
                                            ? "fixed per subject"
                                            : "per credit"}
                                    </small>
                                ))}
                            </td>
                            <td>{money(s.amount_cents)}</td>
                        </tr>
                    ))}
                </Table>
            </div>
            <div className="phase-cards">
                {quote.subjects.map((s) => (
                    <article key={s.class_id} className="subject-choice">
                        <strong>
                            {s.code} · {s.name}
                        </strong>
                        <small>
                            {s.class_code} · {s.teacher}
                        </small>
                        <p>
                            {s.schedule} · {s.credits} academic credits
                        </p>
                        {s.unit_lines.map((u, i) => (
                            <p key={i}>
                                {u.unit_type}: {u.credits} credits
                                <br />
                                {money(u.rate_cents)}{" "}
                                {u.pricing_mode === "fixed"
                                    ? "fixed per subject"
                                    : "per credit"}{" "}
                                · {money(u.amount_cents)}
                            </p>
                        ))}
                        <strong>Subject amount: {money(s.amount_cents)}</strong>
                    </article>
                ))}
            </div>
            <p className="strong">
                Subject assessment: {money(quote.total_cents)}
            </p>
        </>
    );
}

export default function EnrollmentWizard({
    application: a,
    options,
    suggestion,
    balance_cents,
    history,
    grades,
    eligibility,
    plan,
    offerings,
    sections,
    quote,
    pre_cor,
    can_credit,
    can_finance,
    can_finalize,
    can_edit,
    admission_issue,
}: {
    application: Application;
    options: Options;
    suggestion: {
        program_id: number | null;
        year: number | null;
        last: {
            course: string;
            year: number;
            semester: number;
            period: string;
        } | null;
        warning: string | null;
    };
    balance_cents: number;
    history: Enrollment[];
    grades: Grade[];
    eligibility: Eligibility | null;
    plan: PlanRow[];
    offerings: Course[];
    sections: Section[];
    quote: Quote | null;
    pre_cor: PreCor | null;
    can_credit: boolean;
    can_finance: boolean;
    can_finalize: boolean;
    can_edit: boolean;
    admission_issue?: string | null;
}) {
    const { levels } = usePage<Shared>().props;
    const [step, setStep] = useState(a.wizard_step),
        [program, setProgram] = useState(
            String(a.requested_program_id ?? suggestion.program_id ?? ""),
        ),
        [college, setCollege] = useState(""),
        [transfer, setTransfer] = useState(
            a.transfer_requested || a.is_transferee,
        ),
        [selected, setSelected] = useState(
            a.enrollment?.courses.map((c) => c.id) ?? [],
        ),
        [section, setSection] = useState(
            String(a.enrollment?.section_id ?? ""),
        );
    useEffect(() => {
        setStep(a.wizard_step);
        setSelected(a.enrollment?.courses.map((c) => c.id) ?? []);
        setSection(String(a.enrollment?.section_id ?? ""));
    }, [
        a.wizard_step,
        a.enrollment?.id,
        a.enrollment?.curriculum_id,
        a.evaluations,
    ]);
    const chosen = options.programs.find((p) => p.id === Number(program));
    const programs = options.programs.filter(
        (p) =>
            p.level === a.batch.level &&
            p.default_curriculum_id &&
            p.curriculum_template_id &&
            (!college || p.college_id === Number(college)),
    );
    const e = a.enrollment;
    const assigned = options.curricula.find(
        (c) =>
            c.id ===
            (e?.curriculum.program_id === Number(program)
                ? e.curriculum_id
                : (options.curricula.find(
                      (c) =>
                          c.program_id === Number(program) &&
                          a.student.assignments?.some(
                              (s) => s.curriculum_id === c.id,
                          ),
                  )?.id ?? chosen?.default_curriculum_id)),
    );
    const classes = [
        ...new Map(
            [...offerings, ...(e?.courses ?? [])].map((c) => [c.id, c]),
        ).values(),
    ];
    const subjects = [
        ...new Map(classes.map((c) => [c.subject_id, c.subject])).values(),
    ];
    const title = ["Assessment", "Course & subjects", "Accounting", "Review"];
    const pendingTransfers =
        a.transfer_requested &&
        (!a.evaluations.length || a.evaluations.some((r) => !r.approved_at));
    return (
        <Shell title="Student enrollment">
            <Heading
                title={person(a.student)}
                description={`${a.student.student_number} · ${a.batch.branch.name} · ${a.batch.period.name}`}
                action={
                    <ButtonLink
                        href={`/enrollment-batches/${a.batch.id}`}
                        secondary
                    >
                        Back to batch
                    </ButtonLink>
                }
            />
            {admission_issue && !a.student.is_blacklisted && (
                <Alert
                    title="Not eligible for this enrollment batch"
                    tone="warning"
                >
                    {admission_issue}
                </Alert>
            )}
            {a.student.is_blacklisted && (
                <Alert
                    title="Enrollment blocked · Student is blacklisted"
                    tone="danger"
                >
                    {a.student.blacklist_reason} The Registrar or School
                    Administrator must resolve this restriction before
                    enrollment can proceed.
                </Alert>
            )}
            {a.batch.status !== "open" && (
                <Alert title="Enrollment batch is closed" tone="warning">
                    Reopen the batch before making changes.
                </Alert>
            )}
            {a.state === "enrolled" && e && (
                <Alert title="Enrollment confirmed" tone="success">
                    <ButtonLink href={`/enrollments/${e.id}/cor`}>
                        View official COR
                    </ButtonLink>
                </Alert>
            )}
            <div
                className="tabs setup-tabs"
                role="tablist"
                aria-label="Enrollment steps"
            >
                {title.map((t, i) => (
                    <button
                        key={t}
                        role="tab"
                        aria-selected={step === i + 1}
                        disabled={i + 1 > a.wizard_step}
                        onClick={() => setStep(i + 1)}
                    >
                        {i + 1}. {t}
                    </button>
                ))}
            </div>
            {step === 1 && (
                <>
                    <Panel title="Assessment">
                        <p>
                            Check the Student’s records before preparing the
                            subject load.
                        </p>
                        <div className="record-grid">
                            <div>
                                <small>Student status</small>
                                <strong>
                                    {a.is_transferee
                                        ? "Transferee"
                                        : history.length
                                          ? "Returning Student"
                                          : "New Student"}
                                </strong>
                            </div>
                            <div>
                                <small>Recorded outstanding balance</small>
                                <strong>{money(balance_cents)}</strong>
                            </div>
                        </div>
                        {balance_cents > 0 && (
                            <Alert
                                title="Outstanding balance · warning"
                                tone="warning"
                            >
                                The wizard can continue. Finance clearance is
                                required before an official COR; past-debt
                                arrangements need Finance Approver approval.
                            </Alert>
                        )}
                        {history.length > 0 && (
                            <>
                                <h4>Previous enrollment</h4>
                                <Table
                                    columns={[
                                        "Period",
                                        "Course",
                                        "Year / Grade",
                                    ]}
                                >
                                    {history.map((h) => (
                                        <tr key={h.id}>
                                            <td>{h.period.name}</td>
                                            <td>{h.curriculum.program.name}</td>
                                            <td>{h.year_level}</td>
                                        </tr>
                                    ))}
                                </Table>
                            </>
                        )}
                        {grades.length > 0 && (
                            <details className="accordion">
                                <summary>
                                    Final grades and previous subjects
                                </summary>
                                <Table columns={["Subject", "Grade", "Result"]}>
                                    {grades.map((g) => (
                                        <tr key={g.id}>
                                            <td>{g.course?.subject.name}</td>
                                            <td>{g.official_grade}</td>
                                            <td>
                                                {g.passed
                                                    ? "Passed"
                                                    : "Failed · review prerequisites"}
                                            </td>
                                        </tr>
                                    ))}
                                </Table>
                            </details>
                        )}
                        {can_edit && (
                            <SaveForm
                                url={`/enrollment-applications/${a.id}/assess`}
                                label="Complete Assessment · Continue"
                            />
                        )}
                    </Panel>
                </>
            )}
            {step === 2 && (
                <>
                    <Panel title="Course and entry stage">
                        {suggestion.last && (
                            <p>
                                Last enrollment:{" "}
                                <strong>
                                    {suggestion.last.course} · Year{" "}
                                    {suggestion.last.year} · Semester{" "}
                                    {suggestion.last.semester}
                                </strong>
                                . The next stage is suggested from the Course
                                setup; review it before loading subjects.
                            </p>
                        )}
                        {suggestion.warning && (
                            <Alert title="Review progression" tone="warning">
                                {suggestion.warning}
                            </Alert>
                        )}
                        <SaveForm
                            url={`/enrollment-applications/${a.id}/course/prepare`}
                            label="Load Course subjects"
                            reset={false}
                            disabled={!can_edit}
                        >
                            {a.batch.level === "college" && (
                                <Field label="College">
                                    <select
                                        value={
                                            college ||
                                            String(chosen?.college_id ?? "")
                                        }
                                        onChange={(event) => {
                                            setCollege(event.target.value);
                                            setProgram("");
                                        }}
                                    >
                                        <option value="">All Colleges</option>
                                        {options.colleges.map((c) => (
                                            <option key={c.id} value={c.id}>
                                                {c.name}
                                            </option>
                                        ))}
                                    </select>
                                </Field>
                            )}
                            <Field label="Course">
                                <select
                                    name="program_id"
                                    required
                                    value={program}
                                    onChange={(event) => {
                                        setProgram(event.target.value);
                                        setCollege("");
                                    }}
                                >
                                    <option value="">Choose Course</option>
                                    {programs.map((p) => (
                                        <option key={p.id} value={p.id}>
                                            {p.name}
                                        </option>
                                    ))}
                                </select>
                            </Field>
                            {chosen && (
                                <>
                                    <p>
                                        College:{" "}
                                        <strong>
                                            {chosen.college?.name ??
                                                levels[chosen.level]}
                                        </strong>
                                    </p>
                                    <Field label="Year / Grade">
                                        <select
                                            name="year_level"
                                            required
                                            key={program}
                                            defaultValue={
                                                a.proposed_year ??
                                                suggestion.year ??
                                                chosen.start_year
                                            }
                                        >
                                            {Array.from(
                                                {
                                                    length: chosen.duration_years,
                                                },
                                                (_, i) => chosen.start_year + i,
                                            ).map((y) => (
                                                <option key={y} value={y}>
                                                    {chosen.level === "college"
                                                        ? "Year"
                                                        : "Grade"}{" "}
                                                    {y}
                                                </option>
                                            ))}
                                        </select>
                                    </Field>
                                    <p>
                                        Assigned Course plan:{" "}
                                        <strong>
                                            {assigned?.version ?? "Needs setup"}
                                        </strong>
                                        . Curriculum is configured in School
                                        setup.
                                    </p>
                                </>
                            )}
                            <Button
                                type="button"
                                variant="secondary"
                                onClick={() => setTransfer(!transfer)}
                            >
                                {transfer
                                    ? "Cancel transfer process"
                                    : "Process Transfer"}
                            </Button>
                            <input
                                type="hidden"
                                name="transfer_requested"
                                value={transfer ? "1" : "0"}
                            />
                            {transfer && (
                                <Field label="Transfer reason">
                                    <textarea
                                        name="transfer_reason"
                                        defaultValue={a.transfer_reason ?? ""}
                                        required
                                        minLength={5}
                                        maxLength={2000}
                                        placeholder="Previous school / Course and reason for transfer"
                                    />
                                </Field>
                            )}
                        </SaveForm>
                    </Panel>
                    {e && a.transfer_requested && can_edit && (
                        <TransferEditor
                            application={a}
                            can_credit={can_credit}
                            options={options}
                        />
                    )}
                    {e && (
                        <Panel title="Draft subjects and class schedule">
                            <p>
                                The Section’s usual classes fill the draft.
                                Adjust for retakes or additional subjects in the
                                assigned Course plan.
                            </p>
                            <SaveForm
                                url={`/enrollment-applications/${a.id}/course/save`}
                                label="Save subjects · Continue to Accounting"
                                reset={false}
                                disabled={!can_edit}
                            >
                                <Field label="Section">
                                    <select
                                        name="section_id"
                                        value={section}
                                        onChange={(event) => {
                                            setSection(event.target.value);
                                            const ids = plan
                                                .filter(
                                                    (p) =>
                                                        p.status === "needed",
                                                )
                                                .map(
                                                    (p) =>
                                                        classes.find(
                                                            (c) =>
                                                                c.subject_id ===
                                                                    p.subject_id &&
                                                                c.sections?.some(
                                                                    (s) =>
                                                                        s.id ===
                                                                        Number(
                                                                            event
                                                                                .target
                                                                                .value,
                                                                        ),
                                                                ),
                                                        )?.id,
                                                )
                                                .filter(
                                                    (id): id is number => !!id,
                                                );
                                            setSelected(ids);
                                        }}
                                    >
                                        <option value="">Choose Section</option>
                                        {sections.map((s) => (
                                            <option key={s.id} value={s.id}>
                                                {s.name} ·{" "}
                                                {s.current_count ?? 0}/
                                                {s.capacity} Students
                                            </option>
                                        ))}
                                    </select>
                                </Field>
                                <input
                                    type="hidden"
                                    name="course_ids"
                                    value={JSON.stringify(selected)}
                                />
                                {plan
                                    .filter((p) => p.issues.length)
                                    .map((p) => (
                                        <Alert
                                            key={p.subject_id}
                                            title={`${p.code} · ${p.status}`}
                                            tone="warning"
                                        >
                                            {p.issues.join(" ")}
                                        </Alert>
                                    ))}
                                {subjects.map((s) => {
                                    const selectedId = selected.find((id) =>
                                        classes.some(
                                            (c) =>
                                                c.id === id &&
                                                c.subject_id === s.id,
                                        ),
                                    );
                                    return (
                                        <Field
                                            key={s.id}
                                            label={`${s.code} · ${s.name} · ${s.units} credits`}
                                        >
                                            <select
                                                value={selectedId ?? ""}
                                                onChange={(event) =>
                                                    setSelected([
                                                        ...selected.filter(
                                                            (id) =>
                                                                !classes.some(
                                                                    (c) =>
                                                                        c.id ===
                                                                            id &&
                                                                        c.subject_id ===
                                                                            s.id,
                                                                ),
                                                        ),
                                                        ...(event.target.value
                                                            ? [
                                                                  Number(
                                                                      event
                                                                          .target
                                                                          .value,
                                                                  ),
                                                              ]
                                                            : []),
                                                    ])
                                                }
                                            >
                                                <option value="">
                                                    Do not include
                                                </option>
                                                {classes
                                                    .filter(
                                                        (c) =>
                                                            c.subject_id ===
                                                            s.id,
                                                    )
                                                    .map((c) => (
                                                        <option
                                                            key={c.id}
                                                            value={c.id}
                                                        >
                                                            {c.section} ·{" "}
                                                            {c.schedule} ·{" "}
                                                            {c.teacher.name} ·{" "}
                                                            {c.roster_count ??
                                                                0}
                                                            /{c.capacity}
                                                        </option>
                                                    ))}
                                            </select>
                                        </Field>
                                    );
                                })}
                                {eligibility?.warnings.map((w) => (
                                    <Alert
                                        key={w}
                                        title="Review warning"
                                        tone="warning"
                                    >
                                        {w}
                                    </Alert>
                                ))}
                                {eligibility?.academic_issues.map((w) => (
                                    <p key={w} className="small">
                                        {w}
                                    </p>
                                ))}
                            </SaveForm>
                        </Panel>
                    )}
                </>
            )}
            {step === 3 && quote && (
                <>
                    <Panel title="Accounting">
                        <p>
                            Subject charges are calculated from the Course
                            plan’s Lecture and Laboratory credit allocations.
                        </p>
                        <QuoteTable quote={quote} />
                        <p>
                            Recorded outstanding balance:{" "}
                            <strong>{money(balance_cents)}</strong>
                        </p>
                        <p>
                            Clearance status:{" "}
                            <Badge
                                tone={
                                    eligibility?.financial_cleared
                                        ? "success"
                                        : "warning"
                                }
                            >
                                {eligibility?.financial_cleared
                                    ? "Cleared"
                                    : "Finance review required"}
                            </Badge>
                        </p>
                        <p className="small">
                            Finance Staff confirms the payment required under
                            the school’s payment arrangements. The subject
                            assessment is a quote; saving it does not record a
                            payment or add a ledger charge.
                        </p>
                        {can_finance && (
                            <ButtonLink
                                href={`/finance?student=${a.student.id}`}
                                secondary
                            >
                                Review with Finance
                            </ButtonLink>
                        )}
                        {can_edit && (
                            <div className="actions">
                                <SaveForm
                                    url={`/enrollment-applications/${a.id}/accounting`}
                                    label="Accounting reviewed · Continue"
                                >
                                    <input
                                        type="hidden"
                                        name="skip"
                                        value="0"
                                    />
                                </SaveForm>
                                <SaveForm
                                    url={`/enrollment-applications/${a.id}/accounting`}
                                    label="Skip Accounting · Review Pre-COR"
                                >
                                    <input
                                        type="hidden"
                                        name="skip"
                                        value="1"
                                    />
                                </SaveForm>
                            </div>
                        )}
                    </Panel>
                </>
            )}
            {step === 4 && pre_cor && quote && (
                <>
                    <Panel title="Review · Pre-COR">
                        <Badge tone="warning">
                            Pending enrollment · Pre-COR
                        </Badge>
                        <div className="record-grid">
                            <div>
                                <small>Student</small>
                                <strong>
                                    {pre_cor.student_name} ·{" "}
                                    {pre_cor.student_number}
                                </strong>
                            </div>
                            <div>
                                <small>Course / Year</small>
                                <strong>
                                    {pre_cor.course} · {pre_cor.year_level}
                                </strong>
                            </div>
                            <div>
                                <small>School Year / semester</small>
                                <strong>
                                    {pre_cor.school_year} · {pre_cor.period}
                                </strong>
                            </div>
                            <div>
                                <small>Course curriculum</small>
                                <strong>{pre_cor.curriculum}</strong>
                            </div>
                        </div>
                        <QuoteTable quote={quote} />
                        {a.accounting_skipped && (
                            <Alert title="Accounting skipped" tone="warning">
                                Save keeps enrollment pending until Finance
                                clearance and Registrar confirmation.
                            </Alert>
                        )}
                        {pendingTransfers && (
                            <Alert
                                title="Registrar transfer review required"
                                tone="warning"
                            >
                                Past subjects must have recorded credit
                                decisions before official enrollment can be
                                confirmed.
                            </Alert>
                        )}
                        {eligibility?.academic_issues.map((issue) => (
                            <p key={issue}>{issue}</p>
                        ))}
                        <p>
                            Finance clearance:{" "}
                            <strong>
                                {eligibility?.financial_cleared
                                    ? "Cleared"
                                    : "Pending"}
                            </strong>
                            .{" "}
                            {can_finalize
                                ? "The Registrar can confirm when all checks pass."
                                : "The Registrar issues the official COR after the required checks pass."}
                        </p>
                        {can_edit && (
                            <SaveForm
                                url={`/enrollment-applications/${a.id}/save`}
                                label={
                                    can_finalize &&
                                    eligibility?.ready &&
                                    !pendingTransfers
                                        ? "Save and confirm enrollment"
                                        : "Save pending enrollment"
                                }
                            />
                        )}
                        {a.saved_at && (
                            <div className="actions">
                                <ButtonLink
                                    href={`/enrollment-applications/${a.id}/pre-cor`}
                                    secondary
                                >
                                    View saved Pre-COR
                                </ButtonLink>
                                {e && (
                                    <ButtonLink
                                        href={`/enrollments/${e.id}`}
                                        secondary
                                    >
                                        Student enrollment record
                                    </ButtonLink>
                                )}
                            </div>
                        )}
                    </Panel>
                </>
            )}
        </Shell>
    );
}
