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

enum ExpiryStatus {
    Ok,
    Soon,
    Expired,
}

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

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

    const expired = createMemo<ExpiryStatus>(() => {
        if (expirationDate() === null) {
            return ExpiryStatus.Ok;
        }

        const expiryDate = new Date(`${expirationDate()}T00:00:00`);

        const today = new Date();
        const aMonthFromNow = new Date();
        aMonthFromNow.setDate(aMonthFromNow.getDate() + 30);

        if (expiryDate < today) {
            return ExpiryStatus.Expired;
        } else if (expiryDate < aMonthFromNow) {
            return ExpiryStatus.Soon;
        } else {
            return ExpiryStatus.Ok;
        }
    });

    const dateColor = createMemo(() => {
        switch (expired()) {
            case ExpiryStatus.Ok:
                return "var(--c-success)";
            case ExpiryStatus.Soon:
                return "#9e4300";
            case ExpiryStatus.Expired:
                return "var(--c-error)";
        }
    });


    const loadExpiration = () => {
        setError("");
        setStatus(LoadingStatus.Loading);
        setExpirationDate(null);
        setLocalExpirationDate(null);

        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 setExpiration2Months = () => {
        setStatus(LoadingStatus.Loading);
        const newDate = new Date();
        newDate.setDate(newDate.getDate() + 60);
        setLocalExpirationDate(newDate.toISOString().split("T")[0]);

        setExpiration();
    };

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

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

    onMount(loadExpiration);

    return (
        <OutlinedCard class="w-[24rem] 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 h-10">
                    <span>
                    Esta cuenta expira el:
                    </span>

                    <span
                        class="font-mono font-bold text-center"
                        style={{color: dateColor()}}
                        title={expired() === ExpiryStatus.Expired ? "Esta cuenta ha expirado" : ""}
                    >
                        <Show when={loading()}>
                            <LoadingIcon
                                class="animate-spin"
                                fill="var(--c-primary-container)"
                            />
                        </Show>
                        <Show when={!loading()}>
                            {formatDate(expirationDate() ?? "0-0-0")}
                        </Show>
                        <Show when={expired() === ExpiryStatus.Expired}>
                            <WarningIcon
                                class="mx-2"
                                fill="var(--c-error)"
                            />
                        </Show>
                    </span>
                </p>

                <hr />

                <div class="grid grid-cols-2">
                    <div class="border-r border-c-outline pt-2 pr-1">
                        <p>Establecer expiracion:</p>

                        <button
                            class="bg-c-primary text-c-on-primary px-3 py-2 rounded-full cursor-pointer
                            disabled:opacity-50 disabled:cursor-not-allowed relative mt-[2.47rem]"
                            type="button"
                            disabled={loading()}
                            onclick={setExpiration2Months}
                        >
                            <span class="mr-6">
                                2 meses d. hoy
                            </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-1"
                                style={{display: loading() ? "none" : "inline-block"}}
                            >
                                <PlusIcon
                                    fill="var(--c-on-primary)"
                                />
                            </span>
                        </button>
                    </div>
                    <div class="pt-2 pl-1 text-right">
                        <p>Establecer expiracion:</p>

                        <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 my-1"
                            type="date"
                            name="classroom-expiration-update"
                            id="classroom-expiration-update"
                            value={localExpirationDate() ?? ""}
                            oninput={(e) => setLocalExpirationDate(e.target.value)}
                            disabled={status() === LoadingStatus.Loading}
                        />

                        <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">
                                Establecer
                            </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>

                <div class="pt-2 grid grid-cols-[auto_8.5rem] items-center gap-2">
                    <span class="text-c-error">
                        {error()}
                    </span>

                </div>
            </div>

        </OutlinedCard>
    );
}
