"use client";
import { useParams } from "next/navigation";
import { useEffect, useState } from "react";
import Location from "@components/Location/Location";
import { useLocationStore } from "@store/Location.Store";
import { useEventHandlerStore, EVENT_TYPES } from "@store/EventHandler.Store";
import StorefrontOutlinedIcon from "@mui/icons-material/StorefrontOutlined";
import PaymentsIcon from "@mui/icons-material/CurrencyExchangeOutlined";
import { ThemeProvider } from "@emotion/react";
import turnosXpressTheme from "@core/app/theme/turnosXpress";
import { ButtonGroup, DialogActions, DialogContent } from "@mui/material";
import ButtonMaterial from "@mui/material/Button";
import { useNavigation } from "@core/app/hooks/goto";
import { CashFlowHistoryView, FindCashFlowBalanceParams } from "@core/Models/CashFlow.model";
import { useSessionStore } from "@core/Store/Sesion.Store";
import { useAlert } from "@core/Store/Alert.Store";
import dayjs from "dayjs";
import { cashFlowCalculateBalance, cashFlowHistory } from "../Cash.Service";
import YearInput from "@core/app/components/YearInput/YearInput";
import { formatPrice } from "@core/app/helpers/Numbers";
import SecureByPlan, { SECURE_CONTENTS } from "@core/app/components/SecureByPlan/SecureByPlan";

import CalculateIcon from "@mui/icons-material/EventRepeatOutlined";
import DialogWindow from "@core/app/components/DialogWindow/DialogWindow";
import { useBottomToolbarStore } from "@core/Store/BottomToolbar.Store";
import TextMonth from "@core/app/components/TextMonth/TextMonth";

type UrlData = {
    id: string;
};

