import { createMemo, createSignal, onMount } from "solid-js";
import { OutlinedCard } from "../../components/OutlinedCard";
import { LoadingStatus, backend, useLoading, wait } from "../../utils/functions";
import { LoadingIcon } from "../../icons/LoadingIcon";
import { ArrowsClockwiseIcon } from "../../icons/ArrowsClockwiseIcon";
import { JsonResult } from "../../types/JsonResult";
import { AxiosError } from "axios";

export function AccountExpiration(props: {userId: number}) {
    const [expirationDate, setExpirationDate] = createSignal<string | null>(null); // YYYY-MM-DD
    const {status, setStatus, error, setError} = useLoading();

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

    const loadExpiration = async() => {
        setError("");
        setStatus(LoadingStatus.Loading);
        setExpirationDate(null);
        if (import.meta.env.DEV) await wait(1500);

        backend.get<JsonResult<string>>(`/api/classroom/expiration_date/${props.userId}`)
            .then((response) => {
                if (response.status === 200) {
                    const date = response.data.Ok.substring(0, 10);
                    console.log(date);
                    setExpirationDate(date);
                    setStatus(LoadingStatus.Ok);
                }
            })
            .catch((err: AxiosError<JsonResult<null>>) => {
                console.log(err);

                setStatus(LoadingStatus.Error);

                if (err.response?.status === 500) {
                    setError(`Error: ${err?.response?.data?.Error}`);
                } else {
                    setError("Error estableciendo fecha de expiracion. Revisar consola");
                }
            });
    };

    const setExpiration = async() => {
        setStatus(LoadingStatus.Loading);

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

        backend.put<JsonResult<null>>(
            `/api/classroom/expiration_date/${props.userId}`,
            {date: expirationDate()},
        )
            .then((response) => {
                if (response.status === 200) {
                    setStatus(LoadingStatus.Ok);
                }
            })
            .catch((error) => {
                console.error(error);
                setStatus(LoadingStatus.Error);
            });
    };

    onMount(loadExpiration);

    return (
        <OutlinedCard class="w-[24rem] h-[10.5rem] overflow-hidden">
            <h2 class="text-xl p-3 bg-c-surface-variant text-c-on-surface-variant">
                Fecha de expiración del acceso
            </h2>

            <div class="px-4 py-4">
                <p class="grid grid-cols-[auto_9rem] items-center">
                    <span>
                        Fecha de expiración:
                    </span>

                    <input
                        class="bg-c-surface text-c-on-surface border border-c-outline rounded-lg py-1 px-2 font-mono
                            disabled:opacity-50 disabled:cursor-not-allowed"
                        type="date"
                        name="classroom-expiration-update"
                        id="classroom-expiration-update"
                        value={expirationDate() ?? ""}
                        oninput={(e) => setExpirationDate(e.target.value)}
                        disabled={status() === LoadingStatus.Loading}
                    />
                </p>

                <div class="pt-2 grid grid-cols-[auto_8.5rem] items-center gap-2">
                    <span class="text-c-error">
                        {error()}
                    </span>
                    <button
                        class="bg-c-primary text-c-on-primary px-4 py-2 rounded-full cursor-pointer
                            disabled:opacity-50 disabled:cursor-not-allowed relative"
                        type="button"
                        disabled={loading()}
                        onclick={setExpiration}
                    >
                        <span class="mr-6">
                            Actualizar
                        </span>
                        <span
                            class="absolute top-1 right-2"
                            style={{display: loading() ? "inline-block" : "none"}}
                        >
                            <LoadingIcon
                                class="animate-spin"
                                fill="var(--c-primary-container)"
                            />
                        </span>
                        <span
                            class="absolute top-1 right-2"
                            style={{display: loading() ? "none" : "inline-block"}}
                        >
                            <ArrowsClockwiseIcon
                                fill="var(--c-on-primary)"
                            />
                        </span>
                    </button>
                </div>
            </div>

        </OutlinedCard>
    );
}
