import { Show } from "solid-js";
import { certGenerator } from "../../certGenerator";
import { Person } from "../../types/Person";
import { Register } from "../../types/Register";
import { courseMap } from "../../utils/allCourses";
import { customLabelsMap } from "../../utils/allCustomLabels";
import { DownloadSimpleIcon } from "../../icons/DownloadSimpleIcon";
import { CaretRight } from "../../icons/CaretRight";

export function RegisterElement(props: {register: Register, person: Person, onClick: () => void}) {

    const dateComponents = () => {
        const [, year, month, day] = /(\d{4})-(\d{2})-(\d{2})/.exec(props.register.register_display_date) ?? [];
        return {year, month, day};
    };

    const displayDate = () => {
        const {year, month, day} = dateComponents();
        return `${day}/${month}/${year}`;
    };

    const courseName = () => {
        const course = courseMap()[props.register.register_course_id];
        return course?.course_name ?? "Curso no encontrado";
    };

    const customLabel = () => {
        const labelId = props.register.register_custom_label;
        if (labelId === 1) return "";
        return customLabelsMap()[labelId]?.custom_label_value ?? "";
    };

    const genCert = () => {
        const person = props.person;
        const register = props.register;

        generateCert(person, register);
    };

    const generateable = () => {
        const courseN = courseName();
        return certGenerator[courseN] !== undefined;
    };

    const createdTodayClasses = () => {
        // current dat in YYYY-MM-DD format
        const today = new Date().toISOString()
            .split("T")[0];
        const createdToday = props.register.register_creation_date === today;

        return createdToday ? "bg-c-surface-variant" : "";
    };

    return (
        <div class="grid grid-cols-[11rem_1.5rem_1.25rem] border border-c-outline rounded-md overflow-hidden">
            <div class="border-r border-c-outline-50 align-middle">
                <p
                    class="font-bold overflow-hidden whitespace-nowrap pt-1 px-1"
                    title={`${courseName()} ${customLabel()}`}
                >
                    {courseName()}
                </p>
                <p class="font-mono text-sm px-1">
                    <span class="underline">
                        {customLabel()}
                    </span>
                    &nbsp;
                </p>
                <p class={`text-sm px-1 pb-1 ${createdTodayClasses()}`}>
                    <span class="font-mono">
                        {displayDate()}
                    </span>

                    <Show when={props.register.register_is_preview}>
                        <span class="text-c-error font-bold select-none">
                            &nbsp;sin firmas
                        </span>
                    </Show>
                    <Show when={!props.register.register_is_preview}>
                        <span class="font-mono">
                            &nbsp;-&nbsp;
                        </span>
                        <span
                            class="font-mono underline cursor-pointer hover:text-c-primary"
                            onClick={() => {
                                const code = props.register.register_code.toString();
                                const paddedCode = code.padStart(4, "0");
                                navigator.clipboard.writeText(paddedCode);
                            }}
                        >
                            {props.register.register_code}
                        </span>
                    </Show>
                </p>
            </div>
            <button
                class="hover:bg-c-primary-container rounded-md transition-colors
                        disabled:opacity-0 disabled:cursor-default
                        disabled:hover:bg-c-transparent"
                title="Descargar DOCX"
                onclick={genCert}
                disabled={!generateable()}
            >
                <DownloadSimpleIcon fill="var(--c-on-primary-container)" size={20} />
            </button>
            <button
                class="hover:bg-c-surface-variant rounded-md transition-colors"
                title="Más opciones"
                onclick={props.onClick}
            >
                <CaretRight fill="var(--c-primary)" size={20} />
            </button>
        </div>
    );
}

export function generateCert(person: Person, register: Register) {
    const courseN = courseMap()[register.register_course_id]?.course_name ?? "Curso no encontrado";

    const generator = certGenerator[courseN];
    if (generator === undefined) {
        alert(`El cert \`${courseN}\` no está implementado`);
        return;
    }

    const [, year, month, day] = /(\d{4})-(\d{2})-(\d{2})/.exec(register.register_display_date) ?? [];
    const personFullName = `${person.person_names} ${person.person_paternal_surname} ${person.person_maternal_surname}`;

    // Manage custom label
    const certCustomLabel = register.register_custom_label === 1
        ? ""
        : customLabelsMap()[register.register_custom_label]?.custom_label_value ?? "";

    const certCode = register.register_is_preview ? "0000" : register.register_code.toString().padStart(4, "0");

    generator(`${courseN} - ${personFullName} [${register.register_id.toString(16).toUpperCase()}].docx`, {
        matpel: null,
        personFullName,
        personDni: person.person_dni.toString(),
        certCode,
        certYear: year,
        certMonth: month,
        certDay: day,
        // THIS WAS PREVIOUSLY THE SAME AS certCode. All QR codes generated before this
        // was fixed are useless
        certIId: register.register_id,
        certCustomLabel,
    });
}