export default function OrganizationCashFlowResume() {
    const data = useParams<UrlData>();
    const id = data.id;
    const alert = useAlert();
    const location = useLocationStore();
    const eventHandler = useEventHandlerStore();
    const SessionInfo = useSessionStore();
    const { goTo } = useNavigation();
    const bottomToolbar = useBottomToolbarStore();

    const [dialogCalcVisible, setDialogCalcVisible] = useState<boolean>(false);

    const [year, setYear] = useState<number>(dayjs().year());
    const [month, setMonth] = useState<number>(1);

    const [view, setView] = useState<CashFlowHistoryView | null>(null);

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

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

        location.add({
            url: "/admin/org",
            title: "Organizaciones",
            icon: null,
        });

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

        location.add({
            url: "/admin/org/profile/" + id,
            title: "Caja",
            icon: <PaymentsIcon sx={{ fontSize: "32px", mr: "10px" }} />,
        });
    }, []);

    useEffect(() => {
        bottomToolbar.set(
            <div
                style={{
                    display: "flex",
                    justifyContent: "center",
                    alignItems: "center",
                    width: "100%",
                    flexDirection: "row",
                }}
            >
                <ButtonMaterial
                    variant="text"
                    startIcon={<CalculateIcon />}
                    sx={{ color: "var(--white)" }}
                    onClick={() => {
                        setDialogCalcVisible(true);
                    }}
                >
                    Recalcular Balance
                </ButtonMaterial>
            </div>
        );

        return () => {
            bottomToolbar.clear();
        };
    }, []);

    useEffect(() => {
        cargarDatos();
    }, [SessionInfo.userId, id, year]);

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

        if (!SessionInfo.userId) {
            return;
        }

        if (!id) {
            return;
        }

        const filterData: FindCashFlowBalanceParams = {
            companyId: id,
            sessionUser: SessionInfo.userId,
            year: year,
            month: 6,
        };

        cashFlowHistory(filterData)
            .then((data) => {
                setView(data);
            })
            .catch((error) => {
                alert.showError(error.format());
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.CLEAR);
            });
    };

    const calculateBalanceHandler = () => {
        if (!SessionInfo.userId) {
            return;
        }

        if (!id) {
            return;
        }

        eventHandler.setEventType(EVENT_TYPES.LOADING);

        cashFlowCalculateBalance({
            companyId: id,
            year: year,
            month: month,
            sessionUser: SessionInfo.userId,
        })
            .then(() => {
                alert.showSuccess("Balance calculado correctamente");
                setDialogCalcVisible(false);
                setMonth(1);
                cargarDatos();
            })
            .catch((error) => {
                alert.showError(error.format());
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.CLEAR);
            });
    };

    return (
        <>
            <Location />
            <div style={{ display: "flex", justifyContent: "center", marginTop: "15px" }}>
                <ThemeProvider theme={turnosXpressTheme}>
                    <ButtonGroup variant="outlined" aria-label="Basic button group">
                        <ButtonMaterial
                            variant="outlined"
                            onClick={() => {
                                goTo(`/admin/org/profile/${id}/cash`);
                            }}
                        >
                            Detalle
                        </ButtonMaterial>
                        <ButtonMaterial variant="contained">Resumen</ButtonMaterial>
                    </ButtonGroup>
                </ThemeProvider>
            </div>

            <SecureByPlan content={SECURE_CONTENTS.PAYMENTS} companyId={id}>
                <>
                    <YearInput
                        year={year}
                        setYear={setYear}
                        style={{ marginTop: "15px", height: "50px" }}
                    />

                    <div
                        style={{
                            display: "flex",
                            flexDirection: "column",
                            alignItems: "center",
                            justifyContent: "center",
                            marginTop: "15px",
                            backgroundColor: "var(--white-dark)",
                            borderRadius: "10px",
                            padding: "20px",
                        }}
                    >
                        <div
                            style={{
                                fontSize: "16px",
                                fontWeight: "bold",
                                marginBottom: "10px",
                            }}
                        >
                            Resumen
                        </div>
                        {view && view.data.length > 0 ? (
                            <div
                                style={{
                                    display: "flex",
                                    flexDirection: "column",
                                    alignItems: "center",
                                    justifyContent: "center",
                                    width: "100%",
                                }}
                            >
                                {view.data.map((monthData, index) => (
                                    <div
                                        key={"monthData" + index}
                                        style={{
                                            width: "100%",
                                            display: "flex",
                                            flexDirection: "row",
                                            alignItems: "center",
                                            justifyContent: "space-between",
                                        }}
                                    >
                                        <div
                                            style={{
                                                fontSize: "16px",
                                                textTransform: "capitalize",
                                            }}
                                        >
                                            {dayjs().month(monthData.month).format("MMMM")}
                                        </div>
                                        <div
                                            style={{
                                                fontSize: "16px",
                                            }}
                                        >
                                            {formatPrice(monthData.amount)}
                                        </div>
                                    </div>
                                ))}
                                <div
                                    style={{
                                        width: "100%",
                                        display: "flex",
                                        flexDirection: "row",
                                        alignItems: "center",
                                        justifyContent: "space-between",
                                        marginTop: "10px",
                                    }}
                                >
                                    <div
                                        style={{
                                            fontSize: "16px",
                                            fontWeight: "bold",
                                            textTransform: "capitalize",
                                        }}
                                    >
                                        Total
                                    </div>
                                    <div
                                        style={{
                                            fontSize: "16px",
                                            fontWeight: "bold",
                                        }}
                                    >
                                        {formatPrice(view.total)}
                                    </div>
                                </div>
                            </div>
                        ) : (
                            <div style={{ fontSize: "16px", fontWeight: "bold" }}>
                                No hay movimientos
                            </div>
                        )}
                    </div>

                    <DialogWindow visible={dialogCalcVisible} setVisible={setDialogCalcVisible}>
                        <>
                            <DialogContent
                                style={{
                                    maxWidth: "500px",
                                    minWidth: "300px",
                                    margin: "auto",
                                }}
                            >
                                <TextMonth
                                    label="Seleccionar Mes"
                                    month={month}
                                    setMonth={setMonth}
                                    style={{ marginTop: "15px", height: "50px", width: "300px" }}
                                />
                            </DialogContent>
                            <DialogActions>
                                <ButtonMaterial
                                    variant="contained"
                                    color="primary"
                                    onClick={calculateBalanceHandler}
                                >
                                    Recalcular
                                </ButtonMaterial>
                                <ButtonMaterial
                                    variant="contained"
                                    color="secondary"
                                    onClick={() => {
                                        setDialogCalcVisible(false);
                                    }}
                                >
                                    Cancelar
                                </ButtonMaterial>
                            </DialogActions>
                        </>
                    </DialogWindow>

                    <div style={{ marginBottom: "10px" }}>&nbsp;</div>
                </>
            </SecureByPlan>
        </>
    );
}
