import { useEffect, useState } from "react";
import { Button, Field, Panel, SaveForm, Table } from "./ui";
import type { Options, Program, Requirement, UnitType } from "../types";

export function CourseStages({
    program,
    level = "college",
}: {
    program?: Program;
    level?: string;
}) {
    return (
        <div className="form-grid" key={level}>
            <Field label="Number of years">
                <input
                    name="duration_years"
                    type="number"
                    required
                    min={1}
                    max={12}
                    defaultValue={
                        program?.duration_years ??
                        (level === "senior_high" ? 2 : 4)
                    }
                />
            </Field>
            <Field label="Semesters per year">
                <select
                    name="semesters_per_year"
                    defaultValue={
                        program?.semesters_per_year ??
                        (level === "college" ? 2 : 1)
                    }
                >
                    <option value="1">1 · Annual / one semester</option>
                    <option value="2">2 semesters</option>
                </select>
            </Field>
            <Field label="Starting Year / Grade">
                <input
                    name="start_year"
                    type="number"
                    required
                    min={1}
                    max={12}
                    defaultValue={
                        program?.start_year ??
                        (level === "junior_high"
                            ? 7
                            : level === "senior_high"
                              ? 11
                              : 1)
                    }
                />
            </Field>
        </div>
    );
}

export function CurriculumChoice({
    options,
    initial,
}: {
    options: Options;
    initial?: number | null;
}) {
    return (
        <Field label="Global Curriculum">
            <select
                name="curriculum_template_id"
                defaultValue={initial ?? ""}
                required
            >
                <option value="">Choose Curriculum</option>
                {options.curriculum_templates?.map((c) => (
                    <option value={c.id} key={c.id}>
                        {c.name}
                    </option>
                ))}
            </select>
        </Field>
    );
}

export function UnitAllocation({
    types,
    credits,
    requirement,
}: {
    types: UnitType[];
    credits: string;
    requirement?: Requirement;
}) {
    const lecture = types.find((t) => t.name === "Lecture") ?? types[0];
    const initial = () =>
        requirement?.unitLines?.map((l) => ({
            unit_type_id: l.unit_type_id,
            credits: l.credits,
        })) ?? (lecture ? [{ unit_type_id: lecture.id, credits }] : []);
    const [lines, setLines] = useState(initial);
    useEffect(() => {
        setLines(initial());
    }, [credits, requirement?.id]);
    return (
        <fieldset>
            <legend>Lecture / Laboratory credits</legend>
            <p className="small">
                Select the Unit Types used by this subject. Their credits must
                total {credits} academic credits.
            </p>
            <input
                type="hidden"
                name="unit_lines"
                value={JSON.stringify(lines)}
            />
            {lines.map((l, i) => (
                <div className="form-grid" key={i}>
                    <Field label={`Unit Type ${i + 1}`}>
                        <select
                            required
                            value={l.unit_type_id}
                            onChange={(e) =>
                                setLines(
                                    lines.map((r, n) =>
                                        n === i
                                            ? {
                                                  ...r,
                                                  unit_type_id: Number(
                                                      e.target.value,
                                                  ),
                                              }
                                            : r,
                                    ),
                                )
                            }
                        >
                            {types.map((t) => (
                                <option
                                    key={t.id}
                                    value={t.id}
                                    disabled={lines.some(
                                        (r, n) =>
                                            n !== i && r.unit_type_id === t.id,
                                    )}
                                >
                                    {t.name} · ₱{t.price}{" "}
                                    {t.pricing_mode === "fixed"
                                        ? "fixed"
                                        : "per credit"}
                                </option>
                            ))}
                        </select>
                    </Field>
                    <Field label={`Credits ${i + 1}`}>
                        <input
                            type="number"
                            required
                            min="0.01"
                            max="30"
                            step="0.01"
                            value={l.credits}
                            onChange={(e) =>
                                setLines(
                                    lines.map((r, n) =>
                                        n === i
                                            ? { ...r, credits: e.target.value }
                                            : r,
                                    ),
                                )
                            }
                        />
                    </Field>
                    {lines.length > 1 && (
                        <Button
                            type="button"
                            variant="ghost"
                            onClick={() =>
                                setLines(lines.filter((_, n) => n !== i))
                            }
                        >
                            Remove Unit Type
                        </Button>
                    )}
                </div>
            ))}
            <Button
                type="button"
                variant="secondary"
                disabled={lines.length >= types.length}
                onClick={() => {
                    const next = types.find(
                        (t) => !lines.some((l) => l.unit_type_id === t.id),
                    );
                    if (next)
                        setLines([
                            ...lines,
                            { unit_type_id: next.id, credits: "1" },
                        ]);
                }}
            >
                Add Unit Type
            </Button>
        </fieldset>
    );
}

