"use client";
import { useLocationStore } from "@store/Location.Store";
import GroupsOutlinedIcon from "@mui/icons-material/GroupsOutlined";
import GroupIcon from "@mui/icons-material/Group";
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 { CollaboratorView } from "@core/Models/User.model";
import { createCollaborator, findCollaboratorsByEmail } from "../Collaborators.Service";
import Avatar from "@components/Avatar/Avatar";
import Button from "@components/Button/Button";
import MaterialAlert from "@mui/material/Alert";
import style from "./collaborator-add.module.css";
import * as Yup from "yup";
import { useNavigation } from "@hooks/goto";

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 [collaborator, setCollaborator] = useState<CollaboratorView | null>(null);
    const [findEmail, setFindEmail] = useState<string>("");
    const [validatedEmail, setValidatedEmail] = useState<boolean>(false);
    const { goTo } = useNavigation();

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

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

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

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

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

    const findCollaborator = async () => {
        const schema = Yup.object().shape({
            email: Yup.string()
                .email("Debe ingresar un e-mail.")
                .required("Debe introducir el e-mail."),
        });

        const validateData = async () => {
            try {
                await schema.validate({ email: findEmail }, { abortEarly: true });
                setValidatedEmail(true);
                return true;
            } catch (error) {
                console.error(error);
                setValidatedEmail(false);
                return false;
            }
        };
        if (await validateData()) {
            eventHandler.setEventType(EVENT_TYPES.LOADING);
            findCollaboratorsByEmail({ email: findEmail }).then((data) => {
                setCollaborator(data);
                eventHandler.setEventType(EVENT_TYPES.SLEEP);
            });
        }
    };

    const handleCreateCollaborator = () => {
        if (!collaborator) {
            return;
        }

        eventHandler.setEventType(EVENT_TYPES.LOADING);
        createCollaborator({
            companyId: id,
            userId: collaborator.id,
            roles: [],
            sessionUser: SessionInfo.userId,
        })
            .then(() => {
                alert.showSuccess("Colaborador agregado");
                goTo("/admin/org/profile/" + id + "/collaborators");
            })
            .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={findCollaborator}
                />

                <MaterialAlert severity="info" sx={{ marginTop: "20px" }}>
                    <b>Atención:</b> El colaborador debe estar registrado en TurnosXpress y estar
                    suscripto como míinimo al plan gratuito.
                </MaterialAlert>

                {collaborator && (
                    <>
                        <div className={style.collaboratorResultContainer}>
                            <Avatar
                                size="large"
                                border="solid"
                                name={collaborator.fullName}
                                src={collaborator.avatar}
                                alt={collaborator.fullName}
                            />
                            <h1>{collaborator.fullName}</h1>
                            <p>{collaborator.email}</p>
                            <Button
                                name="invitarButton"
                                text="Invitar"
                                onClick={handleCreateCollaborator}
                            />
                        </div>
                    </>
                )}

                {!collaborator && validatedEmail && (
                    <>
                        <div className={style.collaboratorResultContainer}>
                            <h3>No se encontro el colaborador</h3>
                            <p style={{ textAlign: "center" }}>
                                Enviá una solicitud a su e-mail, <b>{findEmail}</b> para que se una
                                a tu organización.
                            </p>
                            <Button name="sendInvitation" text="Invitar" onClick={() => {}} />
                        </div>
                    </>
                )}

                {!collaborator && !validatedEmail && (
                    <>
                        <div>
                            <p>
                                Para agregar un colaborador, ingrese su e-mail. Debe ser el mismo
                                con el que se registro en la plataforma.
                            </p>
                        </div>
                    </>
                )}
            </div>
        </>
    );
}
