import { FilledCard } from "../../components/FilledCard";
import { For, Show, createSignal } from "solid-js";
import { XIcon } from "../../icons/XIcon";
import { allCourses } from "../../utils/allCourses";
import { RegisterBatchCreate } from "../../types/Register";
import { RegistrationPreview } from ".";
import { loadCustomLabels } from "../../utils/allCustomLabels";
import { FileDashedIcon } from "../../icons/FileDashedIcon";


function isoDateToLocalDate(date: string): string {
    const [,month, day] = /\d{4}-(\d{2})-(\d{2})/.exec(date) ?? "";
    return `${day}/${month}`;
}

function wait(ms: number) {
    return new Promise((resolve) => setTimeout(resolve, ms));
}

export function RegisterPreview(props: {selections: Array<RegistrationPreview>, personId: number | null, onDelete: (v: number) => void, onRegister: () => void}) {
    const [loading, setLoading] = createSignal(false);

    const submit = async() => {
        setLoading(true);

        await wait(2000);

        const registers: RegisterBatchCreate = props.selections.map(({courseId, date, customLabel, is_preview}) => ({
            person_id: props.personId!,
            course_id: courseId,
            date,
            custom_label: customLabel,
            is_preview,
        }));

        const result = await createRegisters(registers);

        if (result === null) {
            console.log("Create register: success");
            // Custom labels may have changed, reload them
            loadCustomLabels();
        } else {
            console.log(`error. ${result}`);
        }

        props.onRegister();
        setLoading(false);
    };

    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={props.selections}>
                    {({courseId, date, customLabel, is_preview}) => (
                        <Register
                            courseId={courseId}
                            date={date}
                            onDelete={props.onDelete}
                            customLabel={customLabel}
                            isPreview={is_preview}
                        />
                    )}
                </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"
                    type="button"
                    disabled={props.selections.length === 0 || loading()}
                    onclick={submit}
                >
                    Registrar los {props.selections.length} cursos
                </button>
            </div>
        </FilledCard>
    );
}

function Register(props: {
    courseId: number,
     date: string,
      customLabel: string,
       onDelete: (v: number) => void,
        isPreview: boolean,
    }) {
    const courseName = () => {
        const courses = allCourses();
        return courses.find((course) => course.course_id === props.courseId)?.course_name ?? `Curso invalido! (${props.courseId})`;
    };

    return (
        <div class="grid grid-cols-[auto_3rem_1.5rem] py-1 px-2 rounded-md border border-c-outline my-1">
            <span title={props.isPreview ? "Sin firmas" : ""}>
                <Show when={props.isPreview}>
                    <FileDashedIcon size={16} class="pr-2" fill="var(--c-on-surface)" />
                </Show>
                {courseName()}
            </span>
            <span class="font-mono">
                {isoDateToLocalDate(props.date)}
            </span>
            <button
                class="hover:bg-c-surface-variant rounded-md"
                onclick={() => props.onDelete(props.courseId)}
            >
                <XIcon fill="var(--c-on-surface)" />
            </button>
            <span>
                {props.customLabel}
            </span>
        </div>
    );
}


async function createRegisters(data: RegisterBatchCreate): Promise<null | string> {
    const response = await fetch(`${import.meta.env.VITE_BACKEND_URL}/api/register/batch`, {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify(data),
    });

    if (response.ok) {
        return null;
    } else {
        const data = await response.json();
        return JSON.stringify(data);
    }
}
