import { Accessor, For, createSignal } from "solid-js";
import { Chip } from "../../components/Chip";
import { getCourseMemo } from "../../utils/allCourses";
import { Course } from "../../types/Course";
import { RegistrationPreview } from ".";

type PresetName = "None" | "2 Matpel" | "3 Matpel" | "4 Escolta" | "MD, 2 Matpel" | "3 4x4" | "2 4x4";

function genPresets(): {[k: string]: Array<Accessor<Course | null>>} {
    return {
        "2 Matpel": [
            getCourseMemo("Matpel 2"),
            getCourseMemo("Matpel 1"),
        ],
        "3 Matpel": [
            getCourseMemo("Matpel 3"),
            getCourseMemo("Matpel 2"),
            getCourseMemo("Matpel 1"),
        ],
        "4 Escolta": [
            getCourseMemo("Sup. Escolta"),
            getCourseMemo("Matpel 3"),
            getCourseMemo("Matpel 2"),
            getCourseMemo("Matpel 1"),
        ],
        "MD, 2 Matpel": [
            getCourseMemo("Matpel 2"),
            getCourseMemo("Matpel 1"),
            getCourseMemo("Manejo Defensivo"),
        ],
        "3 4x4": [
            getCourseMemo("4x4"),
            getCourseMemo("Mecanica Basica"),
            getCourseMemo("Manejo Defensivo"),
        ],
        "2 4x4": [
            getCourseMemo("4x4"),
            getCourseMemo("Manejo Defensivo"),
        ],
    };
}

export function RegisterPresets(props: {
    disableCreation: boolean,
    onAdd: (v: RegistrationPreview) => void
}) {
    let datePicker: HTMLInputElement | undefined;
    const [selectedPreset, setSelectedPreset] = createSignal<PresetName>("None");
    const [isPreview, setIsPreview] = createSignal(false);
    const [error, setError] = createSignal("");
    const presets = genPresets();

    const add = () => {
        if (datePicker === undefined) {
            return;
        }
        const date = datePicker.value;
        const preset = selectedPreset();

        if (date === "") {
            setError("Selecciona una fecha");
            setTimeout(() => setError(""), 5000);
            return;
        }
        if (preset === "None") {
            setError("Selecciona un preset");
            setTimeout(() => setError(""), 5000);
            return;
        }

        const presetIds = presets[preset];
        const currentDate = new Date(date);
        for (const courseMemo of presetIds) {
            // Get course and course duration from the memo
            const course = courseMemo();
            if (course === null) {
                setError(`Un curso no existe. Error fatal. (${preset})`);
                return;
            }

            const courseId = course.course_id;
            const courseDuration = course.course_days_amount;
            const dateYYYYMMDD = currentDate.toISOString().split("T")[0];

            // Add
            props.onAdd({
                courseId,
                date: dateYYYYMMDD,
                customLabel: "",
                is_preview: isPreview(),
            });

            // Substract current date for the next course
            currentDate.setDate(currentDate.getDate() - courseDuration);
        }

        setSelectedPreset("None");
    };

    return (
        <>
            <div class="h-52">
                <p>Las fechas se colocan automáticamente según la duración del curso y su jeraquía.</p>
                <br />
                <div class="flex flex-wrap gap-2">
                    <For each={Object.keys(presets)}>
                        {(key) => (
                            <Chip
                                selected={selectedPreset() === key}
                                select={() => setSelectedPreset(key as PresetName)}
                                text={key}
                            />
                        )}
                    </For>
                </div>
            </div>
            <div class="mt-4 mb-2">
                <div class="relative">
                    <input
                        ref={datePicker}
                        id="create-date"
                        class="bg-c-surface text-c-on-surface border border-c-outline rounded-lg p-2 font-mono"
                        type="date"
                    />
                    <label for="create-date" class="absolute -top-2 left-2 text-xs bg-c-surface px-1">Fecha</label>
                </div>
            </div>
            <div>
                <input
                    oninput={(ev) => setIsPreview(ev.target.checked)}
                    checked={isPreview()}
                    type="checkbox"
                    name="is_preview"
                    id="preset-is-preview"
                />
                <label class="px-2 py-2 select-none" for="preset-is-preview">Cert sin firmas</label>
            </div>
            <div>
                <input
                    class="bg-c-primary text-c-on-primary px-4 py-2 rounded-full cursor-pointer
                                        disabled:opacity-50 disabled:cursor-not-allowed"
                    type="button"
                    value="Agregar"
                    onclick={add}
                    disabled={props.disableCreation}
                />

                <p
                    class="my-2 p-1 w-fit mx-4 text-c-error inline-block"
                >
                    {error()}&nbsp;
                </p>
            </div>
        </>
    );
}
