"use client";
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 { useAlert } from "@store/Alert.Store";
import Location from "@components/Location/Location";
import { useLocationStore } from "@store/Location.Store";
import AccountCircleOutlinedIcon from "@mui/icons-material/AccountCircleOutlined";
import MaterialAlert from "@mui/material/Alert";
import Button from "@core/app/components/Button/Button";
import { useConfirmStore } from "@core/Store/Confirm.Store";
import { deleteUser } from "./Advanced.Service";
import { useNavigation } from "@core/app/hooks/goto";

export default function EditProfile() {
    const alert = useAlert();
    const confirm = useConfirmStore();
    const SessionInfo = useSessionStore();
    const SessionToken = useSessionTokenStore();
    const eventHandler = useEventHandlerStore();
    const [verification, setVerification] = useState("");
    const { goTo } = useNavigation();

    const location = useLocationStore();

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

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

        location.add({
            url: "/user/profile/edit",
            title: "Configuración avanzada",
            icon: <AccountCircleOutlinedIcon sx={{ fontSize: "32px", mr: "10px" }} />,
        });
    }, []);

    useEffect(() => {
        if (!SessionInfo.userId) {
            return;
        }
    }, [SessionInfo.userId]);

    const eliminarHandler = () => {
        if (!SessionInfo.userId) {
            return;
        }

        if (verification === "eliminar-usuario") {
            confirm.show(
                "Si eliminas tu usuario se perderá toda la información asociada. ¿Estas seguro?",
                () => {
                    eventHandler.setEventType(EVENT_TYPES.LOADING);
                    deleteUser({ sessionUser: SessionInfo.userId })
                        .then(() => {
                            SessionInfo.clear();
                            SessionToken.setToken("");
                            goTo("/landing/login");
                            alert.showSuccess("Usuario eliminado");
                        })
                        .catch((error) => {
                            alert.showError(error.format());
                        })
                        .finally(() => {
                            eventHandler.setEventType(EVENT_TYPES.SLEEP);
                        });
                },
                () => {
                    eventHandler.setEventType(EVENT_TYPES.SLEEP);
                }
            );
        } else {
            alert.showError("La confirmación no es correcta");
        }
    };

    return (
        <>
            <Location />
            <MaterialAlert severity="info" sx={{ marginTop: "20px", width: "100%" }}>
                <strong>Atención:</strong> para darte de baja escribe{" "}
                <strong>eliminar-usuario</strong> en la casilla de confirmación.
            </MaterialAlert>
            <Textbox
                name="verification"
                placeholder="Confirmación"
                type="text"
                value={verification}
                width="100%"
                onChange={(e) => {
                    setVerification(e.target.value);
                }}
            />

            <Button
                text="Eliminar mi usuario"
                width="100%"
                color="error"
                style={{ height: "42px", marginTop: "10px" }}
                onClick={eliminarHandler}
            />
        </>
    );
}
