"use client";
import { useState, useEffect } from "react";
import { useParams } from "next/navigation";
import { useSessionStore } from "@store/Sesion.Store";
import Location from "@components/Location/Location";
import { useLocationStore } from "@store/Location.Store";
import { useEventHandlerStore, EVENT_TYPES } from "@store/EventHandler.Store";
import ClientsIcon from "@mui/icons-material/AccountBoxOutlined";
import Textbox from "@components/Textbox/Textbox";
import { useAlert } from "@store/Alert.Store";
import { useNavigation } from "@hooks/goto";
import TextPhone from "@core/app/components/TextPhone/TextPhone";
import { updateClient, findClientById } from "../Client.Service";
import { validatePhone } from "@core/helpers/validatePhone";
import { useConfirmStore } from "@core/Store/Confirm.Store";
import Switch from "@core/app/components/Switch/Switch";
import { Box, Typography } from "@mui/material";

type UrlData = {
    oid: string;
    clientId: string;
};

export default function ClientCreate() {
    const data = useParams<UrlData>();
    const id = data.oid;
    const clientId = data.clientId;
    const alert = useAlert();
    const confirm = useConfirmStore();
    const SessionInfo = useSessionStore();
    const location = useLocationStore();
    const eventHandler = useEventHandlerStore();
    const [firstName, setFirstName] = useState("");
    const [lastName, setLastName] = useState("");
    const [email, setEmail] = useState("");
    const [phoneCountryCode] = useState("549");
    const [phoneAreaCode, setPhoneAreaCode] = useState("");
    const [phoneNumber, setPhoneNumber] = useState("");
    const [banned, setBanned] = useState(false);
    const { goTo } = useNavigation();

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

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

        location.add({
            url: "/admin/org/profile/" + id + "/clients",
            title: "Clientes",
            icon: null,
        });

        location.add({
            url: "/admin/org/" + id + "/client/" + clientId + "/profile",
            title: "Perfil",
            icon: <ClientsIcon sx={{ mr: 0.5 }} fontSize="inherit" />,
        });

        location.add({
            url: "",
            title: "Editar",
            icon: <ClientsIcon sx={{ fontSize: "32px", mr: "10px" }} />,
        });
    }, []);

    useEffect(() => {
        findClientById({
            id: clientId,
            companyId: id,
            sessionUser: SessionInfo.userId,
        })
            .then((client) => {
                setFirstName(client.firstName);
                setLastName(client.lastName);
                setEmail(client.email);
                setPhoneAreaCode(client.phoneAreaCode);
                setPhoneNumber(client.phoneNumber);
                setBanned(client.banned || false);
            })
            .catch((error) => {
                alert.showError(error.message);
            });
    }, []);

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

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

            updateClient({
                id: clientId,
                companyId: id,
                firstName: firstName,
                lastName: lastName,
                email: email,
                phoneCountryCode: phoneCountryCode,
                phoneAreaCode: phoneAreaCode,
                phoneNumber: phoneNumber,
                banned: banned,
                sessionUser: SessionInfo.userId,
            })
                .then(() => {
                    alert.showSuccess(
                        `Información del cliente ${firstName} ${lastName} actualizada`
                    );
                    setTimeout(() => {
                        goTo("/admin/org/" + id + "/client/" + clientId + "/profile");
                    }, 2000);
                })
                .catch((error) => {
                    alert.showError(error.message);
                })
                .finally(() => {
                    eventHandler.setEventType(EVENT_TYPES.SLEEP);
                });
        }
    }, [eventHandler.eventType]);

    return (
        <>
            <Location />

            <div style={{ marginTop: "15px" }}></div>

            <Textbox
                placeholder="Nombre"
                type="text"
                value={firstName}
                width="100%"
                onChange={(e) => {
                    setFirstName(e.target.value);
                    eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                }}
            />

            <Textbox
                placeholder="Apellido"
                type="text"
                value={lastName}
                width="100%"
                onChange={(e) => {
                    setLastName(e.target.value);
                    eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                }}
            />
            <Textbox
                placeholder="E-mail"
                type="email"
                value={email}
                width="100%"
                onChange={(e) => {
                    setEmail(e.target.value);
                    eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                }}
            />
            <TextPhone
                label="Teléfono"
                areaCode={phoneAreaCode}
                number={phoneNumber}
                width="100%"
                onChangeArea={(e) => {
                    setPhoneAreaCode(e.target.value);
                    eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                }}
                onChangePhone={(e) => {
                    setPhoneNumber(e.target.value);
                    eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                }}
            />
            <div style={{ marginTop: "15px" }}></div>
            <Box sx={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                <Typography variant="body1" sx={{ fontWeight: "bold", paddingLeft: "10px" }}>Baneado (No puede reservar)</Typography>
                <Switch
                    checked={banned}
                    onChange={(checked) => {
                        setBanned(checked);
                        eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                    }}
                />
            </Box>
            <div style={{ marginTop: "15px" }}></div>
        </>
    );
}
