"use client";
import Button from "@components/Button/Button";
import Textbox from "@components/Textbox/Textbox";
import TextPhone from "@components/TextPhone/TextPhone";
import { SignUpParams } from "@core/Models/User.model";
import { useState } from "react";
import Checkbox from "@mui/material/Checkbox";
import Link from "next/link";
import AnimatedContainer from "@components/AnimatedConainer/AnimatedContainer";
import { signUp } from "./Signup.Service";
import { useAlert } from "@core/Store/Alert.Store";
import {
    EVENT_TYPES,
    useEventHandlerStore,
} from "@core/Store/EventHandler.Store";
import { useNavigation } from "@hooks/goto";
import { useConfirmStore } from "@core/Store/Confirm.Store";
import { validatePhone } from "@core/helpers/validatePhone";

export default function RegisterPage() {
    const alert = useAlert();
    const confirm = useConfirmStore();
    const eventHandler = useEventHandlerStore();
    const { goTo } = useNavigation();

    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");
    const [firstName, setFirstName] = useState("");
    const [lastName, setLastName] = useState("");
    const [areaCode, setAreaCode] = useState("");
    const [phone, setPhone] = useState("");
    const [checkReadTerms, setCheckReadTerms] = useState(false);

    const registerUser = () => {
        const validationPhoneResult = validatePhone(areaCode, phone);

        if (!validationPhoneResult.isValid) {
            confirm.show(
                validationPhoneResult.message,
                () => {},
                () => {}
            );
            return;
        }

        const data: SignUpParams = {
            email: email,
            password: password,
            firstName: firstName,
            lastName: lastName,
            phoneAreaCode: areaCode,
            phoneNumber: phone,
        };

        if (!checkReadTerms) {
            confirm.show(
                "Para registrarte debes aceptar los términos y condiciones y las politicas de privacidad",
                () => {},
                () => {}
            );
            return;
        }

        eventHandler.setEventType(EVENT_TYPES.LOADING);

        signUp(data)
            .then(() => {
                alert.showSuccess(
                    "Registro exitoso. Hemos enviado un correo electronico para activar tu cuenta."
                );
                setTimeout(() => {
                    goTo("/landing/login/verification");
                }, 2000);
            })
            .catch((error) => {
                alert.showError(error.format());
                eventHandler.setEventType(EVENT_TYPES.SLEEP);
            });
    };

    return (
        <>
            <AnimatedContainer
                color="#aeaeae"
                minSize={150}
                maxSize={500}
                items={10}
                style={{
                    display: "flex",
                    flexDirection: "column",
                    justifyContent: "center",
                    alignItems: "center",
                    background:
                        "linear-gradient(180deg, var(--wine-darkest) 0%, var(--wine-dark) 100%)",
                }}
            >
                <div className="homeCentered">
                    <div style={{ paddingLeft: "20px", paddingRight: "20px" }}>
                        <div className="card">
                            <h1 className="homeTitleHeader">
                                Registrate Gratis
                            </h1>
                            <Textbox
                                placeholder="Email"
                                type="text"
                                value={email}
                                width="100%"
                                onChange={(e) => {
                                    setEmail(e.target.value);
                                }}
                            />
                            <Textbox
                                placeholder="Clave"
                                type="password"
                                value={password}
                                width="100%"
                                onChange={(e) => {
                                    setPassword(e.target.value);
                                }}
                            />
                            <Textbox
                                placeholder="Nombre"
                                type="text"
                                value={firstName}
                                width="100%"
                                onChange={(e) => {
                                    setFirstName(e.target.value);
                                }}
                            />
                            <Textbox
                                placeholder="Apellido"
                                type="text"
                                value={lastName}
                                width="100%"
                                onChange={(e) => {
                                    setLastName(e.target.value);
                                }}
                            />
                            <TextPhone
                                label="Teléfono"
                                width="100%"
                                areaCode={areaCode}
                                number={phone}
                                onChangeArea={(
                                    e: React.ChangeEvent<HTMLInputElement>
                                ) => {
                                    setAreaCode(e.target.value);
                                }}
                                onChangePhone={(
                                    e: React.ChangeEvent<HTMLInputElement>
                                ) => {
                                    setPhone(e.target.value);
                                }}
                            />
                            <div
                                style={{
                                    display: "flex",
                                    flexDirection: "row",
                                    alignItems: "flex-start",
                                    justifyContent: "flex-start",
                                }}
                            >
                                <Checkbox
                                    checked={checkReadTerms}
                                    onClick={() =>
                                        setCheckReadTerms(!checkReadTerms)
                                    }
                                />
                                <div style={{ marginTop: "8px" }}>
                                    Declaro que acepto los siguientes&nbsp;
                                    <Link href="/landing/terms">
                                        Términos y condiciones
                                    </Link>{" "}
                                    y{" "}
                                    <Link href="/landing/privacy">
                                        Políticas de privacidad
                                    </Link>
                                </div>
                            </div>
                            <Button
                                name="btnLogin"
                                text="Registrarme"
                                width="100%"
                                onClick={registerUser}
                                style={{ marginTop: "20px" }}
                                type="submit"
                            />
                            <div style={{ marginTop: "10px" }}>
                                Ya tengo una cuenta!&nbsp;
                                <Link href="/landing/login">
                                    Iniciar Sesión
                                </Link>
                            </div>
                        </div>
                    </div>
                </div>
            </AnimatedContainer>
        </>
    );
}
