import { For, createMemo } from "solid-js";
import { FilledCard } from "../components/FilledCard";
import { LoadingIcon } from "../icons/LoadingIcon";
import { LoadingStatus, backend, useLoading, wait } from "../utils/functions";
import { ClassroomCourseValue, allClassrooomCourses } from "../types/ClassroomCourse";
import { XIcon } from "../icons/XIcon";
import { JsonResult } from "../types/JsonResult";
import { AxiosError } from "axios";

export function ClassroomRegistrationPreview(props: {
    surname_first_letter: string,
    userId: number | null,
    selections: Set<ClassroomCourseValue>,
    deleteRegister: (k: string) => void,
    onSuccess: () => void,
}) {
    const {status, setStatus, setError} = useLoading();

    const loading = createMemo(() => status() === LoadingStatus.Loading);

    const submit = async() => {
        if (props.userId === null) return;

        setStatus(LoadingStatus.Loading);

        if (import.meta.env.DEV) await wait(1500);

        backend.post<JsonResult<null>>(`/api/classroom/course/${props.userId}`, {
            surname_first_letter: "A",
            courses: [...props.selections.values()],
        })
            .then((response) => {
                if (response.status === 200) {
                    setStatus(LoadingStatus.Ok);
                    props.onSuccess();
                } else {
                    console.error(response.data);
                    setError(response.data.Error.reason);
                    setStatus(LoadingStatus.Error);
                }
            })
            .catch((err: AxiosError<JsonResult<null>>) => {
                console.error(err);
                if (err.response?.data?.Error?.reason) {
                    setError(err.response.data.Error.reason);
                }

                setStatus(LoadingStatus.Error);
            });
    };

    const selections = createMemo(() => [...props.selections]);

    return (
        <FilledCard class="border border-c-outline overflow-hidden">
            <h2 class="p-4 font-bold text-xl">Confirmar registro</h2>
            <div class="bg-c-surface p-4">
                <For each={selections()}>
                    {(course_key) => (
                        <div class="grid grid-cols-[auto_1.5rem] py-1 px-2 rounded-md border border-c-outline my-1">
                            <span class="font-mono">
                                {allClassrooomCourses[course_key]}
                            </span>
                            <button
                                class="hover:bg-c-surface-variant rounded-md"
                                onclick={() => props.deleteRegister(course_key)}
                            >
                                <XIcon fill="var(--c-on-surface)" />
                            </button>
                        </div>
                    )}
                </For>

                <button
                    class="bg-c-primary text-c-on-primary px-4 py-2 rounded-full cursor-pointer mt-4
                            disabled:opacity-50 disabled:cursor-not-allowed relative"
                    type="button"
                    disabled={props.userId === null || selections().length === 0 || loading()}
                    onclick={submit}
                >
                    <span
                        class="absolute top-1 left-2"
                        style={{display: loading() ? "inline-block" : "none"}}
                    >
                        <LoadingIcon
                            class="animate-spin"
                            fill="var(--c-primary-container)"
                        />
                    </span>
                    <span class="ml-6">
                        Matricular en {selections().length} cursos
                    </span>
                </button>
            </div>
        </FilledCard>
    );
}
