"use client";
import { useRouter } from "next/navigation";
import { useState, useEffect } from "react";
import Textbox from "@components/Textbox/Textbox";
import { useSessionStore, useSessionTokenStore } from "@store/Sesion.Store";
import { EVENT_TYPES, useEventHandlerStore } from "@store/EventHandler.Store";
import { changePassword } from "./UserSecurity.Service";
import { useAlert } from "@store/Alert.Store";
import { ApiError } from "@models/Server.Error.model";
import * as Yup from "yup";

import Location from "@components/Location/Location";
import { useLocationStore } from "@store/Location.Store";
import AccountCircleOutlinedIcon from "@mui/icons-material/AccountCircleOutlined";

export default function EditProfile() {
    const router = useRouter();
    const alert = useAlert();
    const SessionInfo = useSessionStore();
    const SessionToken = useSessionTokenStore();
    const eventHandler = useEventHandlerStore();
    const [oldPassword, setOldPassword] = useState("");
    const [newPassword1, setNewPassword1] = useState("");
    const [newPassword2, setNewPassword2] = useState("");
    const location = useLocationStore();

    const logOut = () => {
        SessionInfo.clear();
        SessionToken.setToken("");
        goTo("/");
    };

    const goTo = (path: string) => {
        router.push(path);
    };

    useEffect(() => {
        eventHandler.setEventType(EVENT_TYPES.SLEEP);
    }, []);

    useEffect(() => {
        location.clear();

        location.add({
            url: "/user/profile",
            title: "Perfil de usuario",
            icon: <AccountCircleOutlinedIcon sx={{ fontSize: "32px", mr: "10px" }} />,
        });

        location.add({
            url: "/user/profile/security",
            title: "Cambiar contraseña",
            icon: <AccountCircleOutlinedIcon sx={{ fontSize: "32px", mr: "10px" }} />,
        });
    }, []);

    useEffect(() => {
        if (eventHandler.eventType === EVENT_TYPES.SAVE) {
            const schema = Yup.object().shape({
                oldPassword: Yup.string().required("Debe introducir la contraseña anterior."),
                newPassword1: Yup.string()
                    .min(8, "La nueva contraseña debe tener al menos 8 caracteres.")
                    .required("Debe introducir una nueva contraseña."),
                newPassword2: Yup.string()
                    .min(
                        8,
                        "La verificación de la nueva contraseña debe tener al menos 8 caracteres."
                    )
                    .required("Debe introducir la verificación de la nueva contraseña."),
            });

            schema
                .validate({ oldPassword, newPassword1, newPassword2 }, { abortEarly: true })
                .then(() => {
                    if (newPassword1 !== newPassword2) {
                        alert.showError("Las contraseñas no coinciden");
                        eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                        return;
                    }
                    changePassword({
                        oldPassword: oldPassword,
                        newPassword: newPassword1,
                        sessionUser: SessionInfo.userId,
                    })
                        .then(() => {
                            alert.showSuccess(
                                "Contraseña actualizada!. Cerrando sesión en 3 segundos."
                            );
                            setTimeout(() => {
                                logOut();
                            }, 3000);
                        })
                        .catch((error: ApiError) => {
                            alert.showError(error.format());
                        })
                        .finally(() => {
                            eventHandler.setEventType(EVENT_TYPES.SLEEP);
                        });
                })
                .catch((error: Yup.ValidationError) => {
                    eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                    alert.showError(error.message);
                });
        }
    }, [eventHandler.eventType]);

    return (
        <>
            <Location />
            <Textbox
                name="oldPassword"
                placeholder="Contraseña anterior"
                type="password"
                value={oldPassword}
                width="100%"
                onChange={(e) => {
                    setOldPassword(e.target.value);
                    eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                }}
            />
            <Textbox
                name="newPassword1"
                placeholder="Contraaseña nueva"
                type="password"
                value={newPassword1}
                width="100%"
                onChange={(e) => {
                    setNewPassword1(e.target.value);
                    eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                }}
            />
            <Textbox
                name="newPassword2"
                placeholder="Repetir contraaseña nueva"
                type="password"
                value={newPassword2}
                width="100%"
                onChange={(e) => {
                    setNewPassword2(e.target.value);
                    eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                }}
            />
        </>
    );
}
