"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 MaterialAlert from "@mui/material/Alert";
import { createClient } from "../Clients.Service";

type UrlData = {
    id: string;
};

export default function ClientCreate() {
    const data = useParams<UrlData>();
    const id = data.id;
    const alert = useAlert();
    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 { goTo } = useNavigation();

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

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

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

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

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

    useEffect(() => {
        if (eventHandler.eventType === EVENT_TYPES.SAVE) {
            createClient({
                companyId: id,
                firstName: firstName,
                lastName: lastName,
                email: email,
                phoneCountryCode: phoneCountryCode,
                phoneAreaCode: phoneAreaCode,
                phoneNumber: phoneNumber,
                sessionUser: SessionInfo.userId,
            })
                .then((newClient) => {
                    alert.showSuccess(
                        `El cliente ${newClient.firstName} ${newClient.lastName} ha sido creado`
                    );
                    setTimeout(() => {
                        goTo("/admin/org/profile/" + id + "/clients");
                    }, 2000);
                })
                .catch((error) => {
                    alert.showError(error.message);
                })
                .finally(() => {
                    eventHandler.setEventType(EVENT_TYPES.SLEEP);
                });
        }
    }, [eventHandler.eventType]);

    return (
        <>
            <Location />

            <MaterialAlert sx={{ width: "100%", marginTop: "10px" }} severity="info">
                <strong>Nuevo cliente:</strong> Desde aquí puedes crear un cliente para tu
                organización. Si el cliente se registra en TurnosXpress, se generará automáticamente
                al hacer una reservación. Si no está registrado, puedes crear un cliente para hacer
                reservas a su nombre, y luego fusionarlo con el nuevo registro para evitar
                duplicados.
            </MaterialAlert>

            <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>
        </>
    );
}
