import { JSX, Show, createSignal } from "solid-js";
import { SearchableSelect } from "./SearchableSelect";
import { CustomLabelSelect } from "./CustomLabelSelect";
import { courseMap } from "../../utils/allCourses";
import { RegistrationPreview } from ".";

type HTMLEventFn = JSX.EventHandlerUnion<HTMLFormElement, Event & {
    submitter: HTMLElement;
}>;

export function ManualRegistration(props: {
    personId: number | null,
    onAdd: (v: RegistrationPreview) => void
}) {
    // Used to update SearchableSelect.tsx manually
    const [count, setCount] = createSignal(0);
    const [error, setError] = createSignal("");

    const [selectedCourseId, seSelectedCourseId] = createSignal<number | null>(null);
    const [customLabel, setCustomLabel] = createSignal("");
    const [isPreview, setIsPreview] = createSignal(false);

    let datePicker: HTMLInputElement | undefined;

    const courseHasCustomLabel = () => {
        const courseId = selectedCourseId();
        if (courseId === null) {
            return false;
        }

        const course = courseMap()[courseId];
        return course?.course_has_custom_label === true;
    };

    const register: HTMLEventFn = async(ev) => {
        ev.preventDefault();

        const subject = selectedCourseId();

        if (datePicker === undefined) {
            return;
        }

        if (courseHasCustomLabel() && customLabel() === "") {
            setError("Escoge una denominación");

            console.log(error());

            setTimeout(() => setError(""), 5000);
            return;
        }

        const date = datePicker.value;

        if (subject === null) {
            setError("Selecciona un curso");

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

            setTimeout(() => setError(""), 5000);
            return;
        }

        const data: RegistrationPreview = {
            courseId: subject,
            date,
            customLabel: customLabel(),
            is_preview: isPreview(),
        };

        props.onAdd(data);
        // This is used to update & refresh the <SearchableSelect> component
        setCount((x) => x + 1);
        setCustomLabel("");
    };

    return (
        <>
            <form onsubmit={register}>
                <div class="h-52">
                    <SearchableSelect
                        onChange={seSelectedCourseId}
                        count={count()}
                    />
                </div>

                <div class="mt-4 mb-2 grid grid-cols-[9.5rem_auto] gap-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>
                    <Show when={courseHasCustomLabel()}>
                        <div class="relative">
                            <CustomLabelSelect
                                onChange={setCustomLabel}
                                count={count()}
                            />
                            <label for="create-date" class="absolute -top-2 left-2 text-xs bg-c-surface px-1">
                                Denominación
                            </label>
                        </div>
                    </Show>
                </div>
                <div>
                    <input
                        oninput={(ev) => setIsPreview(ev.target.checked)}
                        checked={isPreview()}
                        type="checkbox"
                        name="is_preview"
                        id="manual-is-preview"
                    />
                    <label class="px-2 py-2 select-none" for="manual-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="submit"
                        value="Agregar"
                        disabled={props.personId === null}
                    />

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