import { usePage } from "@inertiajs/react";
import { useState } from "react";
import Shell from "../components/Shell";
import {
    Badge,
    Button,
    Dialog,
    Empty,
    Errors,
    Field,
    Heading,
    Pagination,
    Panel,
    SaveForm,
    Table,
} from "../components/ui";
import {
    person,
    type Credit,
    type Options,
    type Paginated,
    type Shared,
    type Student,
} from "../types";
export default function Credits({
    credits,
    students,
    options,
}: {
    credits: Paginated<Credit>;
    students: Student[];
    options: Options;
}) {
    const [add, setAdd] = useState(false);
    const [approve, setApprove] = useState<Credit | null>(null);
    const { auth, roles } = usePage<Shared>().props;
    const canApprove = (c: Credit) =>
        auth?.assignments.some(
            (g) =>
                roles[g.role]?.permissions.includes("credit.approve") &&
                (g.branch_id === null || g.branch_id === c.branch_id),
        );
    return (
        <Shell title="Transfer credits">
            <Heading
                title="Transfer credits"
                description="Record external subjects and transcript evidence for registrar evaluation."
                action={
                    <Button icon="plus" onClick={() => setAdd(true)}>
                        Submit transfer credit
                    </Button>
                }
            />
            <Panel>
                <p>
                    Approved equivalents satisfy the mapped curriculum
                    requirement and prerequisites. Original external grades
                    remain separate from local grade calculations.
                </p>
                {credits.data.length ? (
                    <Table
                        columns={[
                            "Student",
                            "Equivalent subject",
                            "External record",
                            "Status",
                            "Actions",
                        ]}
                    >
                        {credits.data.map((c) => (
                            <tr key={c.id}>
                                <td>
                                    {person(c.student)}
                                    <small>{c.student.student_number}</small>
                                </td>
                                <td>
                                    {c.subject.code}
                                    <small>
                                        {c.curriculum.program.name} ·{" "}
                                        {c.curriculum.version}
                                    </small>
                                </td>
                                <td>
                                    {c.source_school}
                                    <small>
                                        {c.source_subject} · Original grade{" "}
                                        {c.source_grade}
                                    </small>
                                </td>
                                <td>
                                    <Badge
                                        tone={
                                            c.status === "approved"
                                                ? "success"
                                                : "warning"
                                        }
                                    >
                                        {c.status === "approved"
                                            ? "Approved"
                                            : "Pending review"}
                                    </Badge>
                                </td>
                                <td>
                                    <div className="actions">
                                        <a
                                            href={`/credits/${c.id}/transcript`}
                                            target="_blank"
                                            rel="noreferrer"
                                        >
                                            View transcript
                                        </a>
                                        {c.status === "pending" &&
                                            canApprove(c) && (
                                                <Button
                                                    variant="secondary"
                                                    onClick={() =>
                                                        setApprove(c)
                                                    }
                                                >
                                                    Approve equivalent
                                                </Button>
                                            )}
                                    </div>
                                </td>
                            </tr>
                        ))}
                    </Table>
                ) : (
                    <Empty title="No transfer-credit evaluations yet" />
                )}
                <Pagination page={credits} />
            </Panel>
            {add && (
                <Dialog
                    title="Submit transfer credit"
                    onClose={() => setAdd(false)}
                >
                    <Errors />
                    <SaveForm
                        url="/credits"
                        label="Submit for evaluation"
                        onSuccess={() => setAdd(false)}
                    >
                        <Field label="Student">
                            <select name="student_id" required>
                                <option value="">Choose student</option>
                                {students.map((s) => (
                                    <option key={s.id} value={s.id}>
                                        {s.student_number} · {person(s)}
                                    </option>
                                ))}
                            </select>
                        </Field>
                        <div className="form-grid">
                            <Field label="Branch">
                                <select name="branch_id" required>
                                    <option value="">Choose branch</option>
                                    {options.branches.map((b) => (
                                        <option key={b.id} value={b.id}>
                                            {b.name}
                                        </option>
                                    ))}
                                </select>
                            </Field>
                            <Field label="Curriculum version">
                                <select name="curriculum_id" required>
                                    <option value="">Choose curriculum</option>
                                    {options.curricula
                                        .filter((c) => c.published)
                                        .map((c) => (
                                            <option key={c.id} value={c.id}>
                                                {c.program.name} · {c.version}
                                            </option>
                                        ))}
                                </select>
                            </Field>
                            <Field label="Equivalent local subject">
                                <select name="subject_id" required>
                                    <option value="">Choose subject</option>
                                    {options.subjects.map((s) => (
                                        <option key={s.id} value={s.id}>
                                            {s.code} · {s.name}
                                        </option>
                                    ))}
                                </select>
                            </Field>
                            <Field label="Original external grade">
                                <input
                                    name="source_grade"
                                    required
                                    maxLength={80}
                                />
                            </Field>
                        </div>
                        <Field label="Source school">
                            <input name="source_school" required />
                        </Field>
                        <Field label="Source subject">
                            <input name="source_subject" required />
                        </Field>
                        <Field
                            label="Transcript evidence"
                            hint="PDF or image, up to 10 MB."
                        >
                            <input
                                name="transcript"
                                type="file"
                                required
                                accept=".pdf,.jpg,.jpeg,.png"
                            />
                        </Field>
                    </SaveForm>
                </Dialog>
            )}
            {approve && (
                <Dialog
                    title="Approve subject equivalency"
                    onClose={() => setApprove(null)}
                >
                    <Errors />
                    <p>
                        {person(approve.student)} · {approve.source_subject} →{" "}
                        {approve.subject.code}
                    </p>
                    <SaveForm
                        url={`/credits/${approve.id}/approve`}
                        label="Approve equivalent"
                        onSuccess={() => setApprove(null)}
                    >
                        <Field label="Evaluation reason">
                            <textarea
                                name="reason"
                                required
                                minLength={5}
                                maxLength={2000}
                            />
                        </Field>
                    </SaveForm>
                </Dialog>
            )}
        </Shell>
    );
}
