"use client";
import { useState, useEffect, useRef } 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 AccountBalanceOutlinedIcon from "@mui/icons-material/AccountBalanceOutlined";
import AccountMovementsIcon from "@mui/icons-material/CurrencyExchangeOutlined";
import DataGrid, { DataGridColumn } from "@core/app/components/DataGrid/DataGrid";
import { formatPrice } from "@core/app/helpers/Numbers";
import dayjs from "dayjs";
import {
    ICashFlow,
    PaginateCashFlowParams,
    PaginateCashFlowResults,
} from "@core/Models/CashFlow.model";
import { cashFlowPaginate } from "../Cash.Service";
import SecureByPlan, { SECURE_CONTENTS } from "@core/app/components/SecureByPlan/SecureByPlan";
import Filterable from "@core/app/components/Filterable/Filterable";
import { TextObjectFilterResult } from "@core/Models/TextObjectFilter.model";
import { TextObjectModalContent } from "@core/Store/TextObjectModal.Store";
import TextObjectFilterItem from "@core/app/components/TextObjectFilterItem/TextObjectFilterItem";
import TextObjectFilter from "@core/app/components/TextObjectFilter/TextObjectFilter";
import { useFilterStore } from "@core/Store/Filter.Store";
import { FindEmployeesParams } from "@core/Models/Collaborators.model";
import filterObjects from "@components/TextObjectFilter/Filter.Service";
import { FindClientsParams } from "@core/Models/Clients.model";
import { paymentMethods, PAYMENT_METHODS } from "@core/Models/Payments.model";

type UrlData = {
    id: string;
};

interface FilterContentProps {
    collaboratorsData: TextObjectFilterResult[];
    setCollaboratorId: (id: string) => void;
    methodsData: TextObjectFilterResult[];
    setMethodId: (id: string) => void;
    clientData: TextObjectFilterResult[];
    setClientId: (id: string) => void;
}

const FilterContent = (props: FilterContentProps) => {
    const [clientFilterContent] = 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 [collaboratorFilterContent] = useState<TextObjectModalContent>({
        header: (
            <div>
                <div
                    style={{
                        fontWeight: "700",
                        fontSize: "14px",
                        paddingTop: "7px",
                    }}
                >
                    Seleccionar Colaborador:
                </div>
                <p
                    style={{
                        fontWeight: "500",
                        fontSize: "13px",
                        paddingTop: "2px",
                    }}
                >
                    Ingrese el nombre del colaborador para buscarlo.
                </p>
            </div>
        ),
        bottom: <div>&nbsp;</div>,
        renderResult: (result: TextObjectFilterResult, index: number) => (
            <TextObjectFilterItem key={index} data={result} />
        ),
    });

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

    return (
        <>
            <TextObjectFilter
                placeholder="Cliente"
                content={clientFilterContent}
                data={props.clientData}
                onChange={(id) => {
                    props.setClientId(id);
                }}
            />

            <TextObjectFilter
                placeholder="Colaborador"
                content={collaboratorFilterContent}
                data={props.collaboratorsData}
                onChange={(id) => {
                    props.setCollaboratorId(id);
                }}
            />

            <TextObjectFilter
                placeholder="Método de Pago"
                content={methodFilterContent}
                data={props.methodsData}
                onChange={(id) => {
                    props.setMethodId(id);
                }}
            />
        </>
    );
};

