import { For, Show, createMemo } from "solid-js";
import { ScanData, 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: ScanData | null}) {
    const {status, setStatus, error, setError} = useLoading();

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

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

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

        let fullCount = 0;
        let partialCount = 0;
        let invalidCount = 0;

        for (const [, result] of props.scanData.Ok) {
            if ("Full" in result) {
                fullCount += 1;
            } else if ("Partial" in result) {
                partialCount += 1;
            } else {
                invalidCount += 1;
            }
        }

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

    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((res) => {
                setStatus(LoadingStatus.Ok);
                console.log(res);
            })
            .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>
                    </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>
                </FilledCard>
            </Show>
        </>
    );
}


function dataFromScanResult(result: ScanResult) {
    if ("Full" in result) {
        return `DNI: ${result.Full[0]}, iid: ${result.Full[1]}`;
    } else if ("Partial" in result) {
        return `DNI: ${result.Partial[0]}`;
    } else if ("Error" in result) {
        return `Error: ${result.Error}`;
    }
}
