"use client";
import { useState, useEffect } from "react";
import { useParams } from "next/navigation";
import Location from "@components/Location/Location";
import { useLocationStore } from "@store/Location.Store";
import { useEventHandlerStore, EVENT_TYPES } from "@store/EventHandler.Store";
import { useAlert } from "@core/Store/Alert.Store";
import { useSessionStore } from "@store/Sesion.Store";

import StorefrontOutlinedIcon from "@mui/icons-material/StorefrontOutlined";
import PlaceOutlinedIcon from "@mui/icons-material/PlaceOutlined";
import ChatBubbleOutlineOutlinedIcon from "@mui/icons-material/ChatBubbleOutlineOutlined";
import CategoryOutlinedIcon from "@mui/icons-material/CategoryOutlined";
import PeopleAltOutlinedIcon from "@mui/icons-material/PeopleAltOutlined";
import AdminPanelSettingsOutlinedIcon from "@mui/icons-material/AdminPanelSettingsOutlined";
import PendingActionsOutlinedIcon from "@mui/icons-material/PendingActionsOutlined";
import TodayOutlinedIcon from "@mui/icons-material/TodayOutlined";
import PaymentsIcon from "@mui/icons-material/CurrencyExchangeOutlined";
import CashIcon from "@mui/icons-material/AccountBalanceOutlined";
import DiscountsIcon from "@mui/icons-material/LocalOfferOutlined";
import TemplatesIcon from "@mui/icons-material/SpeakerNotesOutlined";
import AssistanceIcon from "@mui/icons-material/HeadsetMicOutlined";
import ShareOutlinedIcon from "@mui/icons-material/ShareOutlined";
import Dialog from "@mui/material/Dialog";
import DialogContent from "@mui/material/DialogContent";
import DialogTitle from "@mui/material/DialogTitle";
import CloseIcon from "@mui/icons-material/Close";
import IconButton from "@mui/material/IconButton";
import { getSlug } from "@core/app/helpers/Slug";
import {
    FacebookShareButton,
    WhatsappShareButton,
    TwitterShareButton,
    EmailShareButton,
    TelegramShareButton,
    FacebookIcon,
    WhatsappIcon as WhatsAppShareIcon,
    TwitterIcon,
    EmailIcon,
    TelegramIcon
} from "react-share";

import { useNavigation } from "@hooks/goto";
import { MyOranizationsView } from "@models/Company.model";
import { loadOrganizationsById } from "./Org.Service";
import Button from "@components/Button/Button";
import MaterialAlert from "@mui/material/Alert";
import { validateGuestCollaborator } from "./collaborators/Collaborators.Service";
import { useBottomToolbarStore } from "@store/BottomToolbar.Store";

import dayjs from "dayjs";
import "dayjs/locale/es";
import { useAppointmentsViewStore } from "@core/Store/AppointmentsView.Store";
import ButtonPanel, { ButtonPanelItem } from "@core/app/components/ButtonPanel/ButtonPanel";
dayjs.locale("es");

type UrlData = {
    id: string;
};