export default function CashFlowMovementsList() {
    const data = useParams<UrlData>();
    const id = data.id;

    const SessionInfo = useSessionStore();
    const location = useLocationStore();
    const eventHandler = useEventHandlerStore();
    const filter = useFilterStore();

    const [clientFilterData, setClientFilterData] = useState<TextObjectFilterResult[]>([]);
    const [clientId, setClientId] = useState<string>("");

    const [collaboratorFilterData, setCollaboratorFilterData] = useState<TextObjectFilterResult[]>(
        []
    );
    const [collaboratorId, setCollaboratorId] = useState<string>("");

    const [methodFilterData, setMethodFilterData] = useState<TextObjectFilterResult[]>([]);
    const [methodId, setMethodId] = useState<string>("");

    const [dataGridColumns] = useState<DataGridColumn<ICashFlow>[]>([
        {
            field: "description",
            title: "Detalle",
            width: null,
            render: (value: ICashFlow) => (
                <>
                    <div
                        style={{
                            paddingLeft: "10px",
                            paddingRight: "10px",
                            paddingTop: "10px",
                        }}
                    >
                        {value.description}
                    </div>
                    <div
                        style={{
                            paddingLeft: "10px",
                            paddingRight: "10px",
                            color: "var(--gray-dark)",
                        }}
                    >
                        {dayjs(value.createdAt).format("DD MMMM YYYY - HH:mm")}
                    </div>
                </>
            ),
        },
        {
            field: "amount",
            title: "Importe",
            width: 150,
            render: (value: ICashFlow) => (
                <div
                    style={{
                        padding: "10px",
                        textAlign: "right",
                        color: value.amount > 0 ? "var(--green-darkestX2)" : "var(--red)",
                    }}
                >
                    {formatPrice(value.amount)}
                </div>
            ),
        },
    ]);

    const [pageSize] = useState<number>(
        parseInt(
            process.env.NEXT_PUBLIC_DATAGRID_PAGE_SIZE
                ? process.env.NEXT_PUBLIC_DATAGRID_PAGE_SIZE
                : "10"
        )
    );
    const [movements, setMovements] = useState<PaginateCashFlowResults>();
    const movementsRef = useRef(movements);

    const loadMovements = (page: number = 1, pageSize: number = 30) => {
        eventHandler.setEventType(EVENT_TYPES.LOADING);

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

        if (clientId) {
            filterData.clientId = clientId;
        }

        if (collaboratorId) {
            filterData.employeeId = collaboratorId;
        }

        if (methodId) {
            filterData.paymentMethod = methodId as PAYMENT_METHODS;
        }

        cashFlowPaginate(filterData)
            .then((res) => {
                setMovements(res);
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.CLEAR);
            });
    };

    useEffect(() => {
        const filter: FindClientsParams = {
            companyId: id,
        };
        filterObjects<FindClientsParams>("clients/filter-all", filter).then((res) => {
            setClientFilterData(res);
        });
    }, []);

    useEffect(() => {
        const filter: FindEmployeesParams = {
            companyId: id,
        };
        filterObjects<FindEmployeesParams>("employees/filter-all", filter).then((res) => {
            setCollaboratorFilterData(res);
        });
    }, []);

    useEffect(() => {
        setMethodFilterData(paymentMethods);
    }, []);

    useEffect(() => {
        filter.setTitle("Filtrar Movimientos");
        filter.clearFilterData();
        filter.setContent(
            <FilterContent
                collaboratorsData={collaboratorFilterData}
                setCollaboratorId={setCollaboratorId}
                methodsData={methodFilterData}
                setMethodId={setMethodId}
                clientData={clientFilterData}
                setClientId={setClientId}
            />
        );
        filter.setOnFilter(() => { });
    }, [collaboratorFilterData, methodFilterData, clientFilterData]);

    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/profile/" + id + "/cash",
            title: "Caja",
            icon: <AccountBalanceOutlinedIcon sx={{ mr: 0.5 }} fontSize="inherit" />,
        });

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

    useEffect(() => {
        movementsRef.current = movements;
    }, [movements]);

    useEffect(() => {
        let loadPage = 1;

        if (movementsRef.current) {
            loadPage = movementsRef.current.page;
        }
        loadMovements(loadPage, pageSize);
    }, [clientId, collaboratorId, methodId]);

    return (
        <>
            <Location />
            <Filterable />

            <SecureByPlan content={SECURE_CONTENTS.PAYMENTS} companyId={id}>
                <>
                    <div
                        style={{
                            position: "absolute",
                            top: "80px",
                            left: "0px",
                            right: "0px",
                            bottom: "30px",
                        }}
                    >
                        <DataGrid
                            columns={dataGridColumns}
                            data={movements ? movements.data : []}
                            pagination={true}
                            page={movements?.page}
                            pages={movements?.pages}
                            pageSize={pageSize}
                            handleRefresh={loadMovements}
                            handleRowClick={() => { }}
                        />
                    </div>

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