import { router, usePage } from "@inertiajs/react";
import { useState } from "react";
import Shell from "../components/Shell";
import { QuoteTable } from "./EnrollmentWizard";
import type { Quote } from "../enrollment-workflow";
import {
    Alert,
    Badge,
    Button,
    Dialog,
    Empty,
    Errors,
    Field,
    Heading,
    Panel,
    SaveForm,
    Table,
} from "../components/ui";
import {
    money,
    person,
    type Enrollment,
    type FinancialEntry,
    type Options,
    type Shared,
    type Student,
} from "../types";

interface ClearanceItem extends Enrollment {
    quote: Quote | null;
    accounting_skipped: boolean;
    past_balance_cents: number;
    clearance_valid: boolean;
    arrangement_valid: boolean;
}
export default function Finance({
    students,
    selected,
    entries,
    balance_cents,
    enrollments,
    options,
}: {
    students: Student[];
    selected: Student | null;
    entries: FinancialEntry[];
    balance_cents: number;
    enrollments: ClearanceItem[];
    options: Options;
}) {
    const { auth, roles } = usePage<Shared>().props;
    const [clearing, setClearing] = useState<ClearanceItem | null>(null);
    const [arranging, setArranging] = useState<ClearanceItem | null>(null);
    const [recording, setRecording] = useState(false);
    const canArrange = (e: Enrollment) =>
        auth?.assignments.some(
            (g) =>
                roles[g.role]?.permissions.includes("finance.approve") &&
                (g.branch_id === null || g.branch_id === e.branch_id) &&
                g.department_id === null,
        );
    return (
        <Shell title="Financial clearance">
            <Heading
                title="Financial clearance"
                description="Finance Staff records Cleared or On Hold. Past-debt payment arrangements require Finance Approver approval."
            />
            <Panel>
                <Field label="Student financial records">
                    <select
                        value={selected?.id ?? ""}
                        onChange={(event) =>
                            router.get(
                                "/finance",
                                event.target.value
                                    ? { student: event.target.value }
                                    : {},
                            )
                        }
                    >
                        <option value="">All pending enrollments</option>
                        {students.map((s) => (
                            <option key={s.id} value={s.id}>
                                {s.student_number + " · " + person(s)}
                            </option>
                        ))}
                    </select>
                </Field>
            </Panel>
            {selected && (
                <Panel title={person(selected)}>
                    <p>{selected.student_number}</p>
                    <div className="record-item">
                        <div>
                            <small>Recorded outstanding balance</small>
                            <strong>{money(balance_cents)}</strong>
                        </div>
                        <Button
                            variant="secondary"
                            onClick={() => setRecording(true)}
                        >
                            Record charge or payment
                        </Button>
                    </div>
                    <p className="small">
                        Current-term payment conditions are reviewed manually.
                        Entries assigned to earlier periods, or opening balances
                        without a period, are treated as previous debt.
                    </p>
                </Panel>
            )}
            <Panel title="Enrollment clearance decisions">
                {!enrollments.length && (
                    <Empty title="No enrollments to review">
                        Choose a Student or wait for Enrollment Staff to prepare
                        a draft.
                    </Empty>
                )}
                {enrollments.map((e) => (
                    <article className="subject-choice" key={e.id}>
                        <div className="record-item">
                            <div>
                                <strong>{person(e.student)}</strong>
                                <small>
                                    {e.student.student_number} · {e.period.name}{" "}
                                    · {e.branch.name}
                                </small>
                            </div>
                            <Badge
                                tone={e.clearance_valid ? "success" : "warning"}
                            >
                                {e.clearance_valid
                                    ? "Cleared"
                                    : e.clearance?.status === "on_hold"
                                      ? "On Hold"
                                      : e.clearance
                                        ? "Needs clearance review"
                                        : "Awaiting clearance"}
                            </Badge>
                        </div>
                        <p>
                            Previous debt:{" "}
                            <strong>{money(e.past_balance_cents)}</strong>
                        </p>
                        {e.quote && (
                            <details className="accordion">
                                <summary>
                                    Enrollment assessment ·{" "}
                                    {money(e.quote.total_cents)}
                                    {e.accounting_skipped
                                        ? " · Accounting skipped"
                                        : ""}
                                </summary>
                                <div>
                                    <QuoteTable quote={e.quote} />
                                    <p className="small">
                                        Review these charges when deciding
                                        payment requirements and clearance. A
                                        quote does not post ledger charges or
                                        payments.
                                    </p>
                                </div>
                            </details>
                        )}
                        {e.clearance?.reason && (
                            <p>Decision notes: {e.clearance.reason}</p>
                        )}
                        {e.past_balance_cents > 0 && (
                            <p>
                                <Badge
                                    tone={
                                        e.arrangement_valid
                                            ? "success"
                                            : "warning"
                                    }
                                >
                                    {e.arrangement_valid
                                        ? "Payment arrangement approved"
                                        : "Finance Approver approval required"}
                                </Badge>
                            </p>
                        )}
                        {e.clearance?.arrangement_terms && (
                            <details className="accordion">
                                <summary>Recorded arrangement</summary>
                                <div>
                                    <p>{e.clearance.arrangement_terms}</p>
                                    <p>{e.clearance.arrangement_reason}</p>
                                    <p className="small">
                                        Changes to financial records require
                                        review of clearance and the arrangement.
                                    </p>
                                </div>
                            </details>
                        )}
                        <div className="actions">
                            <Button onClick={() => setClearing(e)}>
                                Record Cleared / On Hold
                            </Button>
                            {canArrange(e) && e.past_balance_cents > 0 && (
                                <Button
                                    variant="secondary"
                                    onClick={() => setArranging(e)}
                                >
                                    Approve past-debt arrangement
                                </Button>
                            )}
                        </div>
                    </article>
                ))}
            </Panel>
            {selected && (
                <Panel title="Retained financial entries">
                    {entries.length ? (
                        <Table
                            columns={[
                                "Reference / date",
                                "Period",
                                "Description",
                                "Type",
                                "Amount",
                            ]}
                        >
                            {entries.map((entry) => (
                                <tr key={entry.id}>
                                    <td>
                                        {entry.reference}
                                        <small>
                                            {new Date(
                                                entry.created_at,
                                            ).toLocaleDateString("en-PH")}
                                        </small>
                                    </td>
                                    <td>
                                        {entry.period?.name ??
                                            "Opening / previous balance"}
                                    </td>
                                    <td>{entry.description}</td>
                                    <td>
                                        {entry.kind === "charge"
                                            ? "Charge"
                                            : "Payment"}
                                    </td>
                                    <td>{money(entry.amount_cents)}</td>
                                </tr>
                            ))}
                        </Table>
                    ) : (
                        <p>No financial entries recorded.</p>
                    )}
                </Panel>
            )}
            {clearing && (
                <Dialog
                    title={"Financial clearance · " + person(clearing.student)}
                    onClose={() => setClearing(null)}
                >
                    <Errors />
                    <p>
                        {clearing.period.name} · Previous debt{" "}
                        {money(clearing.past_balance_cents)}
                    </p>
                    {clearing.past_balance_cents > 0 &&
                        !clearing.arrangement_valid && (
                            <Alert
                                title="Past debt needs settlement or Finance Approver approval"
                                tone="warning"
                            >
                                Finance Staff can record On Hold while an
                                arrangement is pending.
                            </Alert>
                        )}
                    <SaveForm
                        url={"/finance/enrollments/" + clearing.id + "/clear"}
                        label="Record clearance decision"
                        onSuccess={() => setClearing(null)}
                    >
                        <Field label="Clearance decision">
                            <select
                                name="status"
                                required
                                defaultValue={
                                    clearing.past_balance_cents > 0 &&
                                    !clearing.arrangement_valid
                                        ? "on_hold"
                                        : (clearing.clearance?.status ??
                                          "on_hold")
                                }
                            >
                                <option value="on_hold">On Hold</option>
                                <option
                                    value="cleared"
                                    disabled={
                                        clearing.past_balance_cents > 0 &&
                                        !clearing.arrangement_valid
                                    }
                                >
                                    Cleared
                                </option>
                            </select>
                        </Field>
                        <Field label="Reason / verification notes">
                            <textarea
                                name="reason"
                                required
                                minLength={5}
                                maxLength={2000}
                            />
                        </Field>
                        <p className="small">
                            Cleared confirms the school's current payment
                            conditions were reviewed. It does not erase a debt
                            or replace a required arrangement approval.
                        </p>
                    </SaveForm>
                </Dialog>
            )}
            {arranging && (
                <Dialog
                    title={
                        "Approve payment arrangement · " +
                        person(arranging.student)
                    }
                    onClose={() => setArranging(null)}
                >
                    <Errors />
                    <p>Previous debt: {money(arranging.past_balance_cents)}</p>
                    <SaveForm
                        url={
                            "/finance/enrollments/" +
                            arranging.id +
                            "/arrangement"
                        }
                        label="Approve payment arrangement"
                        onSuccess={() => setArranging(null)}
                    >
                        <Field label="Approval reason">
                            <textarea
                                name="reason"
                                required
                                minLength={5}
                                maxLength={2000}
                            />
                        </Field>
                        <Field label="Approved payment terms">
                            <textarea
                                name="terms"
                                required
                                minLength={5}
                                maxLength={4000}
                                placeholder="Record agreed amounts, due dates and conditions."
                            />
                        </Field>
                        <p className="small">
                            The debt remains recorded. Finance Staff then
                            records Cleared or On Hold for the enrollment.
                        </p>
                    </SaveForm>
                </Dialog>
            )}
            {recording && selected && (
                <Dialog
                    title={"Record charge or payment · " + person(selected)}
                    onClose={() => setRecording(false)}
                >
                    <Errors />
                    <SaveForm
                        url={"/finance/students/" + selected.id + "/entries"}
                        label="Record financial entry"
                        onSuccess={() => setRecording(false)}
                        transform={(data) =>
                            data.set(
                                "amount_cents",
                                String(
                                    Math.round(
                                        Number(data.get("amount")) * 100,
                                    ),
                                ),
                            )
                        }
                    >
                        <input
                            type="hidden"
                            name="branch_id"
                            value={selected.home_branch_id}
                        />
                        <Field label="Type">
                            <select name="kind">
                                <option value="charge">Charge</option>
                                <option value="payment">Payment</option>
                            </select>
                        </Field>
                        <Field
                            label="Period this entry applies to"
                            hint="Use the original period for previous charges/payments. Choose the current period for current-term entries."
                        >
                            <select name="academic_period_id">
                                <option value="">
                                    Opening / previous balance (no period)
                                </option>
                                {options.periods.map((p) => (
                                    <option key={p.id} value={p.id}>
                                        {p.name}
                                    </option>
                                ))}
                            </select>
                        </Field>
                        <Field label="Amount (PHP)">
                            <input
                                name="amount"
                                type="number"
                                min="0.01"
                                max="1000000"
                                step="0.01"
                                required
                            />
                        </Field>
                        <Field label="Description">
                            <input
                                name="description"
                                required
                                maxLength={160}
                            />
                        </Field>
                        <Field label="Unique reference">
                            <input name="reference" required maxLength={100} />
                        </Field>
                        <p className="small">
                            New financial entries require clearance to be
                            reviewed again.
                        </p>
                    </SaveForm>
                </Dialog>
            )}
        </Shell>
    );
}