export default function OrganizationProfile() {
    const data = useParams<UrlData>();
    const id = data.id;
    const location = useLocationStore();
    const bottomToolbar = useBottomToolbarStore();
    const eventHandler = useEventHandlerStore();
    const SessionInfo = useSessionStore();
    const alert = useAlert();
    const appointmentsView = useAppointmentsViewStore();
    const { goTo } = useNavigation();
    const [organization, setOrganization] = useState<MyOranizationsView | null>();

    const [collaboratorButtons, setCollaboratorButtons] = useState<Array<ButtonPanelItem>>([]);

    const buttons: Array<ButtonPanelItem> = [
        {
            icon: <StorefrontOutlinedIcon />,
            text: "Configuración",
            onClick: () => goTo("/admin/org/profile/" + id + "/edit"),
        },
        {
            icon: <PlaceOutlinedIcon />,
            text: "Editar ubicación",
            onClick: () => goTo("/admin/org/profile/" + id + "/address"),
        },
        {
            icon: <ChatBubbleOutlineOutlinedIcon />,
            text: "WhatsApp",
            onClick: () => goTo("/admin/org/profile/" + id + "/wap"),
        },
        {
            icon: <CategoryOutlinedIcon />,
            text: "Servicios",
            onClick: () => goTo("/admin/org/profile/" + id + "/services"),
        },
        {
            icon: <PeopleAltOutlinedIcon />,
            text: "Colaboradores",
            onClick: () => goTo("/admin/org/profile/" + id + "/collaborators"),
        },
        {
            icon: <AdminPanelSettingsOutlinedIcon />,
            text: "Clientes",
            onClick: () => goTo("/admin/org/profile/" + id + "/clients"),
        },
        {
            icon: <PendingActionsOutlinedIcon />,
            text: "Horarios habilitados",
            onClick: () => goTo("/admin/org/profile/" + id + "/schedules"),
        },
        {
            icon: <TodayOutlinedIcon />,
            text: "Turnos",
            onClick: () => {
                appointmentsView.clear();
                goTo(
                    "/admin/org/profile/" +
                        id +
                        "/appointments/" +
                        encodeURIComponent(dayjs(new Date()).clone().startOf("day").toISOString())
                );
            },
        },
        {
            icon: <PaymentsIcon />,
            text: "Pagos",
            onClick: () => goTo("/admin/org/profile/" + id + "/payments"),
        },
        {
            icon: <CashIcon />,
            text: "Caja",
            onClick: () => goTo("/admin/org/profile/" + id + "/cash"),
        },
        {
            icon: <DiscountsIcon />,
            text: "Descuentos",
            onClick: () => goTo("/admin/org/profile/" + id + "/discounts"),
        },
        {
            icon: <TemplatesIcon />,
            text: "Plantillas",
            onClick: () => goTo("/admin/org/profile/" + id + "/templates"),
        },
        {
            icon: <AssistanceIcon />,
            text: "Asistencia",
            onClick: () => goTo("/admin/org/profile/" + id + "/assistance"),
        },
    ];

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

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

        location.add({
            url: "/admin/org",
            title: "Organizaciones",
            icon: <StorefrontOutlinedIcon sx={{ fontSize: "32px", mr: "10px" }} />,
        });

        location.add({
            url: "",
            title: "Panel de control",
            icon: null,
        });

        bottomToolbar.set(<></>);

        if (SessionInfo.userId) {
            loadOrganization();
        }
    }, [SessionInfo.userId]);

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

        if (!organization.employeeId) {
            return;
        }

        setCollaboratorButtons([
            {
                icon: <TodayOutlinedIcon />,
                text: "Mis Turnos",
                onClick: () => {
                    appointmentsView.setCollaboratorId(organization.employeeId);
                    goTo(
                        "/admin/org/profile/" +
                            id +
                            "/appointments/" +
                            encodeURIComponent(
                                dayjs(new Date()).clone().startOf("day").toISOString()
                            )
                    );
                },
            },
            {
                icon: <ChatBubbleOutlineOutlinedIcon />,
                text: "Mensajes",
                onClick: () => goTo("/messenger"),
            },
        ]);
    }, [organization]);

    const loadOrganization = () => {
        eventHandler.setEventType(EVENT_TYPES.LOADING);
        loadOrganizationsById({ id: id, sessionUser: SessionInfo.userId })
            .then((response: MyOranizationsView) => {
                setOrganization(response);
            })
            .catch((error) => {
                alert.showError(error.format());
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.SLEEP);
            });
    };

    const handleAgree = () => {
        if (!organization) {
            return;
        }

        eventHandler.setEventType(EVENT_TYPES.LOADING);

        validateGuestCollaborator({
            employeeId: organization.employeeId,
            sessionUser: SessionInfo.userId,
        })
            .then(() => {
                loadOrganization();
            })
            .catch((error) => {
                alert.showError(error.format());
                eventHandler.setEventType(EVENT_TYPES.SLEEP);
            });
    };

    return (
        <>
            <Location />
            <div
                style={{
                    display: "flex",
                    flexDirection: "column",
                    marginTop: "20px",
                    gap: "10px",
                }}
            >
                {organization && (organization.isOwner || organization.isAdmin) && (
                    <>
                        <ButtonPanel title="Área de administración" items={buttons} />
                        <div style={{ height: "15px" }}></div>
                    </>
                )}

                {organization && !organization.fullOk && (
                    <>
                        <h3>Área de Colaboradores</h3>
                        <div
                            style={{
                                display: "flex",
                                flexDirection: "column",
                                alignContent: "center",
                                justifyContent: "center",
                                width: "100%",
                            }}
                        >
                            <MaterialAlert
                                severity="info"
                                sx={{
                                    marginTop: "10px",
                                    maxWidth: "680px",
                                    marginLeft: "auto",
                                    marginRight: "auto",
                                }}
                            >
                                <strong>Atención:</strong> Para formar parte de la organización
                                primero debes aceptar la invitación y esperar a ser aceptado por el
                                administrador
                            </MaterialAlert>
                            {!organization.guestOk && (
                                <Button
                                    name="acceptButton"
                                    width="100%"
                                    text="Aceptar invitación"
                                    style={{
                                        marginTop: "20px",
                                        maxWidth: "680px",
                                        marginLeft: "auto",
                                        marginRight: "auto",
                                    }}
                                    onClick={handleAgree}
                                />
                            )}
                        </div>
                    </>
                )}

            {organization && organization.fullOk && (
                <>
                    <ButtonPanel title="Área de Colaboradores" items={collaboratorButtons} />
                </>
            )}

            <div style={{ height: "20px" }}></div>
        </div>
    </>
);
}