export function CurriculumCatalog({ options }: { options: Options }) {
    return (
        <>
            <Panel title="Global Curricula">
                <p>
                    Choose a global Curriculum for each Course, then build that
                    Course’s own subject plan by Year and semester.
                </p>
                <Table columns={["Curriculum", "Description"]}>
                    {options.curriculum_templates?.map((c) => (
                        <tr key={c.id}>
                            <td>{c.name}</td>
                            <td>{c.description ?? "—"}</td>
                        </tr>
                    ))}
                </Table>
                {options.global_setup && (
                    <details className="accordion">
                        <summary>Add global Curriculum</summary>
                        <div>
                            <SaveForm
                                url="/academic/setup"
                                label="Add Curriculum"
                            >
                                <input
                                    type="hidden"
                                    name="operation"
                                    value="curriculum_template"
                                />
                                <Field label="Curriculum name">
                                    <input
                                        name="name"
                                        required
                                        maxLength={160}
                                    />
                                </Field>
                                <Field label="Description">
                                    <textarea
                                        name="description"
                                        maxLength={4000}
                                    />
                                </Field>
                            </SaveForm>
                        </div>
                    </details>
                )}
            </Panel>
            <Panel title="Unit Types">
                <p>
                    Lecture and Laboratory are Unit Types. Allocate them to
                    subjects within a Course plan. Per-credit rates multiply the
                    allocated credits; a fixed rate applies once to that
                    subject’s selected Unit Type.
                </p>
                <Table columns={["Unit Type", "Pricing", "Price (PHP)"]}>
                    {options.unit_types?.map((t) => (
                        <tr key={t.id}>
                            <td>{t.name}</td>
                            <td>
                                {t.pricing_mode === "fixed"
                                    ? "Fixed per subject"
                                    : "Per credit"}
                            </td>
                            <td>{t.price}</td>
                        </tr>
                    ))}
                </Table>
                {options.global_setup &&
                    [...(options.unit_types ?? []), null].map((t) => (
                        <details key={t?.id ?? "new"} className="accordion">
                            <summary>
                                {t ? `Configure ${t.name}` : "Add Unit Type"}
                            </summary>
                            <div>
                                <SaveForm
                                    url="/academic/setup"
                                    label="Save Unit Type"
                                    reset={false}
                                >
                                    <input
                                        type="hidden"
                                        name="operation"
                                        value="unit_type"
                                    />
                                    {t && (
                                        <input
                                            type="hidden"
                                            name="unit_type_id"
                                            value={t.id}
                                        />
                                    )}
                                    <Field label="Unit Type name">
                                        <input
                                            name="name"
                                            required
                                            maxLength={100}
                                            defaultValue={t?.name}
                                        />
                                    </Field>
                                    <Field label="Pricing method">
                                        <select
                                            name="pricing_mode"
                                            defaultValue={
                                                t?.pricing_mode ?? "per_credit"
                                            }
                                        >
                                            <option value="per_credit">
                                                Per credit
                                            </option>
                                            <option value="fixed">
                                                Fixed per subject
                                            </option>
                                        </select>
                                    </Field>
                                    <Field label="Price (PHP)">
                                        <input
                                            name="price"
                                            required
                                            type="number"
                                            min="0"
                                            max="1000000"
                                            step="0.01"
                                            defaultValue={t?.price ?? "0.00"}
                                        />
                                    </Field>
                                    <p className="small">
                                        Price changes apply to newly prepared
                                        assessments. Saved Pre-COR assessments
                                        and issued CORs retain their history.
                                    </p>
                                </SaveForm>
                            </div>
                        </details>
                    ))}
            </Panel>
        </>
    );
}

export function BranchCalendars({
    options,
    levels,
}: {
    options: Options;
    levels: Record<string, string>;
}) {
    const [branch, setBranch] = useState(String(options.branches[0]?.id ?? "")),
        [level, setLevel] = useState("college"),
        [kind, setKind] = useState("semester"),
        [ids, setIds] = useState<number[]>([]);
    useEffect(() => {
        setKind(
            options.branch_settings?.find(
                (s) => s.branch_id === Number(branch) && s.level === level,
            )?.enrollment_kind ?? (level === "college" ? "semester" : "year"),
        );
        setIds(
            options.branch_periods
                ?.filter(
                    (p) => p.branch_id === Number(branch) && p.level === level,
                )
                .map((p) => p.academic_period_id) ?? [],
        );
    }, [branch, level, options.branch_settings, options.branch_periods]);
    return (
        <Panel title="Branch enrollment calendars">
            <p>
                Enable School Years and semesters for each Branch and school
                level before opening enrollment.
            </p>
            <SaveForm
                url="/academic/setup"
                label="Save Branch calendar"
                reset={false}
            >
                <input type="hidden" name="operation" value="branch_calendar" />
                <input
                    type="hidden"
                    name="period_ids"
                    value={JSON.stringify(ids)}
                />
                <div className="form-grid">
                    <Field label="Branch">
                        <select
                            name="branch_id"
                            value={branch}
                            onChange={(e) => setBranch(e.target.value)}
                            required
                        >
                            {options.branches.map((b) => (
                                <option key={b.id} value={b.id}>
                                    {b.name}
                                </option>
                            ))}
                        </select>
                    </Field>
                    <Field label="School level">
                        <select
                            name="level"
                            value={level}
                            onChange={(e) => setLevel(e.target.value)}
                        >
                            {Object.entries(levels).map(([k, v]) => (
                                <option key={k} value={k}>
                                    {v}
                                </option>
                            ))}
                        </select>
                    </Field>
                    <Field label="Enrollment cycle">
                        <select
                            name="enrollment_kind"
                            value={kind}
                            onChange={(e) => {
                                setKind(e.target.value);
                                setIds([]);
                            }}
                        >
                            <option value="year">Yearly</option>
                            <option value="semester">Semester-based</option>
                        </select>
                    </Field>
                </div>
                <fieldset>
                    <legend>Available School Years / semesters</legend>
                    {options.periods
                        .filter((p) => p.kind === kind)
                        .map((p) => (
                            <label className="checkbox" key={p.id}>
                                <input
                                    type="checkbox"
                                    checked={ids.includes(p.id)}
                                    onChange={(e) =>
                                        setIds(
                                            e.target.checked
                                                ? [...ids, p.id]
                                                : ids.filter(
                                                      (id) => id !== p.id,
                                                  ),
                                        )
                                    }
                                />
                                {p.school_year} · {p.name}
                            </label>
                        ))}
                </fieldset>
            </SaveForm>
        </Panel>
    );
}
