import { router, usePage } from "@inertiajs/react";
import { useState, type ReactNode } from "react";
import Shell from "../components/Shell";
import { periodName } from "../school-periods";
import MeetingEditor from "../components/MeetingEditor";
import {
    BranchCalendars,
    CourseStages,
    CurriculumCatalog,
    CurriculumChoice,
    UnitAllocation,
} from "../components/CurriculumSetup";
import {
    Alert,
    Badge,
    Button,
    ButtonLink,
    Field,
    Heading,
    Panel,
    SaveForm,
    Table,
} from "../components/ui";
import type { Curriculum, Meeting, Options, Section, Shared } from "../types";

const terms: Record<string, string> = {
    year: "Full school year",
    semester_1: "First semester",
    semester_2: "Second semester",
};
function Choice({
    name,
    label,
    rows,
    initial = "",
    optional = false,
}: {
    name: string;
    label: string;
    rows: { id: number | string; name: string }[];
    initial?: string | number;
    optional?: boolean;
}) {
    return (
        <Field label={label}>
            <select name={name} required={!optional} defaultValue={initial}>
                <option value="">
                    {optional ? "None" : `Choose ${label.toLowerCase()}`}
                </option>
                {rows.map((r) => (
                    <option key={r.id} value={r.id}>
                        {r.name}
                    </option>
                ))}
            </select>
        </Field>
    );
}
function Term({ initial = "" }: { initial?: string }) {
    return (
        <Choice
            name="term_key"
            label="Curriculum term"
            initial={initial}
            rows={Object.entries(terms).map(([id, name]) => ({ id, name }))}
        />
    );
}
function Add({ title, children }: { title: string; children: ReactNode }) {
    return (
        <details className="accordion">
            <summary>{title}</summary>
            <div>{children}</div>
        </details>
    );
}
function Reason() {
    return (
        <Field label="Reason">
            <textarea name="reason" required minLength={5} maxLength={2000} />
        </Field>
    );
}
function RequirementForm({ c, options }: { c: Curriculum; options: Options }) {
    const [subject, setSubject] = useState("");
    return (
        <SaveForm
            url="/setup/requirements"
            label="Add curriculum subject"
            transform={(data) => {
                data.set(
                    "prerequisite_ids",
                    JSON.stringify(
                        data.getAll("prerequisite_ids[]").map(Number),
                    ),
                );
                data.delete("prerequisite_ids[]");
                data.set("term_label", terms[String(data.get("term_key"))]);
            }}
        >
            <input type="hidden" name="curriculum_id" value={c.id} />
            <Field label="Subject">
                <select
                    name="subject_id"
                    required
                    value={subject}
                    onChange={(e) => setSubject(e.target.value)}
                >
                    <option value="">Choose Subject</option>
                    {options.subjects.map((s) => (
                        <option key={s.id} value={s.id}>
                            {s.code} · {s.name} · {s.units} credits
                        </option>
                    ))}
                </select>
            </Field>
            {subject && (
                <UnitAllocation
                    types={options.unit_types ?? []}
                    credits={
                        options.subjects.find((s) => s.id === Number(subject))
                            ?.units ?? "0"
                    }
                />
            )}
            <div className="form-grid">
                <Field label="Year / grade">
                    <input
                        name="year_level"
                        type="number"
                        required
                        min={1}
                        max={12}
                    />
                </Field>
                <Term />
                <Choice
                    name="classification"
                    label="Classification"
                    rows={[
                        { id: "Major", name: "Major" },
                        { id: "Minor", name: "Minor" },
                    ]}
                />
            </div>
            <fieldset>
                <legend>Prerequisites</legend>
                {c.subjects.length ? (
                    c.subjects.map((r) => (
                        <label className="checkbox" key={r.id}>
                            <input
                                type="checkbox"
                                name="prerequisite_ids[]"
                                value={r.subject_id}
                            />
                            <span>
                                {r.subject.code} · {r.subject.name}
                            </span>
                        </label>
                    ))
                ) : (
                    <p className="small">
                        Add other curriculum subjects first, then select any
                        prerequisites.
                    </p>
                )}
            </fieldset>
        </SaveForm>
    );
}
function ClassForm({ options }: { options: Options }) {
    const [branch, setBranch] = useState("");
    const [meetings, setMeetings] = useState<Meeting[]>([
        { day: 1, start: "", end: "" },
    ]);
    return (
        <SaveForm url="/setup/courses" label="Create Subject Class">
            <div className="form-grid">
                <Field label="Branch">
                    <select
                        name="branch_id"
                        required
                        value={branch}
                        onChange={(e) => setBranch(e.target.value)}
                    >
                        <option value="">Choose Branch</option>
                        {options.branches.map((b) => (
                            <option key={b.id} value={b.id}>
                                {b.name}
                            </option>
                        ))}
                    </select>
                </Field>
                <Choice
                    name="department_id"
                    label="Department"
                    rows={options.departments.filter(
                        (d) => String(d.branch_id) === branch,
                    )}
                />
                <Choice
                    name="academic_period_id"
                    label="Enrollment period"
                    rows={options.periods}
                />
                <Choice
                    name="program_id"
                    label="Course / school level"
                    rows={options.programs}
                />
                <Choice
                    name="subject_id"
                    label="Subject"
                    rows={options.subjects.map((s) => ({
                        id: s.id,
                        name: `${s.code} · ${s.name} (${s.units} units)`,
                    }))}
                />
                <Choice
                    name="teacher_id"
                    label="Teacher"
                    rows={options.teachers}
                />
                <Choice
                    name="grading_policy_id"
                    label="Final-grade scale"
                    rows={options.policies}
                />
                <Field label="Class code">
                    <input
                        name="section"
                        required
                        maxLength={60}
                        placeholder="e.g. ENG101-A"
                    />
                </Field>
                <Field label="Class capacity">
                    <input
                        name="capacity"
                        type="number"
                        required
                        min={1}
                        max={500}
                        defaultValue={40}
                    />
                </Field>
            </div>
            <p className="small">
                Students from other Courses can join when their curricula
                include this subject and the school level is compatible. Link
                the usual Sections after creating the class.
            </p>
            <input
                type="hidden"
                name="meetings"
                value={JSON.stringify(meetings)}
            />
            <MeetingEditor value={meetings} onChange={setMeetings} />
        </SaveForm>
    );
}
function ScaleForm({ levels }: { levels: Record<string, string> }) {
    const [scale, setScale] = useState("percentage");
    const [rows, setRows] = useState([{ grade: "", passed: false }]);
    return (
        <SaveForm url="/setup/policies" label="Save final-grade scale">
            <Field label="Scale name">
                <input name="name" required maxLength={160} />
            </Field>
            <Choice
                name="level"
                label="School level"
                rows={Object.entries(levels).map(([id, name]) => ({
                    id,
                    name,
                }))}
            />
            <Field label="Grade format">
                <select
                    name="scale"
                    value={scale}
                    onChange={(e) => setScale(e.target.value)}
                >
                    <option value="percentage">
                        Percentage (e.g. 75, 80, 85)
                    </option>
                    <option value="numeric">
                        Numeric values (e.g. 1.0, 2.0)
                    </option>
                </select>
            </Field>
            {scale === "percentage" ? (
                <Field label="Passing mark">
                    <input
                        name="passing_mark"
                        type="number"
                        min={0}
                        max={100}
                        step="0.01"
                        required
                    />
                </Field>
            ) : (
                <>
                    <p>
                        List the school's allowed numeric grades and mark which
                        values pass.
                    </p>
                    {rows.map((row, i) => (
                        <div className="form-grid" key={i}>
                            <Field label={`Allowed grade ${i + 1}`}>
                                <input
                                    type="number"
                                    min={0}
                                    max={100}
                                    step="0.01"
                                    required
                                    value={row.grade}
                                    onChange={(e) =>
                                        setRows(
                                            rows.map((r, n) =>
                                                n === i
                                                    ? {
                                                          ...r,
                                                          grade: e.target.value,
                                                      }
                                                    : r,
                                            ),
                                        )
                                    }
                                />
                            </Field>
                            <label className="checkbox">
                                <input
                                    type="checkbox"
                                    checked={row.passed}
                                    onChange={(e) =>
                                        setRows(
                                            rows.map((r, n) =>
                                                n === i
                                                    ? {
                                                          ...r,
                                                          passed: e.target
                                                              .checked,
                                                      }
                                                    : r,
                                            ),
                                        )
                                    }
                                />
                                <span>Passing grade</span>
                            </label>
                        </div>
                    ))}
                    <Button
                        type="button"
                        variant="secondary"
                        onClick={() =>
                            setRows([...rows, { grade: "", passed: false }])
                        }
                    >
                        Add allowed grade
                    </Button>
                </>
            )}
            <input
                type="hidden"
                name="conversions"
                value={JSON.stringify(
                    scale === "numeric"
                        ? rows.map((r) => ({
                              grade: Number(r.grade),
                              passed: r.passed,
                          }))
                        : [],
                )}
            />
        </SaveForm>
    );
}
function SchoolYearForm() {
    const [year, setYear] = useState("");
    const [term, setTerm] = useState("year");
    const name =
        term === "year"
            ? `School Year ${year}`
            : `${term === "semester_1" ? "First Semester" : "Second Semester"} · ${year}`;
    return (
        <SaveForm url="/setup/periods" label="Add school year / semester">
            <Field label="School year">
                <input
                    name="school_year"
                    required
                    placeholder="2026–2027"
                    value={year}
                    onChange={(event) =>
                        setYear(event.target.value.replace(/-/g, "–"))
                    }
                />
            </Field>
            <Field label="Coverage">
                <select
                    name="term_key"
                    value={term}
                    onChange={(event) => setTerm(event.target.value)}
                >
                    <option value="year">Full School Year</option>
                    <option value="semester_1">First Semester</option>
                    <option value="semester_2">Second Semester</option>
                </select>
            </Field>
            <input type="hidden" name="name" value={name} />
            <input
                type="hidden"
                name="kind"
                value={term === "year" ? "year" : "semester"}
            />
            <div className="form-grid">
                <Field label="Classes start">
                    <input name="starts_on" type="date" required />
                </Field>
                <Field label="Classes end">
                    <input name="ends_on" type="date" required />
                </Field>
            </div>
            <input type="hidden" name="enrollment_open" value="0" />
            <p className="small">
                After creating this School Year, enable it for a Branch below
                and open its enrollment batch from Enrollments.
            </p>
            {year && <p className="small">Adding: {name}</p>}
        </SaveForm>
    );
}
function CourseForm({
    options,
    levels,
}: {
    options: Options;
    levels: Record<string, string>;
}) {
    const [level, setLevel] = useState("college");
    return (
        <SaveForm url="/setup/programs" label="Add Course">
            <CurriculumChoice options={options} />
            <CourseStages level={level} />
            <Field label="Course name">
                <input name="name" required maxLength={160} />
            </Field>
            <Field label="School level">
                <select
                    name="level"
                    value={level}
                    onChange={(event) => setLevel(event.target.value)}
                >
                    {Object.entries(levels).map(([key, name]) => (
                        <option key={key} value={key}>
                            {name}
                        </option>
                    ))}
                </select>
            </Field>
            {level === "college" && (
                <Choice
                    name="college_id"
                    label="College"
                    rows={options.colleges}
                />
            )}
            <p className="small">
                Create the Course, then prepare and publish its curriculum.
                Enrollment will apply that curriculum automatically.
            </p>
        </SaveForm>
    );
}
export default function AcademicSetup(
    options: Options & { sections: Section[]; global_setup: boolean },
) {
    const { levels } = usePage<Shared>().props;
    const tabs = [
        "Courses & curricula",
        "Sections",
        "Subject Classes",
        "School years & grades",
    ];
    const [tab, setTab] = useState(tabs[0]);
    const sectionRows = options.sections.map((s) => ({
        id: s.id,
        name: `${s.name} · ${s.branch?.name}`,
    }));
    const classRows = options.courses.map((c) => ({
        id: c.id,
        name: `${c.subject.code} · ${c.section} · ${c.period.name} · ${c.branch.name}`,
    }));
    return (
        <Shell title="School setup">
            <Heading
                title="School setup"
                description="Prepare the curriculum, student groups and actual teaching timetable before enrollment."
            />
            {options.courses.some((c) => !c.meetings?.length) && (
                <Alert
                    title="Some existing timetables need review"
                    tone="warning"
                >
                    Enter weekly meeting times on the{" "}
                    <a href="/schedule">Schedules page</a> so conflict checks
                    can be completed.
                </Alert>
            )}
            <div
                className="tabs setup-tabs"
                role="tablist"
                aria-label="School setup areas"
            >
                {tabs.map((t) => (
                    <button
                        role="tab"
                        aria-selected={tab === t}
                        aria-controls="setup-content"
                        key={t}
                        onClick={() => setTab(t)}
                    >
                        {t}
                    </button>
                ))}
            </div>
            <div id="setup-content" role="tabpanel" className="form-stack">
                {tab === tabs[0] && (
                    <>
                        <CurriculumCatalog options={options} />
                        <Panel title="Colleges">
                            <p className="small">
                                A College groups degree Courses, such as the
                                College of Engineering. Branches are campuses.
                            </p>
                            {options.colleges.map((college) => (
                                <p key={college.id}>
                                    <strong>{college.name}</strong>
                                </p>
                            ))}
                            {options.global_setup && (
                                <Add title="Add College">
                                    <SaveForm
                                        url="/academic/setup"
                                        label="Add College"
                                    >
                                        <input
                                            type="hidden"
                                            name="operation"
                                            value="college"
                                        />
                                        <Field label="College name">
                                            <input
                                                name="name"
                                                required
                                                maxLength={160}
                                                placeholder="e.g. College of Engineering"
                                            />
                                        </Field>
                                    </SaveForm>
                                </Add>
                            )}
                        </Panel>
                        <Panel title="Courses">
                            <Table
                                columns={[
                                    "College",
                                    "Course",
                                    "School level",
                                    "Curriculum for new Students",
                                ]}
                            >
                                {options.programs.map((p) => (
                                    <tr key={p.id}>
                                        <td>
                                            {p.college?.name ||
                                                (p.level === "college"
                                                    ? "Needs setup"
                                                    : "Not applicable")}
                                        </td>
                                        <td>{p.name}</td>
                                        <td>{levels[p.level]}</td>
                                        <td>
                                            {options.curricula.find(
                                                (c) =>
                                                    c.id ===
                                                    p.default_curriculum_id,
                                            )?.version ||
                                                "Publish and set a curriculum"}
                                        </td>
                                    </tr>
                                ))}
                            </Table>
                            {options.global_setup &&
                                options.programs.map((program) => {
                                    const versions = options.curricula.filter(
                                        (c) =>
                                            c.program_id === program.id &&
                                            c.published,
                                    );
                                    return (
                                        <Add
                                            key={program.id}
                                            title={`Configure ${program.name}`}
                                        >
                                            <SaveForm
                                                url="/academic/setup"
                                                label="Save Course settings"
                                            >
                                                <input
                                                    type="hidden"
                                                    name="operation"
                                                    value="course_settings"
                                                />
                                                <input
                                                    type="hidden"
                                                    name="program_id"
                                                    value={program.id}
                                                />
                                                <CurriculumChoice
                                                    options={options}
                                                    initial={
                                                        program.curriculum_template_id
                                                    }
                                                />
                                                <CourseStages
                                                    program={program}
                                                />
                                                {program.level ===
                                                    "college" && (
                                                    <Choice
                                                        name="college_id"
                                                        label="College"
                                                        rows={options.colleges}
                                                        initial={
                                                            program.college_id ??
                                                            ""
                                                        }
                                                    />
                                                )}
                                                <Choice
                                                    name="curriculum_id"
                                                    label="Curriculum for new Students"
                                                    initial={
                                                        program.default_curriculum_id ??
                                                        ""
                                                    }
                                                    optional={!versions.length}
                                                    rows={versions.map((c) => ({
                                                        id: c.id,
                                                        name: c.version,
                                                    }))}
                                                />
                                                <p className="small">
                                                    This curriculum is applied
                                                    automatically at enrollment.
                                                    Returning Students retain
                                                    their already assigned
                                                    version.
                                                </p>
                                            </SaveForm>
                                        </Add>
                                    );
                                })}
                            {options.global_setup && (
                                <Add title="Add Course">
                                    <CourseForm
                                        options={options}
                                        levels={levels}
                                    />
                                </Add>
                            )}
                        </Panel>
                        <Panel title="Subject catalog">
                            <Table columns={["Code / subject", "Units"]}>
                                {options.subjects.map((s) => (
                                    <tr key={s.id}>
                                        <td>
                                            <strong>{s.code}</strong>
                                            <small>{s.name}</small>
                                        </td>
                                        <td>{s.units}</td>
                                    </tr>
                                ))}
                            </Table>
                            {options.global_setup && (
                                <Add title="Add subject">
                                    <SaveForm
                                        url="/setup/subjects"
                                        label="Add subject"
                                    >
                                        <div className="form-grid">
                                            <Field label="Subject code">
                                                <input
                                                    name="code"
                                                    required
                                                    maxLength={30}
                                                />
                                            </Field>
                                            <Field label="Subject name">
                                                <input
                                                    name="name"
                                                    required
                                                    maxLength={160}
                                                />
                                            </Field>
                                            <Field label="Credit units">
                                                <input
                                                    name="units"
                                                    type="number"
                                                    min="0.01"
                                                    max={30}
                                                    step="0.01"
                                                    required
                                                />
                                            </Field>
                                        </div>
                                    </SaveForm>
                                </Add>
                            )}
                        </Panel>
                        <Panel title="Course subject plans">
                            <p className="small">
                                Each curriculum defines subjects by Year/Grade
                                and term. Major/Minor classification belongs
                                here; weekly times belong to Subject Classes.
                            </p>
                            {options.curricula.map((c) => (
                                <Add
                                    key={c.id}
                                    title={`${c.program.name} · ${c.version} · ${c.published ? "Published" : "Draft"}`}
                                >
                                    <Table
                                        columns={[
                                            "Subject",
                                            "Year / grade",
                                            "Term",
                                            "Classification",
                                        ]}
                                    >
                                        {c.subjects.map((r) => (
                                            <tr key={r.id}>
                                                <td>
                                                    {r.subject.code}
                                                    <small>
                                                        {r.subject.name}
                                                    </small>
                                                    {r.prerequisites.length >
                                                        0 && (
                                                        <small>
                                                            Requires:{" "}
                                                            {r.prerequisites
                                                                .map(
                                                                    (p) =>
                                                                        p
                                                                            .requiredSubject
                                                                            ?.code,
                                                                )
                                                                .join(", ")}
                                                        </small>
                                                    )}
                                                </td>
                                                <td>{r.year_level}</td>
                                                <td>
                                                    {r.term_key
                                                        ? terms[r.term_key]
                                                        : "Needs review"}
                                                </td>
                                                <td>
                                                    {r.classification ??
                                                        "Needs review"}
                                                    {r.unitLines?.map((l) => (
                                                        <small key={l.id}>
                                                            {l.unitType.name}:{" "}
                                                            {l.credits} credits
                                                        </small>
                                                    ))}
                                                </td>
                                            </tr>
                                        ))}
                                    </Table>
                                    {options.global_setup &&
                                        c.subjects
                                            .filter(
                                                (r) =>
                                                    !r.term_key ||
                                                    !r.classification,
                                            )
                                            .map((r) => (
                                                <Add
                                                    key={r.id}
                                                    title={`Review existing requirement: ${r.subject.code}`}
                                                >
                                                    <SaveForm
                                                        url="/academic/setup"
                                                        label="Record requirement review"
                                                    >
                                                        <input
                                                            type="hidden"
                                                            name="operation"
                                                            value="requirement_mapping"
                                                        />
                                                        <input
                                                            type="hidden"
                                                            name="requirement_id"
                                                            value={r.id}
                                                        />
                                                        <Term
                                                            initial={
                                                                r.term_key ?? ""
                                                            }
                                                        />
                                                        <Choice
                                                            name="classification"
                                                            label="Classification"
                                                            initial={
                                                                r.classification ??
                                                                ""
                                                            }
                                                            rows={[
                                                                {
                                                                    id: "Major",
                                                                    name: "Major",
                                                                },
                                                                {
                                                                    id: "Minor",
                                                                    name: "Minor",
                                                                },
                                                            ]}
                                                        />
                                                        <Reason />
                                                    </SaveForm>
                                                </Add>
                                            ))}
                                    {!c.published && options.global_setup && (
                                        <>
                                            {c.subjects.map((r) => (
                                                <Add
                                                    key={`units-${r.id}`}
                                                    title={`Edit ${r.subject.code} Lecture / Laboratory credits`}
                                                >
                                                    <SaveForm
                                                        url="/academic/setup"
                                                        label="Save subject Unit Types"
                                                        reset={false}
                                                    >
                                                        <input
                                                            type="hidden"
                                                            name="operation"
                                                            value="unit_allocation"
                                                        />
                                                        <input
                                                            type="hidden"
                                                            name="requirement_id"
                                                            value={r.id}
                                                        />
                                                        <UnitAllocation
                                                            types={
                                                                options.unit_types ??
                                                                []
                                                            }
                                                            credits={
                                                                r.subject.units
                                                            }
                                                            requirement={r}
                                                        />
                                                    </SaveForm>
                                                </Add>
                                            ))}
                                            <RequirementForm
                                                c={c}
                                                options={options}
                                            />
                                            <SaveForm
                                                url={`/curricula/${c.id}/publish`}
                                                label="Publish curriculum version"
                                            >
                                                <p>
                                                    Review the subject sequence
                                                    and prerequisites. Published
                                                    versions stay locked for
                                                    assigned Students.
                                                </p>
                                            </SaveForm>
                                            {c.subjects.map((r) => (
                                                <div
                                                    key={r.id}
                                                    className="actions"
                                                >
                                                    <Button
                                                        type="button"
                                                        variant="ghost"
                                                        onClick={() => {
                                                            if (
                                                                window.confirm(
                                                                    `Remove ${r.subject.code} from this draft curriculum?`,
                                                                )
                                                            )
                                                                router.delete(
                                                                    `/requirements/${r.id}`,
                                                                    {
                                                                        preserveScroll: true,
                                                                    },
                                                                );
                                                        }}
                                                    >
                                                        Remove {r.subject.code}{" "}
                                                        from draft
                                                    </Button>
                                                </div>
                                            ))}
                                        </>
                                    )}
                                </Add>
                            ))}
                            {options.global_setup && (
                                <Add title="Create curriculum version">
                                    <SaveForm
                                        url="/setup/curricula"
                                        label="Create curriculum version"
                                    >
                                        <Choice
                                            name="program_id"
                                            label="Course"
                                            rows={options.programs}
                                        />
                                        <CurriculumChoice options={options} />
                                        <Field label="Version">
                                            <input
                                                name="version"
                                                required
                                                maxLength={60}
                                                placeholder="e.g. 2026"
                                            />
                                        </Field>
                                    </SaveForm>
                                </Add>
                            )}
                        </Panel>
                    </>
                )}
                {tab === tabs[1] && (
                    <>
                        <Panel title="Sections">
                            <p>
                                A Section is a continuing collection of
                                Students. Each Subject Class has its own
                                timetable and actual roster.
                            </p>
                            <ButtonLink href="/sections" secondary>
                                View Section memberships
                            </ButtonLink>
                            {options.sections.map((s) => (
                                <Add
                                    key={s.id}
                                    title={`${s.name} · ${s.branch?.name} · ${s.current_count ?? 0}/${s.capacity} members`}
                                >
                                    <SaveForm
                                        url="/academic/setup"
                                        label="Update Section capacity"
                                    >
                                        <input
                                            type="hidden"
                                            name="operation"
                                            value="limits"
                                        />
                                        <input
                                            type="hidden"
                                            name="target"
                                            value="section"
                                        />
                                        <input
                                            type="hidden"
                                            name="target_id"
                                            value={s.id}
                                        />
                                        <Field label="Section capacity">
                                            <input
                                                type="number"
                                                name="capacity"
                                                min={1}
                                                max={500}
                                                required
                                                defaultValue={s.capacity}
                                            />
                                        </Field>
                                    </SaveForm>
                                    {s.availabilities?.map((a) => (
                                        <div className="record-item" key={a.id}>
                                            <div>
                                                <strong>
                                                    {a.program.name} ·
                                                    Year/Grade {a.year_level}
                                                </strong>
                                                <small>
                                                    {a.period.name} · Fill order{" "}
                                                    {a.sort_order}
                                                </small>
                                            </div>
                                            <SaveForm
                                                url="/academic/setup"
                                                label="Remove availability"
                                            >
                                                <input
                                                    type="hidden"
                                                    name="operation"
                                                    value="availability_remove"
                                                />
                                                <input
                                                    type="hidden"
                                                    name="availability_id"
                                                    value={a.id}
                                                />
                                            </SaveForm>
                                        </div>
                                    ))}
                                    <p className="small">
                                        Usual classes:{" "}
                                        {s.classes
                                            ?.map(
                                                (c) =>
                                                    `${c.subject.code} (${c.period.name})`,
                                            )
                                            .join(", ") || "None linked yet"}
                                    </p>
                                </Add>
                            ))}
                        </Panel>
                        <Panel title="Create Section">
                            <SaveForm
                                url="/academic/setup"
                                label="Create Section"
                            >
                                <input
                                    type="hidden"
                                    name="operation"
                                    value="section"
                                />
                                <Choice
                                    name="branch_id"
                                    label="Branch"
                                    rows={options.branches}
                                />
                                <Choice
                                    name="department_id"
                                    label="Department"
                                    optional
                                    rows={options.departments.map((d) => ({
                                        id: d.id,
                                        name: `${d.name} · ${d.branch?.name ?? ""}`,
                                    }))}
                                />
                                <Field label="Section name">
                                    <input
                                        name="name"
                                        required
                                        maxLength={160}
                                    />
                                </Field>
                                <Field label="Section capacity">
                                    <input
                                        name="capacity"
                                        type="number"
                                        min={1}
                                        max={500}
                                        required
                                        defaultValue={40}
                                    />
                                </Field>
                            </SaveForm>
                        </Panel>
                        <Panel title="Available Sections and fill order">
                            <SaveForm
                                url="/academic/setup"
                                label="Save availability"
                            >
                                <input
                                    type="hidden"
                                    name="operation"
                                    value="availability"
                                />
                                <Choice
                                    name="section_id"
                                    label="Section"
                                    rows={sectionRows}
                                />
                                <Choice
                                    name="program_id"
                                    label="Course"
                                    rows={options.programs}
                                />
                                <Choice
                                    name="academic_period_id"
                                    label="Enrollment period"
                                    rows={options.periods}
                                />
                                <div className="form-grid">
                                    <Field label="Incoming Year / Grade">
                                        <input
                                            name="year_level"
                                            type="number"
                                            min={1}
                                            max={12}
                                            required
                                        />
                                    </Field>
                                    <Field label="Fill order">
                                        <input
                                            name="sort_order"
                                            type="number"
                                            min={1}
                                            max={10000}
                                            required
                                            defaultValue={1}
                                        />
                                    </Field>
                                </div>
                                <p className="small">
                                    The first eligible Section with space is
                                    suggested. Existing Students keep their
                                    continuing Section.
                                </p>
                            </SaveForm>
                        </Panel>
                        <Panel title="Link a Section’s usual Subject Classes">
                            <SaveForm
                                url="/academic/setup"
                                label="Save usual class"
                            >
                                <input
                                    type="hidden"
                                    name="operation"
                                    value="class_link"
                                />
                                <Choice
                                    name="section_id"
                                    label="Section"
                                    rows={sectionRows}
                                />
                                <Choice
                                    name="course_offering_id"
                                    label="Subject Class"
                                    rows={classRows}
                                />
                                <Choice
                                    name="action"
                                    label="Action"
                                    initial="add"
                                    rows={[
                                        { id: "add", name: "Link class" },
                                        { id: "remove", name: "Unlink class" },
                                    ]}
                                />
                            </SaveForm>
                        </Panel>
                    </>
                )}
                {tab === tabs[2] && (
                    <>
                        <Panel title="Subject Classes">
                            <ButtonLink href="/schedule" secondary>
                                Review weekly timetables
                            </ButtonLink>
                            {options.courses.map((c) => (
                                <Add
                                    key={c.id}
                                    title={`${c.subject.code} · ${c.section} · ${c.period.name}`}
                                >
                                    <p>
                                        {c.subject.name} · {c.teacher.name} ·{" "}
                                        {c.branch.name}
                                    </p>
                                    <p>
                                        {c.meetings?.length
                                            ? c.schedule
                                            : "Meeting times need review"}
                                    </p>
                                    <p>
                                        Usual Sections:{" "}
                                        {c.sections
                                            ?.map((s) => s.name)
                                            .join(", ") || "Not linked"}
                                    </p>
                                    <ButtonLink
                                        href={`/classes/${c.id}`}
                                        secondary
                                    >
                                        View class roster
                                    </ButtonLink>
                                    <SaveForm
                                        url="/academic/setup"
                                        label="Update class capacity"
                                    >
                                        <input
                                            type="hidden"
                                            name="operation"
                                            value="limits"
                                        />
                                        <input
                                            type="hidden"
                                            name="target"
                                            value="class"
                                        />
                                        <input
                                            type="hidden"
                                            name="target_id"
                                            value={c.id}
                                        />
                                        <Field label="Class capacity">
                                            <input
                                                name="capacity"
                                                type="number"
                                                min={1}
                                                max={500}
                                                required
                                                defaultValue={c.capacity}
                                            />
                                        </Field>
                                    </SaveForm>
                                </Add>
                            ))}
                        </Panel>
                        <Panel title="Create Subject Class">
                            <ClassForm options={options} />
                        </Panel>
                    </>
                )}
                {tab === tabs[3] && (
                    <>
                        <BranchCalendars options={options} levels={levels} />
                        <Panel title="School years and semesters">
                            {options.periods.map((p) => (
                                <Add
                                    key={p.id}
                                    title={`${p.school_year} · ${periodName(p)}`}
                                >
                                    <p>
                                        {p.school_year} ·{" "}
                                        {p.starts_on.slice(0, 10)} –{" "}
                                        {p.ends_on.slice(0, 10)}
                                    </p>
                                    <Badge>
                                        {p.term_key
                                            ? terms[p.term_key]
                                            : "Term needs review"}
                                    </Badge>
                                    {options.global_setup && (
                                        <>
                                            {!p.term_key && (
                                                <SaveForm
                                                    url="/academic/setup"
                                                    label="Record period term review"
                                                >
                                                    <input
                                                        type="hidden"
                                                        name="operation"
                                                        value="period_mapping"
                                                    />
                                                    <input
                                                        type="hidden"
                                                        name="academic_period_id"
                                                        value={p.id}
                                                    />
                                                    <Term />
                                                    <Reason />
                                                </SaveForm>
                                            )}
                                        </>
                                    )}
                                </Add>
                            ))}
                        </Panel>
                        {options.global_setup && (
                            <>
                                <Panel title="Add school year or semester">
                                    <SchoolYearForm />
                                </Panel>
                                <Panel title="Final-grade scales">
                                    <p>
                                        Teachers enter final grades directly. No
                                        assessment scores or grade calculations
                                        are required.
                                    </p>
                                    {options.policies.map((p) => (
                                        <p key={p.id}>
                                            <strong>{p.name}</strong> ·{" "}
                                            {levels[p.level]} ·{" "}
                                            {p.scale === "percentage"
                                                ? `Passing mark: ${p.passing_mark}`
                                                : p.conversions
                                                      .map(
                                                          (r) =>
                                                              `${r.grade} (${r.passed ? "Pass" : "Fail"})`,
                                                      )
                                                      .join(", ")}
                                        </p>
                                    ))}
                                    <Add title="Create final-grade scale">
                                        <ScaleForm levels={levels} />
                                    </Add>
                                </Panel>
                                <Panel title="Branches and departments">
                                    <Add title="Add Branch">
                                        <SaveForm
                                            url="/setup/branches"
                                            label="Add Branch"
                                        >
                                            <Field label="Branch name">
                                                <input name="name" required />
                                            </Field>
                                            <Field label="Branch code">
                                                <input
                                                    name="code"
                                                    required
                                                    maxLength={20}
                                                />
                                            </Field>
                                        </SaveForm>
                                    </Add>
                                    <Add title="Add department">
                                        <SaveForm
                                            url="/setup/departments"
                                            label="Add department"
                                        >
                                            <Choice
                                                name="branch_id"
                                                label="Branch"
                                                rows={options.branches}
                                            />
                                            <Field label="Department name">
                                                <input name="name" required />
                                            </Field>
                                        </SaveForm>
                                    </Add>
                                </Panel>
                            </>
                        )}
                    </>
                )}
            </div>
        </Shell>
    );
}
