import { Show, createSignal, onMount } from "solid-js";
import { FilledButton } from "../components/FilledButton";
import { UserPlusIcon } from "../icons/UserPlusIcon";
import { MaterialInput } from "../components/MaterialInput";
import { Person } from "../types/Person";
import { LoadingStatus, backend, useLoading, wait } from "../utils/functions";
import { JsonResult } from "../types/JsonResult";
import { LoadingIcon } from "../icons/LoadingIcon";

type PersonLink = {
    person_id: number,
    person_classroom_id: number,
    person_classroom_username: string,
};

export function ClassroomUserCreation(props: {
    person: Person,
    onCreate: (classroom_id: number, classroom_username: string) => void,
}) {
    const [email, setEmail] = createSignal("yuli.palo.apaza@gmail.com");
    const [username, setUsername] = createSignal("USERNAME");
    const {setError, status, setStatus} = useLoading();
    const [names, setNames] = createSignal(props.person.person_names);
    const [surnames, setSurnames] = createSignal(`${props.person.person_paternal_surname} ${props.person.person_maternal_surname}`);
    const [password, setPassword] = createSignal(props.person.person_dni);
    const [date, setDate] = createSignal("2023-10-03");

    onMount(() => {
        // Setup initial values
        const [firstName, secondName] = props.person.person_names.split(" ");
        const paternalSurname = props.person.person_paternal_surname;
        const maternalSurname = props.person.person_maternal_surname;

        // The username may be composed of A-Z & 0-9.
        const user = `${firstName[0]}${secondName?.[0] ?? ""}${paternalSurname}${maternalSurname[0]}`
            .toUpperCase()
            .replaceAll("Á", "A")
            .replaceAll("É", "E")
            .replaceAll("Í", "I")
            .replaceAll("Ó", "O")
            .replaceAll("Ú", "U")
            .replaceAll("Ñ", "N")
            .replaceAll(" ", "")
            .replaceAll("-", "");

        const next_date = new Date();
        next_date.setDate(next_date.getDate() + 60);
        setDate(next_date.toISOString().split("T")[0]);

        setUsername(user.toUpperCase());
    });

    const createClassroomUser = async() => {
        setStatus(LoadingStatus.Loading);
        console.log("creating...");

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

        backend.post<JsonResult<PersonLink>>("/api/classroom/user", {
            person_id: props.person.person_id,
            person_names: names(),
            person_surnames: surnames(),
            person_email: email(),
            person_username: username(),
            person_password: password(),
            person_expiration_date: date(),
        })
            .then((response) => {
                if (response.status === 200) {
                    setStatus(LoadingStatus.Ok);
                    props.onCreate(
                        response.data.Ok.person_classroom_id,
                        response.data.Ok.person_classroom_username,
                    );
                } else {
                    console.error(response.data);
                    setError(response.data.Error.reason);
                    setStatus(LoadingStatus.Error);
                }
            })
            .catch((err) => {
                console.error(err);
                setError(`Error fatal: ${err.message}`);
                alert(`Error fatal: ${err.message}`);
                setStatus(LoadingStatus.Error);
            });
    };

    return (
        <div class="px-4 pb-4">
            <p class="py-2">
                O cree un nuevo usuario:
            </p>

            <form
                onsubmit={(ev) => {
                    ev.preventDefault();
                    createClassroomUser();
                }}
            >
                <MaterialInput
                    resourceName="Apellidos"
                    value={surnames()}
                    setValue={setSurnames}
                    disabled={status() === LoadingStatus.Loading}
                />
                <MaterialInput
                    resourceName="Nombres"
                    value={names()}
                    setValue={setNames}
                    disabled={status() === LoadingStatus.Loading}
                />
                <MaterialInput
                    resourceName="Correo electrónico"
                    value={email()}
                    type="email"
                    setValue={setEmail}
                    disabled={status() === LoadingStatus.Loading}
                />
                <div class="grid grid-cols-2 gap-1">
                    <MaterialInput
                        class="relative"
                        resourceName="Usuario"
                        value={username()}
                        setValue={(v) => setUsername(v.toUpperCase())}
                        disabled={status() === LoadingStatus.Loading}
                    />
                    <MaterialInput
                        class="relative"
                        resourceName="Contraseña"
                        value={password().toString()}
                        setValue={setPassword}
                        disabled={status() === LoadingStatus.Loading}
                    />
                </div>
                <MaterialInput
                    resourceName="Fecha de expiracion"
                    type="date"
                    value={date()}
                    setValue={setDate}
                    disabled={status() === LoadingStatus.Loading}
                />

                <FilledButton type="submit" class="ml-2" disabled={status() === LoadingStatus.Loading}>
                    <Show when={status() === LoadingStatus.Loading}>
                        <LoadingIcon
                            class="animate-spin relative mr-2"
                            fill="var(--c-primary-container)"
                            size={16}
                        />
                    </Show>
                    <Show when={status() !== LoadingStatus.Loading}>
                        <UserPlusIcon fill="var(--c-on-primary)" class="mr-2 relative scale-150" size={16} />
                    </Show>
                    Crear usuario
                </FilledButton>
            </form>
        </div>
    );
}
