import { usePage } from "@inertiajs/react";
import { useState } from "react";
import Shell from "../components/Shell";
import {
    Badge,
    Alert,
    Button,
    ButtonLink,
    Dialog,
    Empty,
    Field,
    Heading,
    Panel,
    SaveForm,
    Table,
} from "../components/ui";
import { person, type Options, type Shared, type Student } from "../types";
import type { Application, Batch } from "../enrollment-workflow";

export default function EnrollmentBatch({
    batch,
    applications,
    students,
    options,
    can_add,
    can_manage,
}: {
    batch: Batch;
    applications: Application[];
    students: Student[];
    options: Options;
    can_add: boolean;
    can_manage: boolean;
}) {
    const { levels } = usePage<Shared>().props;
    const [adding, setAdding] = useState(false),
        [mode, setMode] = useState("existing"),
        [search, setSearch] = useState(""),
        [program, setProgram] = useState(""),
        [filter, setFilter] = useState("");
    const [removing, setRemoving] = useState<Application | null>(null);
    const actions = (a: Application) => (
        <div className="actions">
            {!a.admission_issue && (
                <ButtonLink
                    href={
                        a.origin === "legacy" || a.state === "enrolled"
                            ? `/enrollments/${a.enrollment_id}`
                            : `/enrollment-applications/${a.id}`
                    }
                    secondary
                >
                    {a.state === "enrolled" ? "View record" : "Continue"}
                </ButtonLink>
            )}
            {a.can_remove && (
                <Button variant="ghost" onClick={() => setRemoving(a)}>
                    Remove from batch
                </Button>
            )}
        </div>
    );
    const programs = options.programs.filter(
        (p) =>
            p.level === batch.level &&
            p.default_curriculum_id &&
            p.curriculum_template_id,
    );
    const chosen = programs.find((p) => p.id === Number(program));
    const matches = students.filter((s) =>
        (person(s) + " " + s.student_number)
            .toLowerCase()
            .includes(search.toLowerCase()),
    );
    const shown = applications.filter((a) =>
        (person(a.student) + " " + a.student.student_number)
            .toLowerCase()
            .includes(filter.toLowerCase()),
    );
    return (
        <Shell title="Enrollment batch">
            <Heading
                title={`${levels[batch.level]} enrollment`}
                description={`${batch.branch.name} · School Year ${batch.period.school_year} · ${batch.period.name}`}
                action={
                    batch.status === "open" && can_add ? (
                        <Button onClick={() => setAdding(true)}>
                            Add Student
                        </Button>
                    ) : undefined
                }
            />
            <div className="actions">
                <ButtonLink href="/enrollments" secondary>
                    All enrollment batches
                </ButtonLink>
                <Badge tone={batch.status === "open" ? "success" : "neutral"}>
                    {batch.status === "open"
                        ? "Open enrollment"
                        : "Closed enrollment"}
                </Badge>
                {can_manage && (
                    <SaveForm
                        url={`/enrollment-batches/${batch.id}/status`}
                        label={
                            batch.status === "open"
                                ? "Close enrollment"
                                : "Reopen enrollment"
                        }
                    >
                        <input
                            type="hidden"
                            name="status"
                            value={batch.status === "open" ? "closed" : "open"}
                        />
                    </SaveForm>
                )}
            </div>
            <Panel title="Students in this enrollment batch">
                <Field label="Search Student name or number">
                    <input
                        type="search"
                        value={filter}
                        onChange={(e) => setFilter(e.target.value)}
                    />
                </Field>
                {shown.length ? (
                    <>
                        <div className="phase-table">
                            <Table
                                columns={[
                                    "Student",
                                    "Course",
                                    "Year / Grade",
                                    "Enrollment status",
                                    "",
                                ]}
                            >
                                {shown.map((a) => (
                                    <tr key={a.id}>
                                        <td>
                                            <strong>{person(a.student)}</strong>
                                            <small>
                                                {a.student.student_number}
                                            </small>
                                            {a.student.is_blacklisted && (
                                                <Badge tone="danger">
                                                    Blacklisted
                                                </Badge>
                                            )}
                                        </td>
                                        <td>
                                            {a.enrollment?.curriculum.program
                                                .name ??
                                                a.requestedProgram?.name ??
                                                "To be selected"}
                                        </td>
                                        <td>
                                            {a.enrollment?.year_level ??
                                                a.proposed_year ??
                                                "—"}
                                        </td>
                                        <td>
                                            <Badge
                                                tone={
                                                    a.state === "enrolled"
                                                        ? "success"
                                                        : "warning"
                                                }
                                            >
                                                {a.state === "enrolled"
                                                    ? "Enrolled"
                                                    : a.state === "pending"
                                                      ? "Pending · Pre-COR"
                                                      : "In progress"}
                                            </Badge>
                                            {a.admission_issue && (
                                                <small>
                                                    {a.admission_issue}
                                                </small>
                                            )}
                                        </td>
                                        <td>{actions(a)}</td>
                                    </tr>
                                ))}
                            </Table>
                        </div>
                        <div className="phase-cards">
                            {shown.map((a) => (
                                <article className="subject-choice" key={a.id}>
                                    <strong>{person(a.student)}</strong>
                                    <small>{a.student.student_number}</small>
                                    <p>
                                        {a.enrollment?.curriculum.program
                                            .name ??
                                            a.requestedProgram?.name ??
                                            "Course to be selected"}{" "}
                                        · Year / Grade{" "}
                                        {a.enrollment?.year_level ??
                                            a.proposed_year ??
                                            "—"}
                                    </p>
                                    <p>
                                        <Badge
                                            tone={
                                                a.state === "enrolled"
                                                    ? "success"
                                                    : "warning"
                                            }
                                        >
                                            {a.state === "enrolled"
                                                ? "Enrolled"
                                                : a.state === "pending"
                                                  ? "Pending · Pre-COR"
                                                  : "In progress"}
                                        </Badge>
                                        {a.student.is_blacklisted && (
                                            <Badge tone="danger">
                                                Blacklisted
                                            </Badge>
                                        )}
                                    </p>
                                    {a.admission_issue && (
                                        <Alert
                                            title="Not eligible for this batch"
                                            tone="warning"
                                        >
                                            {a.admission_issue}
                                        </Alert>
                                    )}
                                    {actions(a)}
                                </article>
                            ))}
                        </div>
                    </>
                ) : (
                    <Empty title="No Students added">
                        Add an existing Student or create a Student record to
                        begin the enrollment wizard.
                    </Empty>
                )}
            </Panel>
            {removing && (
                <Dialog
                    title="Remove Student from enrollment batch"
                    onClose={() => setRemoving(null)}
                >
                    <p>
                        <strong>{person(removing.student)}</strong> ·{" "}
                        {removing.student.student_number}
                    </p>
                    <p>
                        This removes the unfinished enrollment from this batch.
                        The Student’s profile, previous enrollments, grades,
                        financial records and audit history are retained.
                    </p>
                    <SaveForm
                        url={`/enrollment-applications/${removing.id}/remove`}
                        label="Remove Student from batch"
                        variant="danger"
                        onSuccess={() => setRemoving(null)}
                    >
                        <Field label="Removal reason">
                            <textarea
                                name="reason"
                                required
                                minLength={5}
                                maxLength={2000}
                            />
                        </Field>
                    </SaveForm>
                </Dialog>
            )}
            {adding && (
                <Dialog
                    title="Add Student to enrollment"
                    onClose={() => setAdding(false)}
                >
                    <div className="actions">
                        <Button
                            variant={
                                mode === "existing" ? "primary" : "secondary"
                            }
                            onClick={() => setMode("existing")}
                        >
                            Find Student
                        </Button>
                        <Button
                            variant={mode === "new" ? "primary" : "secondary"}
                            onClick={() => setMode("new")}
                        >
                            New Student
                        </Button>
                    </div>
                    <SaveForm
                        key={mode}
                        url={`/enrollment-batches/${batch.id}/students`}
                        label="Begin enrollment"
                        onSuccess={() => setAdding(false)}
                    >
                        {mode === "existing" && (
                            <p className="small">
                                Only eligible Students from {batch.branch.name}{" "}
                                for {levels[batch.level]} appear. Students
                                already in this batch are omitted. Outstanding
                                debt remains a warning during Assessment.
                            </p>
                        )}
                        {mode === "existing" ? (
                            <>
                                <Field label="Search Student">
                                    <input
                                        type="search"
                                        value={search}
                                        onChange={(e) =>
                                            setSearch(e.target.value)
                                        }
                                        placeholder="Name or Student number"
                                    />
                                </Field>
                                <Field label="Student">
                                    <select name="student_id" required>
                                        <option value="">Choose Student</option>
                                        {matches.map((s) => (
                                            <option key={s.id} value={s.id}>
                                                {s.student_number} · {person(s)}
                                                {s.is_blacklisted
                                                    ? " · Blacklisted"
                                                    : ""}
                                            </option>
                                        ))}
                                    </select>
                                </Field>
                                <label className="checkbox">
                                    <input
                                        type="checkbox"
                                        name="is_transferee"
                                        value="1"
                                    />
                                    I am a transferee
                                </label>
                            </>
                        ) : (
                            <>
                                <div className="form-grid">
                                    <Field label="Student number">
                                        <input
                                            name="student_number"
                                            required
                                            maxLength={50}
                                        />
                                    </Field>
                                    <Field label="First name">
                                        <input
                                            name="first_name"
                                            required
                                            maxLength={160}
                                        />
                                    </Field>
                                    <Field label="Middle name">
                                        <input
                                            name="middle_name"
                                            maxLength={160}
                                        />
                                    </Field>
                                    <Field label="Last name">
                                        <input
                                            name="last_name"
                                            required
                                            maxLength={160}
                                        />
                                    </Field>
                                    <Field label="Birth date">
                                        <input name="birth_date" type="date" />
                                    </Field>
                                    <Field label="Email">
                                        <input name="email" type="email" />
                                    </Field>
                                    <Field label="Phone">
                                        <input name="phone" maxLength={40} />
                                    </Field>
                                    <Field label="Guardian name">
                                        <input
                                            name="guardian_name"
                                            maxLength={160}
                                        />
                                    </Field>
                                    <Field label="Guardian phone">
                                        <input
                                            name="guardian_phone"
                                            maxLength={40}
                                        />
                                    </Field>
                                </div>
                                <Field label="Course">
                                    <select
                                        name="program_id"
                                        value={program}
                                        onChange={(e) =>
                                            setProgram(e.target.value)
                                        }
                                        required
                                    >
                                        <option value="">Choose Course</option>
                                        {programs.map((p) => (
                                            <option key={p.id} value={p.id}>
                                                {p.name}
                                            </option>
                                        ))}
                                    </select>
                                </Field>
                                {chosen?.college && (
                                    <p>
                                        College:{" "}
                                        <strong>{chosen.college.name}</strong>
                                    </p>
                                )}
                                <Field label="Current Year / Grade">
                                    <select
                                        key={program}
                                        name="year_level"
                                        required
                                    >
                                        <option value="">
                                            Choose entry Year / Grade
                                        </option>
                                        {chosen &&
                                            Array.from(
                                                {
                                                    length: chosen.duration_years,
                                                },
                                                (_, i) => chosen.start_year + i,
                                            ).map((y) => (
                                                <option key={y} value={y}>
                                                    {batch.level === "college"
                                                        ? "Year"
                                                        : "Grade"}{" "}
                                                    {y}
                                                </option>
                                            ))}
                                    </select>
                                </Field>
                                <label className="checkbox">
                                    <input
                                        type="checkbox"
                                        name="is_transferee"
                                        value="1"
                                    />
                                    I am a transferee
                                </label>
                            </>
                        )}
                    </SaveForm>
                </Dialog>
            )}
        </Shell>
    );
}
