"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 } from "@mui/material";
import ButtonMaterial from "@mui/material/Button";
import { useNavigation } from "@core/app/hooks/goto";
import { PaginateCashFlowParams, PaginateCashFlowResults } from "@core/Models/CashFlow.model";
import { useSessionStore } from "@core/Store/Sesion.Store";
import { cashFlowPaginate } from "./Cash.Service";
import { useAlert } from "@core/Store/Alert.Store";
import { IconButton } from "@mui/material";
import RetirarIcon from "@mui/icons-material/CallMadeOutlined";
import DepositarIcon from "@mui/icons-material/SouthWestOutlined";
import { formatPrice } from "@core/app/helpers/Numbers";
import MovimientosIcon from "@mui/icons-material/Reorder";
import TextRangeDate from "@core/app/components/TextRangeDate/TextRangeDate";
import dayjs, { Dayjs } from "dayjs";
import { getPaymentIcon } from "@core/app/components/PaymentIcons/PaymentIcons";
import { CLIENT_ACCOUNT_MOVEMENT_TYPES } from "@core/Models/ClientAccountMovements.model";
import SecureByPlan, { SECURE_CONTENTS } from "@core/app/components/SecureByPlan/SecureByPlan";

type UrlData = {
    id: string;
};

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

    const [dateFrom, setDateFrom] = useState<Dayjs>(dayjs().startOf("day"));
    const [dateTo, setDateTo] = useState<Dayjs>(dayjs().endOf("day"));
    const [view, setView] = useState<PaginateCashFlowResults | 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(() => {
        cargarDatos();
    }, [SessionInfo.userId, id, dateFrom, dateTo]);

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

        if (!SessionInfo.userId) {
            return;
        }

        if (!id) {
            return;
        }

        const filterData: PaginateCashFlowParams = {
            companyId: id,
            sessionUser: SessionInfo.userId,
            page: 1,
            limit: 10,
        };

        if (dateFrom) {
            filterData.startDate = dateFrom.toDate();
        }
        if (dateTo) {
            filterData.endDate = dateTo.toDate();
        }

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

    const add = (type: CLIENT_ACCOUNT_MOVEMENT_TYPES) => {
        goTo("/admin/org/profile/" + id + "/cash/add/" + type);
    };

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

            <SecureByPlan content={SECURE_CONTENTS.PAYMENTS} companyId={id}>
                <>
                    {view && (
                        <>
                            <TextRangeDate
                                label="Fecha"
                                dateFrom={dateFrom}
                                dateTo={dateTo}
                                setDateFrom={setDateFrom}
                                setDateTo={setDateTo}
                                style={{ marginTop: "20px" }}
                            />
                            <div
                                style={{
                                    display: "flex",
                                    flexDirection: "column",
                                    alignItems: "center",
                                    justifyContent: "center",
                                    backgroundColor: "var(--white-dark)",
                                    borderRadius: "10px",
                                    padding: "10px",
                                    marginTop: "15px",
                                }}
                            >
                                <div
                                    style={{
                                        fontSize: "16px",
                                        fontWeight: "bold",
                                        color: "var(--wine-red)",
                                    }}
                                >
                                    SALDO
                                </div>
                                <div
                                    style={{
                                        fontSize: "45px",
                                        fontWeight: "bold",
                                        color: "var(--wine-red)",
                                    }}
                                >
                                    {formatPrice(view.balance)}
                                </div>
                                <div
                                    style={{
                                        display: "flex",
                                        gap: "10px",
                                        flexDirection: "row",
                                    }}
                                >
                                    <IconButton
                                        sx={{
                                            color: "var(--green-darkestX2)",
                                            display: "flex",
                                            alignItems: "center",
                                            gap: "10px",
                                            flexDirection: "column",
                                            width: "100px",
                                        }}
                                        onClick={() => add(CLIENT_ACCOUNT_MOVEMENT_TYPES.DEPOSIT)}
                                    >
                                        <DepositarIcon sx={{ fontSize: "48px" }} />
                                        <span style={{ fontSize: "14px" }}>Depositar</span>
                                    </IconButton>
                                    <IconButton
                                        sx={{
                                            color: "var(--red-darkest)",
                                            display: "flex",
                                            alignItems: "center",
                                            gap: "10px",
                                            flexDirection: "column",
                                            width: "100px",
                                        }}
                                        onClick={() =>
                                            add(CLIENT_ACCOUNT_MOVEMENT_TYPES.WITHDRAWAL)
                                        }
                                    >
                                        <RetirarIcon sx={{ fontSize: "48px" }} />
                                        <span style={{ fontSize: "14px" }}>Retirar</span>
                                    </IconButton>
                                    <IconButton
                                        sx={{
                                            color: "var(--wine-dark)",
                                            display: "flex",
                                            alignItems: "center",
                                            gap: "10px",
                                            flexDirection: "column",
                                            width: "100px",
                                        }}
                                        onClick={() => {
                                            goTo("/admin/org/profile/" + id + "/cash/movements");
                                        }}
                                    >
                                        <MovimientosIcon sx={{ fontSize: "48px" }} />
                                        <span style={{ fontSize: "14px" }}>Movimientos</span>
                                    </IconButton>
                                </div>
                            </div>
                        </>
                    )}

                    <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",
                            }}
                        >
                            Últimos Movimientos
                        </div>
                        {view && view.data.length > 0 ? (
                            <div
                                style={{
                                    display: "flex",
                                    flexDirection: "column",
                                    alignItems: "center",
                                    justifyContent: "center",
                                    width: "100%",
                                }}
                            >
                                {view.data.map((movement, index) => (
                                    <div
                                        key={"movement" + index}
                                        style={{
                                            width: "100%",
                                        }}
                                    >
                                        <div
                                            style={{
                                                display: "flex",
                                                flexDirection: "row",
                                                alignItems: "flex-start",
                                                justifyContent: "space-between",
                                                width: "100%",
                                                marginBottom: "10px",
                                                borderBottom:
                                                    index < view.data.length - 1
                                                        ? "1px solid var(--white-darkest)"
                                                        : "none",
                                            }}
                                        >
                                            <div
                                                style={{
                                                    maxWidth: "50px",
                                                    minWidth: "50px",
                                                    display: "flex",
                                                    alignItems: "center",
                                                    justifyContent: "center",
                                                    marginTop: "5px",
                                                }}
                                            >
                                                {getPaymentIcon(movement.paymentMethod)}
                                            </div>
                                            <div style={{ width: "100%" }}>
                                                <div style={{ fontSize: "16px" }}>
                                                    {movement.description}
                                                </div>
                                                <div
                                                    style={{
                                                        fontSize: "14px",
                                                        color: "var(--gray-dark)",
                                                        marginBottom: "10px",
                                                    }}
                                                >
                                                    {dayjs(movement.createdAt).format(
                                                        "DD MMMM YYYY - HH:mm"
                                                    )}
                                                </div>
                                            </div>
                                            <div
                                                style={{
                                                    fontSize: "16px",
                                                    fontWeight: "bold",
                                                    color:
                                                        movement.amount > 0
                                                            ? "var(--green-darkestX2)"
                                                            : "var(--red-darkest)",
                                                    backgroundColor:
                                                        movement.amount > 0
                                                            ? "var(--green-light)"
                                                            : "var(--red-light)",
                                                    padding: "5px 10px",
                                                    borderRadius: "5px",
                                                }}
                                            >
                                                {formatPrice(Math.abs(movement.amount))}
                                            </div>
                                        </div>
                                    </div>
                                ))}
                            </div>
                        ) : (
                            <div style={{ fontSize: "16px", fontWeight: "bold" }}>
                                No hay movimientos
                            </div>
                        )}
                    </div>
                    <div style={{ marginBottom: "10px" }}>&nbsp;</div>
                </>
            </SecureByPlan>
        </>
    );
}
