import { Show, createMemo } from "solid-js";
import { ScanResult } from ".";
import { FilledButton } from "../components/FilledButton";
import { FilledCard } from "../components/FilledCard";
import { LoadingIcon } from "../icons/LoadingIcon";
import { PDFIcon } from "../icons/PDFIcon";
import { LoadingStatus, useLoading } from "../utils/functions";
import { QuestionIcon } from "../icons/QuestionIcon";

export function ScansList(props: {scanData: Array<ScanResult> | null, onSuccess: () => void}) {
    const {status, setStatus, error, setError} = useLoading();

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

    const empty = createMemo(() => props.scanData?.length === 0);

    const entriesCount = createMemo(() => {
        if (props.scanData === null) return [0, 0];

        let fullCount = 0;
        let partialCount = 0;
        let emptyCount = 0;

        for (const entry of props.scanData) {
            if ("Full" in entry) {
                fullCount += 1;
            } else if ("Partial" in entry) {
                partialCount += 1;
            } else if ("Empty" in entry) {
                emptyCount += 1;
            }
        }

        return [fullCount, partialCount, emptyCount];
    });

    const erroredEntries = createMemo(() => (props.scanData?.filter((entry) => "Error" in entry) ?? []) as Array<{Error: string}>);

    const convertScans = () => {
        setStatus(LoadingStatus.Loading);

        if (props.scanData === null) {
            setError("No se detectaron escaneos");
            setStatus(LoadingStatus.Error);
            return;
        }

        fetch(
            `${import.meta.env.VITE_BACKEND_URL}/api/scans/convert`,
            {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify(props.scanData),
            },
        )
            .then((res) => res.json())
            .then(() => {
                setStatus(LoadingStatus.Ok);
                props.onSuccess();
            })
            .catch((err) => {
                setStatus(LoadingStatus.Error);
                console.error(err);
            });
    };

    return (
        <>
            <Show when={props.scanData !== null}>
                <FilledCard class="border border-c-outline overflow-hidden">
                    <h1 class="p-3 font-medium text-xl">
                        Escaneos detectados
                    </h1>

                    <div class="bg-c-surface py-2">
                        <Show when={empty()}>
                            <div class="px-4 pb-2">
                                <div class="text-center pt-6 pb-4">
                                    <QuestionIcon class="scale-[200%]" fill="var(--c-outline)" />
                                </div>
                                <p>No se encontraron archivos que cumplan con los parámetros.</p>
                            </div>
                        </Show>

                        <Show when={!empty()}>
                            <div class="px-4">
                            Se detectaron:
                                <br />
                                <p>
                                    - <span class="font-mono">{entriesCount()[0]}</span> archivos
                                    con QR (nombres y curso)
                                </p>
                                <p>
                                    - <span class="font-mono">{entriesCount()[1]}</span> archivos
                                    con QR (solo nombres)
                                </p>
                                <p>
                                    - <span class="font-mono">{entriesCount()[2]}</span> archivos sin QR
                                </p>
                            </div>

                            <Show when={erroredEntries().length > 0}>
                                <div class="px-4 pt-2">
                                    <p class="font-medium">
                                        Errores:
                                    </p>
                                    <ul class="list-disc list-inside">
                                        {erroredEntries().map((entry) => (
                                            <li>
                                                {entry.Error}
                                            </li>
                                        ))}
                                    </ul>
                                </div>
                            </Show>
                        </Show>
                    </div>

                    <p class="px-4 pt-4">
                        El sig. botón:
                        <br />
                        - Convierte los escaneos con QR por completo (1), (2), (3) y (4).
                        <br />
                        - Convierte los escaneos sin QR solo en (1), (2) y (3). Se debe realizar
                        (4) manualmente.
                    </p>

                    <div class="relative mx-4 mb-4">
                        <FilledButton
                            onClick={convertScans}
                            disabled={loading() || empty()}
                        >
                            <span
                                class="absolute top-[1.35rem] left-2"
                                style={{display: loading() ? "none" : "inline-block"}}
                            >
                                <PDFIcon
                                    fill="var(--c-on-primary)"
                                />
                            </span>
                            <span
                                class="absolute top-[1.35rem] left-2"
                                style={{display: loading() ? "inline-block" : "none"}}
                            >
                                <LoadingIcon
                                    class="animate-spin"
                                    fill="var(--c-primary-container)"
                                />
                            </span>

                            <span class="ml-5">
                                Convertir escaneos
                            </span>
                        </FilledButton>
                    </div>

                    <Show when={status() === LoadingStatus.Error}>
                        <div class="px-4 pb-4">
                            <p class="font-medium">
                                Error convirtiendo PDFs: {error()}
                            </p>
                        </div>
                    </Show>
                </FilledCard>
            </Show>
        </>
    );
}

