import { createSignal } from "solid-js";
import { MaterialInput } from "../../components/MaterialInput";

export function PersonRegister(props: {dni: string, onRegister: () => void}) {
    const [paternalSurname, setPaternalSurname] = createSignal("");
    const [maternalSurname, setMaternalSurname] = createSignal("");
    const [names, setNames] = createSignal("");
    const [loading, setLoading] = createSignal(false);

    const register = async() => {
        setLoading(true);

        const paternal = paternalSurname();
        const maternal = maternalSurname();
        const name = names();

        if (paternal === "" || maternal === "" || name === "") {
            return;
        }

        const data = {
            person_dni: props.dni,
            person_names: name.toUpperCase(),
            person_paternal_surname: paternal.toUpperCase(),
            person_maternal_surname: maternal.toUpperCase(),
        };

        const response = await fetch(`${import.meta.env.VITE_BACKEND_URL}/api/person`, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify(data),
        });

        if (response.ok) {
            props.onRegister();
        }

        setLoading(false);
    };

    return (
        <div class="relative max-w-[14rem] mx-auto">
            <form
                onSubmit={(ev) => {
                    ev.preventDefault();
                    register();
                }}
            >
                <MaterialInput
                    resourceName="Apellido paterno"
                    value={paternalSurname()}
                    setValue={(v) => setPaternalSurname(v.toUpperCase())}
                    disabled={loading()}
                />
                <MaterialInput
                    resourceName="Apellido materno"
                    value={maternalSurname()}
                    setValue={(v) => setMaternalSurname(v.toUpperCase())}
                    disabled={loading()}
                />
                <MaterialInput
                    resourceName="Nombres"
                    value={names()}
                    setValue={(v) => setNames(v.toUpperCase())}
                    disabled={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"
                >
                    Registrar
                </button>
            </form>
        </div>
    );
}


