"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 { useAlert } from "@store/Alert.Store";
import { useNavigation } from "@hooks/goto";
import { TextObjectModalContent } from "@core/Store/TextObjectModal.Store";
import { TextObjectFilterResult, TOFClientsParams } from "@core/Models/TextObjectFilter.model";
import TextObjectFilterItem from "@core/app/components/TextObjectFilterItem/TextObjectFilterItem";
import filterObjects from "@core/app/components/TextObjectFilter/Filter.Service";
import TextObjectFilter from "@core/app/components/TextObjectFilter/TextObjectFilter";
import { clientMerge, findClientById } from "../Client.Service";
import { ClientMergeParams, OrganizationClientView } from "@core/Models/Clients.model";
import Button from "@core/app/components/Button/Button";
import MaterialAlert from "@mui/material/Alert";
import { useConfirmStore } from "@core/Store/Confirm.Store";

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 { goTo } = useNavigation();

    const [clientMergeFilterContent] = useState<TextObjectModalContent>({
        header: (
            <div>
                <div style={{ fontWeight: "700", fontSize: "14px", paddingTop: "7px" }}>
                    Seleccionar Cliente:
                </div>
                <p style={{ fontWeight: "500", fontSize: "13px", paddingTop: "2px" }}>
                    Ingrese el nombre del cliente para buscarlo.
                </p>
            </div>
        ),
        bottom: <div>&nbsp;</div>,
        renderResult: (result: TextObjectFilterResult, index: number) => (
            <TextObjectFilterItem key={index} data={result} />
        ),
    });

    const [clientMergeFilterData, setClientMergeFilterData] = useState<TextObjectFilterResult[]>(
        []
    );
    const [clientMergeId, setClientMergeId] = useState<string>("");

    const [clientFromData, setClientFromData] = useState<OrganizationClientView | null>(null);

    const [clientToData, setClientToData] = useState<OrganizationClientView | null>(null);

    const mergeClients = () => {
        eventHandler.setEventType(EVENT_TYPES.LOADING);

        const clientFrom = clientId;
        const clientTo = clientMergeId;

        const data: ClientMergeParams = {
            sessionUser: SessionInfo.userId,
            fromClientId: clientFrom,
            toClientId: clientTo,
        };

        clientMerge(data)
            .then(() => {
                alert.showSuccess("Los clientes fuerón fusionados con éxito.");
                setTimeout(() => {
                    goTo("/admin/org/" + id + "/client/" + clientTo + "/profile");
                }, 3000);
            })
            .catch((error) => {
                alert.showError(error.format());
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.SLEEP);
            });
    };

    const mergeButtonHandler = () => {
        confirm.show(
            "Al fusionar los clientes solo se conservará el cliente elegido. ¿Estas seguro que queres fusionar los clientes?",
            () => {
                mergeClients();
            },
            () => {}
        );
    };

    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: "Fusionar clientes",
            icon: <ClientsIcon sx={{ fontSize: "32px", mr: "10px" }} />,
        });
    }, []);

    useEffect(() => {
        eventHandler.setEventType(EVENT_TYPES.SLEEP);
        const filter: TOFClientsParams = {
            companyId: id,
        };
        filterObjects<TOFClientsParams>("clients/filter-all", filter).then((res) => {
            setClientMergeFilterData(res);
        });
    }, []);

    useEffect(() => {
        if (!id) {
            return;
        }

        if (!clientId) {
            return;
        }

        if (!SessionInfo.userId) {
            return;
        }

        findClientById({
            id: clientId,
            companyId: id,
            sessionUser: SessionInfo.userId,
        })
            .then((client) => {
                setClientFromData(client);
            })
            .catch((error) => {
                alert.showError(error.message);
            });
    }, [id, clientId, SessionInfo.userId]);

    useEffect(() => {
        if (!id) {
            return;
        }

        if (!clientMergeId) {
            return;
        }

        if (!SessionInfo.userId) {
            return;
        }

        findClientById({
            id: clientMergeId,
            companyId: id,
            sessionUser: SessionInfo.userId,
        })
            .then((client) => {
                setClientToData(client);
            })
            .catch((error) => {
                alert.showError(error.message);
            });
    }, [id, clientMergeId, SessionInfo.userId]);

    return (
        <>
            <Location />

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

            <TextObjectFilter
                placeholder="Elegir cliente"
                content={clientMergeFilterContent}
                data={clientMergeFilterData}
                onChange={(id) => {
                    setClientMergeId(id);
                }}
            />

            <MaterialAlert
                severity="info"
                sx={{
                    marginTop: "30px",
                    width: "100%",
                    marginLeft: "auto",
                    marginRight: "auto",
                }}
            >
                <strong>Atención:</strong> El cliente seleccionado{" "}
                <strong>({clientToData ? clientToData.fullName : "No elegido aún"})</strong> será
                fusionado con el cliente actual <strong>({clientFromData?.fullName}).</strong> Esto
                significa que todos los turnos del cliente actual serán asignados al cliente
                seleccionado. El cliente original será borrado. Solo es posible fusionar un cliente
                creado por la organización con un cliente generado por un usuario y prevalecera el
                cliente generado por el usuario.
            </MaterialAlert>

            <Button
                onClick={mergeButtonHandler}
                text="Fusionar clientes"
                style={{ marginTop: "30px" }}
                width="100%"
            />

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