import saveAs from "file-saver";
import { Register } from "../../types/Register";
import { courseMap } from "../../utils/allCourses";
import { genCarnet } from "../../utils/carnetGenerator";
import { formatDate, numberToMonth } from "../../utils/functions";
import { Canvg } from "canvg";
import { Show } from "solid-js";
import { Person } from "../../types/Person";
import QR from "qrcode";

export function RegisterSidebar(props: {
    register: Register,
    person: Person,
    close: () => void,
    onDelete: () => void,
}) {
    const deleteRegister = async() => {

        const res = await fetch(`${import.meta.env.VITE_BACKEND_URL}/api/register/${props.register.register_id}`,{
            method: "DELETE",
        });

        if (res.ok) {
            props.onDelete();
            props.close();
        }
    };

    const courseName = () => courseMap()[props.register.register_course_id]?.course_name ?? "<curso no encontrado>";

    const generateCarnet = () => {
        const canvas = document.createElement("canvas");
        const ctx = canvas.getContext("2d") as CanvasRenderingContext2D;

        const p = props.person;
        const r = props.register;

        const [expiryYear, month] = r.register_display_date.split("-");

        const expiryMonth = numberToMonth(parseInt(month, 10));

        if (expiryMonth === null) {
            alert(`El cert. tiene un mes invalido (${month}), no se puede generar carnet`);
            return;
        }

        // QR code
        QR.toDataURL(`https://eegsac.com/certificado/${p.person_dni}`, {margin: 1}, (err, base64) => {
            if (err) {
                alert("Error creando codigo QR para el carnet.");
                console.error("Error creating QR code");
                console.error(err);
                return;
            }

            const fullname = `${p.person_names} ${p.person_paternal_surname} ${p.person_maternal_surname}`;
            const svgHtml = genCarnet({
                fullname,
                dni: p.person_dni.toString(),
                code: r.register_code.toString().padStart(4, "0"),
                expiryMonth,
                expiryYear,
                qrBase64: base64,
            });
            const v = Canvg.fromString(ctx, svgHtml);
            v.start();
            v.ready().then(() => {
                canvas.toBlob((blob) => {
                    if (blob !== null) {
                        saveAs(blob, `CARNET MATPEL - ${fullname}.png`);
                    } else {
                        console.log("blob is null... :c");
                    }
                });
            });
        });
    };

    return (
        <div class="absolute top-0 bg-c-surface-variant right-0
                    py-4 px-6 w-[20rem]
                    shadow-md rounded-lg"
        >
            <p class="text-xl mb-8">Detalles del certificado</p>

            <p class="underline text-lg">Curso</p>
            <p class="mb-4">{courseName()}</p>

            <p class="underline text-lg">Código del certificado</p>
            <p class="mb-4">{props.register.register_code}</p>

            <p class="underline text-lg">Fecha de creación</p>
            <p class="mb-4">{formatDate(props.register.register_creation_date)}</p>

            <p class="underline text-lg">Fecha del certificado</p>
            <p class="mb-4">{formatDate(props.register.register_display_date)}</p>

            <p class="underline text-lg">Denominacion</p>
            <p class="mb-4">{props.register.register_custom_label}</p>

            <p class="underline text-lg">¿Es cert. sin firmas?</p>
            <p class="mb-8">{props.register.register_is_preview ? "Si" : "No"}</p>

            {/* 12 is the ID for Matpel 3 in the DB */}
            <Show when={props.register.register_course_id === 12}>
                <button
                    class="bg-c-primary text-c-on-primary px-4 py-2 rounded-full cursor-pointer
                        disabled:opacity-50 disabled:cursor-not-allowed"
                    onclick={generateCarnet}
                >
                Generar carnet
                </button>
            </Show>
            <button
                class="bg-c-error text-c-on-error px-4 py-2 rounded-full cursor-pointer
                        disabled:opacity-50 disabled:cursor-not-allowed"
                onclick={deleteRegister}
            >
                Eliminar cert.
            </button>
            <button
                class="ml-2 border border-c-outline bg-c-surface text-c-primary
                        px-4 py-2 rounded-full cursor-pointer
                        disabled:opacity-50 disabled:cursor-not-allowed"
                onclick={props.close}
            >
                Volver
            </button>
        </div>
    );
}
