"use client";
import { useState, useEffect } from "react";
import Textbox from "@components/Textbox/Textbox";
import { useSessionStore } from "@store/Sesion.Store";
import { EVENT_TYPES, useEventHandlerStore } from "@store/EventHandler.Store";
import TextPhone from "@components/TextPhone/TextPhone";
import { loadUserInfo, updateUserInfo } from "./UserEdit.Service";
import { IUserView } from "@models/User.model";
import { useAlert } from "@store/Alert.Store";
import { ApiError } from "@models/Server.Error.model";

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

export default function EditProfile() {
    const alert = useAlert();
    const confirm = useConfirmStore();
    const SessionInfo = useSessionStore();
    const eventHandler = useEventHandlerStore();
    const [firstName, setFirstName] = useState("");
    const [lastName, setLastName] = useState("");
    const [areaCode, setAreaCode] = useState("");
    const [phone, setPhone] = useState("");
    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: "Editar perfil",
            icon: <AccountCircleOutlinedIcon sx={{ fontSize: "32px", mr: "10px" }} />,
        });
    }, []);

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

        loadUserInfo(SessionInfo.userId)
            .then((response: IUserView) => {
                setFirstName(response.firstName);
                setLastName(response.lastName);
                setAreaCode(response.phoneAreaCode);
                setPhone(response.phoneNumber);
                eventHandler.setEventType(EVENT_TYPES.SLEEP);
            })
            .catch(() => {});
    }, [SessionInfo.userId]);

    useEffect(() => {
        if (eventHandler.eventType === EVENT_TYPES.SAVE) {
            const validationPhoneResult = validatePhone(areaCode, phone);

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

            updateUserInfo({
                id: SessionInfo.userId,
                firstName: firstName,
                lastName: lastName,
                phoneNumber: phone,
                phoneAreaCode: areaCode,
                phoneCountryCode: "549",
                sessionUser: SessionInfo.userId,
            })
                .then(() => {
                    alert.showSuccess("Perfil actualizado!");
                })
                .catch((error: ApiError) => {
                    alert.showError(error.format());
                })
                .finally(() => {
                    eventHandler.setEventType(EVENT_TYPES.SLEEP);
                });
        }
    }, [eventHandler.eventType]);

    return (
        <>
            <Location />
            <Textbox
                name="firstName"
                placeholder="Nombre"
                type="text"
                value={firstName}
                width="100%"
                onChange={(e) => {
                    setFirstName(e.target.value);
                    eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                }}
            />
            <Textbox
                name="lastName"
                placeholder="Apellido"
                type="text"
                value={lastName}
                width="100%"
                onChange={(e) => {
                    setLastName(e.target.value);
                    eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                }}
            />
            <TextPhone
                label="Teléfono"
                areaCode={areaCode}
                number={phone}
                width="100%"
                onChangeArea={(e) => {
                    setAreaCode(e.target.value);
                    eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                }}
                onChangePhone={(e) => {
                    setPhone(e.target.value);
                    eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                }}
            />
        </>
    );
}
