"use client";
import { useLocationStore } from "@store/Location.Store";
import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import Location from "@components/Location/Location";
import SearchText from "@components/SearchText/SearchText";
import { useEventHandlerStore, EVENT_TYPES } from "@store/EventHandler.Store";
import { useSessionStore } from "@store/Sesion.Store";
import { useAlert } from "@store/Alert.Store";
import MaterialAlert from "@mui/material/Alert";
import { UserAssistanceInfo } from "@core/Models/User.model";
import Link from "next/link";
import { getAssistanceUserInfo } from "./Assistance.Service";
import AssistanceIcon from "@mui/icons-material/HeadsetMicOutlined";

type UrlData = {
    id: string;
};

export default function CollaboratorsAdd() {
    const urlData = useParams<UrlData>();
    const id = urlData.id;
    const alert = useAlert();
    const eventHandler = useEventHandlerStore();
    const location = useLocationStore();
    const SessionInfo = useSessionStore();
    const [user, setUser] = useState<UserAssistanceInfo | null>(null);
    const [findEmail, setFindEmail] = useState<string>("");

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

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

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

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

    const findUser = async () => {
        eventHandler.setEventType(EVENT_TYPES.LOADING);
        getAssistanceUserInfo({ email: findEmail, sessionUser: SessionInfo.userId })
            .then((response) => {
                setUser(response);
            })
            .catch((error) => {
                alert.showError(error.format());
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.SLEEP);
            });
    };

    return (
        <>
            <Location />
            <div
                style={{ display: "flex", flexDirection: "column", marginTop: "20px", gap: "10px" }}
            >
                <SearchText
                    value={findEmail}
                    width="100%"
                    placeHolder="Buscar por e-mail"
                    actionText="Buscar"
                    onChange={(e) => {
                        setFindEmail(e.target.value.toLowerCase().trim());
                    }}
                    onClick={findUser}
                />

                {!user && (
                    <MaterialAlert severity="info" sx={{ marginTop: "20px" }}>
                        <b>Atención:</b> El usuario debe estar registrado en TurnosXpress con el
                        correo electrónico ingresado.
                    </MaterialAlert>
                )}

                {user && !user.email && (
                    <>
                        <MaterialAlert severity="error" sx={{ marginTop: "20px" }}>
                            <b>Atención:</b> No se ha encontrado un usuario con el e-mail ingresado.
                        </MaterialAlert>
                    </>
                )}

                {user && user.email && user.verificated && !user.recoveryCode && (
                    <>
                        <MaterialAlert severity="success" sx={{ marginTop: "20px" }}>
                            <b>Atención:</b> El usuario asociado al correo electrónico ingresado ya
                            se encuentra activo.
                        </MaterialAlert>
                    </>
                )}

                {user && user.email && user.verificated && user.recoveryCode && (
                    <>
                        <MaterialAlert severity="success" sx={{ marginTop: "20px" }}>
                            <b>Atención:</b> {user.message}
                        </MaterialAlert>
                    </>
                )}

                {user && user.email && !user.verificated && (
                    <>
                        <div
                            style={{
                                display: "flex",
                                flexDirection: "column",
                                marginTop: "10px",
                                backgroundColor: "var(--white-dark)",
                                border: "1px solid var(--gray-light)",
                                borderRadius: "10px",
                                padding: "20px",
                                maxWidth: "600px",
                                marginLeft: "auto",
                                marginRight: "auto",
                            }}
                        >
                            <h1
                                style={{
                                    color: "var(--wine-dark)",
                                    paddingBottom: "0px",
                                    marginBottom: "0px",
                                    marginTop: "0px",
                                    paddingTop: "0px",
                                }}
                            >
                                {user.fullName}
                            </h1>
                            <h2 style={{ color: "var(--black)", fontSize: "16px" }}>
                                {user.email}
                            </h2>
                            <p style={{ color: "var(--black)", marginTop: "15px" }}>
                                El usuario esta inactivo. Para activarlo debe ingresar en{" "}
                                <Link href={"/landing/login/verification"}>
                                    https://turnosxpress.com.ar/landing/login/verification
                                </Link>{" "}
                                con el siguiente código de activación:
                            </p>
                            <div
                                style={{
                                    marginLeft: "auto",
                                    marginRight: "auto",
                                    marginTop: "10px",
                                    marginBottom: "10px",
                                    padding: "10px 20px",
                                    border: "1px solid var(--green-darkest)",
                                    borderRadius: "10px",
                                    backgroundColor: "var(--green-light)",
                                    fontSize: "36px",
                                    fontWeight: "bold",
                                    color: "var(--black)",
                                    letterSpacing: "10px",
                                }}
                            >
                                {user.activationCode}
                            </div>
                        </div>
                    </>
                )}

                {user && user.email && user.verificated && user.recoveryCode && (
                    <>
                        <div
                            style={{
                                display: "flex",
                                flexDirection: "column",
                                marginTop: "10px",
                                backgroundColor: "var(--white-dark)",
                                border: "1px solid var(--gray-light)",
                                borderRadius: "10px",
                                padding: "20px",
                                maxWidth: "600px",
                                marginLeft: "auto",
                                marginRight: "auto",
                            }}
                        >
                            <h1
                                style={{
                                    color: "var(--wine-dark)",
                                    paddingBottom: "0px",
                                    marginBottom: "0px",
                                    marginTop: "0px",
                                    paddingTop: "0px",
                                }}
                            >
                                {user.fullName}
                            </h1>
                            <h2 style={{ color: "var(--black)", fontSize: "16px" }}>
                                {user.email}
                            </h2>
                            <p style={{ color: "var(--black)", marginTop: "15px" }}>
                                El usuario esta activo. Para cambiar la clave debe ingresar en{" "}
                                <Link href={"/landing/recover-account/verify"}>
                                    https://turnosxpress.com.ar/landing/recover-account/verify
                                </Link>{" "}
                                con el siguiente código de recuperación:
                            </p>
                            <div
                                style={{
                                    marginLeft: "auto",
                                    marginRight: "auto",
                                    marginTop: "10px",
                                    marginBottom: "10px",
                                    padding: "10px 20px",
                                    border: "1px solid var(--green-darkest)",
                                    borderRadius: "10px",
                                    backgroundColor: "var(--green-light)",
                                    fontSize: "36px",
                                    fontWeight: "bold",
                                    color: "var(--black)",
                                    letterSpacing: "10px",
                                }}
                            >
                                {user.recoveryCode}
                            </div>
                        </div>
                    </>
                )}
            </div>
        </>
    );
}
