import { For, Show, createEffect, createMemo, createSignal } from "solid-js";
import { Person } from "../../types/Person";
import { Register } from "../../types/Register";
import { RegisterSidebar } from "./RegisterSidebar";
import { DownloadSimpleIcon } from "../../icons/DownloadSimpleIcon";
import { backend, wait } from "../../utils/functions";
import { JsonResult } from "../../types/JsonResult";
import { LoadingIcon } from "../../icons/LoadingIcon";
import { RegisterElement, generateCert } from "./RegisterElement";

export function Registers(props: {person: Person | null, count: number}) {
    const [registers, setRegisters] = createSignal<Array<Register>>([]);
    const [showHidden, setShowHidden] = createSignal(false);
    const [sidebarRegister, setSidebarRegister] = createSignal<Register | null>(null);
    const [loading, setLoading] = createSignal(false);
    const [error, setError] = createSignal("");

    const loadRegisters = async() => {
        setLoading(true);
        setError("");

        const person = props.person!;
        setRegisters([]);

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

        backend.get<JsonResult<Array<Register>>>(`/api/register/${person.person_dni}`)
            .then((response) => {
                if (response.status === 200) {
                    setRegisters(response.data.Ok);
                } else {
                    console.error(response.data.Error);
                    setError(response.data.Error.reason);
                }
            })
            .catch((err) => {
                console.error(err);
                setError(`Error fatal: ${err.message}`);
            })
            .finally(() => setLoading(false));
    };

    createEffect(async() => {
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        const _count = props.count;

        if (props.person === null) {
            setRegisters([]);
            return;
        }

        loadRegisters();
    });

    // All registers sorted by year, and an indicator of whether there's register older
    // than last year
    const registerSortedList = createMemo<[Array<Array<Register>>, boolean]>(() => {
        const allRegisters = registers();

        const registerByYear: {[y: string]: Array<Register>} = {};

        let olderThanLastYear = false;
        allRegisters.forEach((register) => {
            const year = new Date(register.register_display_date).getFullYear();
            const currentYear = new Date().getFullYear();

            // Don't show registers from before last year
            if (year < (currentYear - 1)) {
                olderThanLastYear = true;
                if (!showHidden()) {
                    return;
                }
            }

            if (registerByYear[year] === undefined) {
                registerByYear[year] = [];
            }

            registerByYear[year].push(register);
        });

        // Create a new array with each year's registers
        // Sort the object keys (years) in descending order
        const sortedYears = Object.keys(registerByYear).sort((y1, y2) => (y1 < y2 ? 1 : -1));

        // Create the final array
        const result = sortedYears.map((year) => registerByYear[year].sort((r1, r2) => (r1.register_display_date < r2.register_display_date ? 1 : -1)));

        return [result, olderThanLastYear];
    });

    const inputCheck = () => setShowHidden((x) => !x);

    const todayRegisters = createMemo(() => {
        const today = new Date().toISOString()
            .split("T")[0];
        return registerSortedList()[0][0]
            ?.filter((r) => r.register_creation_date === today) ?? [];
    });


    const [downButtonBg, setDownButtonBg] = createSignal("bg-c-primary text-c-on-primary");
    const downloadTodayCerts = () => {
        if (props.person === null) return;

        todayRegisters().forEach((register) => {
            generateCert(props.person!, register);
        });

        setDownButtonBg("bg-c-success text-c-on-success");

        setTimeout(() => {
            setDownButtonBg("bg-c-primary text-c-on-primary");
        }, 1000);
    };


    return (
        <div class="m-4 p-4 rounded-md relative">
            <h3 class="text-xl font-medium">
                <button
                    class={`${downButtonBg()} inline-block mr-2 rounded-full transition-colors
                        disabled:opacity-25 disabled:cursor-not-allowed px-2`}
                    disabled={todayRegisters().length === 0}
                    title="Descargar todos los cert. creados hoy"
                    onclick={downloadTodayCerts}
                >
                    <DownloadSimpleIcon fill="var(--c-on-primary)" size={24} />
                    <span class="text-sm">
                        &nbsp;hoy
                    </span>
                </button>
                {props.person?.person_names}&nbsp;
                {props.person?.person_paternal_surname}&nbsp;
                {props.person?.person_maternal_surname}

                <Show when={registerSortedList()[1]}>
                    &nbsp;&nbsp;&nbsp;|
                    <input id={`person_${props.person?.person_id ?? "_"}`} type="checkbox" class="ml-4 mr-2" checked oninput={inputCheck} />
                    <label for={`person_${props.person?.person_id ?? "_"}`} class="text-sm">
                        Ocultar cert. anteriores a {new Date().getFullYear() - 1}
                    </label>
                </Show>
            </h3>

            <For each={registerSortedList()[0]}>
                {(year) => (
                    <div class="flex flex-wrap justify-start gap-2 my-6">
                        <For each={year}>
                            {(register) => (
                                <RegisterElement
                                    register={register}
                                    person={props.person!}
                                    onClick={() => setSidebarRegister(register)}
                                />
                            )}
                        </For>
                    </div>
                )}
            </For>

            <Show when={loading()}>
                <div class="text-center">
                    <LoadingIcon class="animate-spin" fill="var(--c-on-surface)" />
                </div>
            </Show>

            <Show when={error() !== ""}>
                <p>Error: {error()}</p>
            </Show>

            <Show when={sidebarRegister() !== null}>
                <RegisterSidebar
                    register={sidebarRegister()!}
                    close={() => setSidebarRegister(null)}
                    onDelete={loadRegisters}
                    person={props.person!}
                />
            </Show>
        </div>
    );
}
