"use client";
import { useParams } from "next/navigation";
import { useState, useEffect, useRef } from "react";
import { motion, AnimatePresence } from "motion/react";
import Pagination from "@mui/material/Pagination";
import CreditCardIcon from "@mui/icons-material/CreditCard";
import UnfoldLessIcon from "@mui/icons-material/UnfoldLess";
import UnfoldMoreIcon from "@mui/icons-material/UnfoldMore";
import FilterAltOutlinedIcon from "@mui/icons-material/FilterAltOutlined";
import Location from "@components/Location/Location";
import PictureAsPdfIcon from "@mui/icons-material/PictureAsPdf";
import { useLocationStore } from "@store/Location.Store";
import { useEventHandlerStore, EVENT_TYPES } from "@store/EventHandler.Store";
import { useSessionStore } from "@store/Sesion.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, IconButton } from "@mui/material";
import ButtonMaterial from "@mui/material/Button";
import DataGrid, { DataGridColumn } from "@core/app/components/DataGrid/DataGrid";
import {
    CreatePaymentParams,
    FindPaymentsParams,
    PaginateNotPayedAppointmentsParams,
    PaginateNotPayedAppointmentsResult,
    PaginatePaymentsView,
    PAYMENT_PROCCESS_DATE,
    paymentMethods,
} from "@core/Models/Payments.model";
import dayjs, { Dayjs } from "dayjs";
import { formatPrice } from "@core/app/helpers/Numbers";
import { getPaymentIcon } from "@core/app/components/PaymentIcons/PaymentIcons";
import PayIcon from "@mui/icons-material/CurrencyExchangeOutlined";
import CreatePaymentIcon from "@mui/icons-material/LocalAtmOutlined";
import { useBottomToolbarStore } from "@core/Store/BottomToolbar.Store";
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 TextObjectMultiFilter from "@core/app/components/TextObjectMultiFilter/TextObjectMultiFilter";
import { useFilterStore } from "@core/Store/Filter.Store";
import { FindEmployeesParams } from "@core/Models/Collaborators.model";
import filterObjects from "@components/TextObjectFilter/Filter.Service";
import { GetNotPayedReport } from "../../Org.Service";
import { FindServicesParams } from "@core/Models/Service.model";
import { FindClientsParams } from "@core/Models/Clients.model";
import TextRangeDateModern from "@core/app/components/TextRangeDateModern/TextRangeDateModern";
import {
    createPayment,
    paginateNotPayedAppointments,
    paginateNotPayedAppointmentsTotal,
    payNotPayedAppointments,
} from "../../Org.Service";
import { useNavigation } from "@core/app/hooks/goto";
import { useAlert } from "@core/Store/Alert.Store";
import DialogWindow from "@core/app/components/DialogWindow/DialogWindow";
import { DialogActions, DialogContent } from "@mui/material";
import {
    CLIENT_ACCOUNT_MOVEMENT_STATUS,
    CLIENT_ACCOUNT_PAYMENT_METHODS,
} from "@core/Models/ClientAccountMovements.model";
import SecureByPlan, { SECURE_CONTENTS } from "@core/app/components/SecureByPlan/SecureByPlan";

type UrlData = {
    id: string;
};

interface FilterContentProps {
    collaboratorsData: TextObjectFilterResult[];
    setCollaboratorId: (id: string) => void;
    servicesData: TextObjectFilterResult[];
    setServiceId: (id: string) => void;
    methodsData: TextObjectFilterResult[];
    setMethodId: (id: string) => void;
    clientData: TextObjectFilterResult[];
    setClientIds: (ids: 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 [serviceFilterContent] = useState<TextObjectModalContent>({
        header: (
            <div>
                <div
                    style={{
                        fontWeight: "700",
                        fontSize: "14px",
                        paddingTop: "7px",
                    }}
                >
                    Seleccionar Servicio:
                </div>
                <p
                    style={{
                        fontWeight: "500",
                        fontSize: "13px",
                        paddingTop: "2px",
                    }}
                >
                    Ingrese el nombre del servicio 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 (
        <>
            <TextObjectMultiFilter
                placeholder="Clientes"
                content={clientFilterContent}
                data={props.clientData}
                onChange={(ids) => {
                    props.setClientIds(ids);
                }}
            />

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

            <TextObjectFilter
                placeholder="Servicio"
                content={serviceFilterContent}
                data={props.servicesData}
                onChange={(id) => {
                    props.setServiceId(id);
                }}
            />

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

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

    const [dialogPayVisible, setDialogPayVisible] = useState<boolean>(false);
    const [dialogPayOneVisible, setDialogPayOneVisible] = useState<boolean>(false);
    const [createPaymentData, setCreatePaymentData] = useState<PaginatePaymentsView | undefined>(
        undefined
    );

    const [paymentMethodFilterContent] = 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} />
        ),
    });

    const [paymentMethhodFilterData, setPaymentMethodFilterData] = useState<
        TextObjectFilterResult[]
    >([]);
    const [paymentMethodId, setPaymentMethodId] = useState<CLIENT_ACCOUNT_PAYMENT_METHODS>(
        CLIENT_ACCOUNT_PAYMENT_METHODS.CASH
    );

    useEffect(() => {
        loadPaymentMethods();
    }, []);

    //-----------------

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

    const [paymentProcessDateFilterData, setPaymentProcessDateMethodFilterData] = useState<
        TextObjectFilterResult[]
    >([]);
    const [paymentProcessDateId, setPaymentProcessDateId] = useState<PAYMENT_PROCCESS_DATE>(
        PAYMENT_PROCCESS_DATE.NOW
    );

    useEffect(() => {
        loadPaymentProcessDates();
    }, []);

    //-----------------

    const loadPaymentProcessDates = () => {
        setPaymentProcessDateMethodFilterData([
            {
                id: PAYMENT_PROCCESS_DATE.NOW,
                name: "Fecha de hoy",
                description: "Se usara la fecha de hoy",
            },
            {
                id: PAYMENT_PROCCESS_DATE.APPOINTMENT,
                name: "Fecha de la reserva",
                description: "Se usara la fecha de la reserva",
            },
        ]);
    };

    const loadPaymentMethods = () => {
        setPaymentMethodFilterData(
            paymentMethods.map((category) => ({
                id: category.id.toString(),
                name: category.name,
                description: category.description,
            }))
        );
    };

    const bottomToolbar = useBottomToolbarStore();
    const [paymentsTotal, setPaymentsTotal] = useState<number>(0);

    const [dateFrom, setDateFrom] = useState<Dayjs>(dayjs().startOf("day"));
    const [dateTo, setDateTo] = useState<Dayjs>(dayjs().endOf("day"));

    const [clientFilterData, setClientFilterData] = useState<TextObjectFilterResult[]>([]);
    const [clientIds, setClientIds] = useState<string[]>([]);

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

    const [serviceFilterData, setServiceFilterData] = useState<TextObjectFilterResult[]>([]);
    const [serviceId, setServiceId] = useState<string>("");

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

    const [dataGridColumns] = useState<DataGridColumn<PaginatePaymentsView>[]>([
        {
            field: "method",
            title: "",
            width: 40,
            render: (value: PaginatePaymentsView) => (
                <div
                    style={{
                        display: "flex",
                        justifyContent: "center",
                        alignItems: "center",
                        verticalAlign: "top",
                        marginTop: "15px",
                    }}
                >
                    {getPaymentIcon(value.method)}
                </div>
            ),
        },
        {
            field: "serviceName",
            title: "Detalle",
            width: null,
            render: (value: PaginatePaymentsView) => (
                <>
                    <div
                        style={{
                            paddingLeft: "10px",
                            paddingRight: "10px",
                            paddingTop: "10px",
                            fontWeight: "bold",
                        }}
                    >
                        {value.clientName + " - " + value.serviceName}
                    </div>
                    <div
                        style={{
                            paddingLeft: "10px",
                            paddingRight: "10px",
                            color: "var(--gray-darkest)",
                        }}
                    >
                        {value.employeeName}
                    </div>
                    <div
                        style={{
                            paddingLeft: "10px",
                            paddingRight: "10px",
                            color: "var(--gray-dark)",
                        }}
                    >
                        {dayjs(value.createdAt).format("DD MMMM YYYY - HH:mm")}
                    </div>
                </>
            ),
        },
        {
            field: "price",
            title: "Importe",
            width: 50,
            render: (value: PaginatePaymentsView) => (
                <div
                    style={{
                        padding: "10px",
                        textAlign: "right",
                        color: value.price > 0 ? "var(--green-darkestX2)" : "var(--red)",
                    }}
                >
                    {formatPrice(value.price)}
                </div>
            ),
        },
        {
            field: "id",
            title: "",
            width: 64,
            render: (value: PaginatePaymentsView) => (
                <div
                    style={{
                        display: "flex",
                        justifyContent: "center",
                        alignContent: "center",
                        padding: "5px",
                    }}
                >
                    <IconButton
                        color="success"
                        sx={{ width: "32px", height: "32px" }}
                        onClick={() => {
                            setCreatePaymentData(value);
                            setDialogPayOneVisible(true);
                        }}
                    >
                        <CreatePaymentIcon />
                    </IconButton>
                </div>
            ),
        },
    ]);

    const [pageSize] = useState<number>(
        parseInt(
            process.env.NEXT_PUBLIC_DATAGRID_PAGE_SIZE
                ? process.env.NEXT_PUBLIC_DATAGRID_PAGE_SIZE
                : "10"
        )
    );
    const [payments, setPayments] = useState<PaginateNotPayedAppointmentsResult>();
    const paymentsRef = useRef(payments);
    const [reloadPayments, setReloadPayments] = useState<boolean>(false);
    const [isScrolled, setIsScrolled] = useState(false);
    const [forceMinimized, setForceMinimized] = useState(false);

    const isMinimized = forceMinimized || isScrolled;

    useEffect(() => {
        const handleScroll = (e: Event) => {
            const target = e.target as HTMLElement;
            if (target && target.scrollTop !== undefined) {
                if (target.clientHeight > 300) {
                    setIsScrolled(target.scrollTop > 50);
                }
            } else if ((target as unknown) === document || (target as unknown) === window) {
                setIsScrolled(window.scrollY > 50);
            }
        };

        window.addEventListener("scroll", handleScroll, { capture: true, passive: true });
        
        return () => {
            window.removeEventListener("scroll", handleScroll, { capture: true });
        };
    }, []);

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

        if (!createPaymentData) {
            return;
        }

        const creationData: CreatePaymentParams = {
            appointmentId: createPaymentData.appointmentId,
            amount: createPaymentData.price,
            method: paymentMethodId,
            status: CLIENT_ACCOUNT_MOVEMENT_STATUS.APPROVED,
            description: "Pago completo de la reserva",
            proccessDate: paymentProcessDateId,
            sessionUser: SessionInfo.userId,
        };

        eventHandler.setEventType(EVENT_TYPES.LOADING);
        createPayment(creationData)
            .then(() => {
                setDialogPayOneVisible(false);
                setCreatePaymentData(undefined);
                alert.showSuccess("Pago Creado Correctamente");
                setReloadPayments(true);
            })
            .catch((error) => {
                alert.showError(error.format());
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.CLEAR);
            });
    };

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

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

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

        if (clientIds && clientIds.length > 0) {
            filterData.clientIds = clientIds;
        }

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

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

        paginateNotPayedAppointments(filterData)
            .then((res) => {
                if (res.page > res.pages) {
                    const newPage = res.page - 1;
                    if (newPage > 0) {
                        loadNotPayedAppointments(newPage, pageSize);
                    }
                    return;
                }
                setPayments(res);
                setReloadPayments(false);
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.CLEAR);
            });
    };

    
    const generarReporte = async () => {
        eventHandler.setEventType(EVENT_TYPES.LOADING);
        try {
            const filterData: FindPaymentsParams = {
                companyId: id,
                sessionUser: SessionInfo.userId,
            };
            if (dateFrom) filterData.startDate = dateFrom.toDate();
            if (dateTo) filterData.endDate = dateTo.toDate();
            if (collaboratorId) filterData.employeeId = collaboratorId;
            if (clientIds && clientIds.length > 0) filterData.clientIds = clientIds;
            if (serviceId) filterData.serviceId = serviceId;
            if (methodId) filterData.method = methodId as any;

            const report = await GetNotPayedReport(filterData);
            
            const pdfMake = await import("pdfmake/build/pdfmake");
            const pdfFonts = (await import("pdfmake/build/vfs_fonts")) as any;
            pdfMake.vfs = pdfFonts.pdfMake ? pdfFonts.pdfMake.vfs : pdfFonts.vfs;
            
            let logoDataUrl = "";
            try {
                const response = await fetch("/favicon512.png");
                const blob = await response.blob();
                logoDataUrl = await new Promise((resolve) => {
                    const reader = new FileReader();
                    reader.onloadend = () => resolve(reader.result as string);
                    reader.readAsDataURL(blob);
                });
            } catch(e) {}

            const tableBody: any[] = [
                [
                    { text: "Cliente", bold: true, color: "#333333", fillColor: "#f5f5f5" },
                    { text: "Datos del Turno", bold: true, color: "#333333", fillColor: "#f5f5f5" },
                    { text: "Monto", bold: true, color: "#333333", fillColor: "#f5f5f5" }
                ]
            ];

            report.items.forEach(item => {
                tableBody.push([
                    item.clientName || "-",
                    { 
                        text: [
                            { text: `${item.serviceName || "-"}\n`, bold: true, fontSize: 11 },
                            `Prof: ${item.employeeName || "-"}\nFecha: ${dayjs(item.appointmentDate).format("DD/MM/YYYY HH:mm")} hs`
                        ],
                        fontSize: 10
                    },
                    { text: "$" + item.price.toLocaleString("es-AR"), alignment: "right" }
                ]);
            });

            // Add total row
            tableBody.push([
                { text: "TOTAL ADEUDADO", bold: true, colSpan: 2, alignment: "right" },
                {},
                { text: "$" + report.totalAmount.toLocaleString("es-AR"), bold: true, alignment: "right" }
            ]);

            const docDefinition: unknown = {
                content: [
                    {
                        columns: [
                            { text: "Reporte de Turnos Adeudados", fontSize: 18, bold: true, margin: [0, 0, 0, 10], width: '*' },
                            ...(logoDataUrl ? [{ image: logoDataUrl, width: 45, margin: [0, 0, 0, 10], alignment: 'right' }] : [])
                        ]
                    },
                    { text: `Filtros aplicados:`, bold: true, margin: [0, 0, 0, 5] },
                    { 
                        text: [
                            { text: "Clientes Seleccionados: ", bold: true },
                            `${clientIds.length > 0 ? clientIds.length : "Todos"}`
                        ],
                        margin: [0, 0, 0, 2] 
                    },
                    { 
                        text: [
                            { text: "Período: ", bold: true },
                            `${dateFrom ? dateFrom.format("DD/MM/YYYY") : "Inicio"} al ${dateTo ? dateTo.format("DD/MM/YYYY") : "Fin"}`
                        ],
                        margin: [0, 0, 0, 20] 
                    },
                    {
                        table: {
                            headerRows: 1,
                            widths: [120, "*", "auto"],
                            body: tableBody
                        },
                        layout: "lightHorizontalLines"
                    }
                ]
            };
            
            if ((window as unknown as { Android: any }).Android && (window as unknown as { Android: any }).Android.savePdf) {
                pdfMake.createPdf(docDefinition as any).getBase64((data: any) => {
                    (window as unknown as { Android: any }).Android?.savePdf(data, `reporte-adeudados.pdf`);
                });
            } else {
                pdfMake.createPdf(docDefinition as any).download(`reporte-adeudados.pdf`);
            }
        } catch (error: unknown) {
            alert.showError((error as { format?: () => string }).format ? (error as { format: () => string }).format() : "Error generando PDF");
        } finally {
            eventHandler.setEventType(EVENT_TYPES.CLEAR);
        }
    };

    const loadNotPayedAppointmentsTotal = () => {
        eventHandler.setEventType(EVENT_TYPES.LOADING);
        const filterData: FindPaymentsParams = {
            companyId: id,
            sessionUser: SessionInfo.userId,
        };

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

        if (clientIds && clientIds.length > 0) {
            filterData.clientIds = clientIds;
        }

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

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

        eventHandler.setEventType(EVENT_TYPES.LOADING);
        paginateNotPayedAppointmentsTotal(filterData)
            .then((res) => {
                setPaymentsTotal(res);
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.CLEAR);
            });
    };

    const handlePayAll = () => {
        if (!paymentMethodId) {
            alert.showError("Debe seleccionar un metodo de pago");
            return;
        }

        eventHandler.setEventType(EVENT_TYPES.LOADING);
        const filterData: FindPaymentsParams = {
            companyId: id,
            method: paymentMethodId,
            proccessDate: paymentProcessDateId,
            sessionUser: SessionInfo.userId,
        };

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

        if (clientIds && clientIds.length > 0) {
            filterData.clientIds = clientIds;
        }

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

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

        eventHandler.setEventType(EVENT_TYPES.LOADING);
        payNotPayedAppointments(filterData)
            .then(() => {
                alert.showSuccess("Pagos realizados con exito");
                setReloadPayments(true);
                setDialogPayVisible(false);
            })
            .catch((error) => {
                alert.showError(error.format());
            })
            .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(() => {
        const filter: FindServicesParams = {
            companyId: id,
        };
        filterObjects<FindServicesParams>("services/filter-all", filter).then((res) => {
            setServiceFilterData(res);
        });
    }, []);

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

    useEffect(() => {
        filter.setTitle("Filtrar Pagos");
        filter.clearFilterData();
        filter.setContent(
            <FilterContent
                collaboratorsData={collaboratorFilterData}
                setCollaboratorId={setCollaboratorId}
                servicesData={serviceFilterData}
                setServiceId={setServiceId}
                methodsData={methodFilterData}
                setMethodId={setMethodId}
                clientData={clientFilterData}
                setClientIds={setClientIds}
            />
        );
        filter.setOnFilter(() => { });

        return () => {
            bottomToolbar.clear();
        };
    }, [paymentsTotal, collaboratorFilterData, serviceFilterData, methodFilterData, clientFilterData, clientIds, collaboratorId, serviceId, methodId]);

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

    useEffect(() => {
        paymentsRef.current = payments;
    }, [payments]);

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

        if (paymentsRef.current) {
            loadPage = paymentsRef.current.page;
        }
        loadNotPayedAppointments(loadPage, pageSize);
        loadNotPayedAppointmentsTotal();
    }, [clientIds, collaboratorId, serviceId, methodId, dateFrom, dateTo, reloadPayments]);


    return (
        <>
            <Location />

            <SecureByPlan content={SECURE_CONTENTS.PAYMENTS} companyId={id}>
                <div style={{ maxWidth: "800px", margin: "0 auto", paddingBottom: "100px", marginTop: "0px" }}>
                    
                    {/* Top Status Card */}
                    <div style={{ position: "sticky", top: "70px", zIndex: 100, marginBottom: "50px", display: "flex", flexDirection: "column", background: "white", paddingBottom: "10px", paddingTop: "5px", margin: "0 -10px", paddingLeft: "10px", paddingRight: "10px" }}>


                    {/* Tabs Selector */}
                    <div style={{ display: "flex", justifyContent: "center", marginBottom: "15px" }}>
                        <ThemeProvider theme={turnosXpressTheme}>
                            <div style={{ 
                                display: "flex", 
                                background: "rgba(255,255,255,0.9)", 
                                backdropFilter: "blur(10px)",
                                borderRadius: "30px", 
                                padding: "5px",
                                boxShadow: "0 4px 15px rgba(0,0,0,0.05)"
                            }}>
                                <ButtonMaterial
                                    variant="text"
                                    onClick={() => goTo(`/admin/org/profile/${id}/payments`)}
                                    style={{ borderRadius: "25px", color: "#666", fontWeight: "bold", padding: "8px 25px" }}
                                >
                                    Pagados
                                </ButtonMaterial>
                                <ButtonMaterial 
                                    variant="contained" 
                                    style={{ borderRadius: "25px", boxShadow: "0 2px 8px rgba(0,0,0,0.1)", fontWeight: "bold", padding: "8px 25px" }}
                                >
                                    Adeudados
                                </ButtonMaterial>
                            </div>
                        </ThemeProvider>
                    </div>

                        <motion.div
                            layout
                            initial={{ opacity: 0, y: -20 }}
                            animate={{ 
                                opacity: 1, 
                                y: 0,
                                padding: isMinimized ? "25px 50px" : "40px 20px",
                                borderRadius: isMinimized ? "15px" : "20px"
                            }}
                            style={{
                                background: "linear-gradient(135deg, #FF416C 0%, #FF4B2B 100%)", // Red gradient for debts
                                color: "white",
                                textAlign: "center",
                                boxShadow: isMinimized ? "0 4px 15px rgba(0,0,0,0.3)" : "0 10px 30px rgba(0,0,0,0.15)",
                                position: "relative",
                                
                                display: "flex",
                                flexDirection: isMinimized ? "row" : "column",
                                alignItems: "center",
                                justifyContent: isMinimized ? "space-between" : "center",
                                transition: "box-shadow 0.3s ease"
                            }}
                        >
                            <IconButton
                                onClick={() => setForceMinimized(!forceMinimized)}
                                style={{ position: "absolute", top: "10px", left: "10px", color: "rgba(255,255,255,0.7)", zIndex: 10 }}
                                size="small"
                                title={forceMinimized ? "Maximizar" : "Minimizar"}
                            >
                                {forceMinimized ? <UnfoldMoreIcon /> : <UnfoldLessIcon />}
                            </IconButton>
                            <IconButton
                                onClick={() => filter.toggle()}
                                style={{ position: "absolute", top: "10px", right: "10px", color: "rgba(255,255,255,0.7)", zIndex: 10 }}
                                size="small"
                                title="Filtrar"
                            >
                                <FilterAltOutlinedIcon />
                            </IconButton>
                            <div style={{ position: "absolute", top: "-50px", right: "-50px", width: "150px", height: "150px", borderRadius: "50%", background: "rgba(255,255,255,0.05)" }}></div>
                            <div style={{ position: "absolute", bottom: "-30px", left: "-30px", width: "100px", height: "100px", borderRadius: "50%", background: "rgba(255,255,255,0.05)" }}></div>
                            
                            <motion.div 
                                animate={{ 
                                    fontSize: isMinimized ? "14px" : "16px",
                                    marginBottom: isMinimized ? "0px" : "10px"
                                }}
                                style={{ fontWeight: "bold", textTransform: "uppercase", letterSpacing: "2px", opacity: 0.9 }}
                            >
                                Total Adeudado
                            </motion.div>
                            <motion.div 
                                animate={{ 
                                    fontSize: isMinimized ? "24px" : "56px",
                                    margin: isMinimized ? "0px" : "10px 0"
                                }}
                                style={{ fontWeight: "900" }}
                            >
                                {formatPrice(paymentsTotal)}
                            </motion.div>
                            
                            {!isMinimized && (
                                <motion.div 
                                    initial={{ opacity: 0 }}
                                    animate={{ opacity: 1 }}
                                    exit={{ opacity: 0 }}
                                    style={{ marginTop: "15px" }}
                                >
                                    <div style={{ marginBottom: "15px", width: "250px", maxWidth: "100%" }}>
                                        <TextRangeDateModern
                            label="Período"
                            dateFrom={dateFrom}
                            dateTo={dateTo}
                            setDateFrom={setDateFrom}
                            setDateTo={setDateTo}
                        />
                                    </div>
                                    <div style={{ display: "flex", gap: "10px", alignItems: "center", flexWrap: "wrap" }}>
                                        <ButtonMaterial
                                            variant="contained"
                                            startIcon={<PayIcon />}
                                            onClick={() => setDialogPayVisible(true)}
                                            style={{
                                                background: "white",
                                                color: "#FF4B2B",
                                                fontWeight: "bold",
                                                borderRadius: "20px",
                                                padding: "8px 20px",
                                                textTransform: "none"
                                            }}
                                        >
                                            Pagar Todos
                                        </ButtonMaterial>
                                        <ButtonMaterial
                                            variant="outlined"
                                            onClick={generarReporte}
                                            style={{
                                                color: "white",
                                                borderColor: "rgba(255,255,255,0.5)",
                                                fontWeight: "bold",
                                                borderRadius: "20px",
                                                padding: "8px 20px",
                                                textTransform: "none"
                                            }}
                                        >
                                            <PictureAsPdfIcon style={{ fontSize: "18px", marginRight: "5px" }} /> PDF
                                        </ButtonMaterial>
                                    </div>
                                </motion.div>
                            )}
                        </motion.div>
                    </div>

                    {/* Dynamic Spacer for layout shift */}
                    <div style={{ height: isMinimized ? "150px" : "0px", transition: "height 0.3s ease" }}></div>

                    {/* Payments List */}
                    <div style={{ display: "flex", flexDirection: "column", gap: "15px", padding: "15px 10px 0 10px" }}>
                        <AnimatePresence>
                            {payments?.data.map((payment, index) => (
                                <motion.div
                                    key={payment.id}
                                    initial={{ opacity: 0, y: 20 }}
                                    animate={{ opacity: 1, y: 0 }}
                                    transition={{ delay: index * 0.05 }}
                                    style={{
                                        background: "white",
                                        borderRadius: "15px",
                                        padding: "20px",
                                        display: "flex",
                                        alignItems: "center",
                                        justifyContent: "space-between",
                                        boxShadow: "0 4px 15px rgba(0,0,0,0.05)",
                                        borderLeft: `4px solid var(--red)`
                                    }}
                                >
                                    <div style={{ display: "flex", alignItems: "center", gap: "15px" }}>
                                        <div style={{ 
                                            background: "rgba(255, 75, 43, 0.1)", 
                                            padding: "10px", 
                                            borderRadius: "12px",
                                            display: "flex",
                                            alignItems: "center",
                                            justifyContent: "center",
                                            color: "var(--red)"
                                        }}>
                                            <CreditCardIcon />
                                        </div>
                                        <div>
                                            <div style={{ fontWeight: "800", fontSize: "15px", color: "#333", marginBottom: "4px" }}>{payment.clientName}</div>
                                            <div style={{ fontWeight: "700", fontSize: "13px", color: "var(--purple)", marginBottom: "4px" }}>{payment.serviceName}</div>
                                            <div style={{ fontSize: "12px", color: "#888" }}>
                                                {dayjs(payment.createdAt).format("DD MMMM YYYY • HH:mm")} • {payment.employeeName}
                                            </div>
                                        </div>
                                    </div>
                                    <div style={{ display: "flex", alignItems: "center", gap: "15px" }}>
                                        <div style={{ fontWeight: "900", fontSize: "16px", color: "var(--red)" }}>
                                            {formatPrice(payment.price)}
                                        </div>
                                        <IconButton 
                                            color="success" 
                                            onClick={() => {
                                                setCreatePaymentData(payment);
                                                setDialogPayOneVisible(true);
                                            }}
                                            sx={{ background: "rgba(46, 204, 113, 0.1)" }}
                                        >
                                            <CreatePaymentIcon />
                                        </IconButton>
                                    </div>
                                </motion.div>
                            ))}
                            
                            {(!payments?.data || payments.data.length === 0) && (
                                <div style={{ textAlign: "center", padding: "50px", color: "#aaa" }}>
                                    <CreditCardIcon sx={{ fontSize: "60px", opacity: 0.2, marginBottom: "15px" }} />
                                    <div style={{ fontSize: "18px", fontWeight: "bold" }}>No hay pagos adeudados</div>
                                    <div style={{ fontSize: "14px", marginTop: "5px" }}>Intenta ajustar los filtros de fecha</div>
                                </div>
                            )}
                        </AnimatePresence>
                    </div>

                    {/* Pagination */}
                    {payments && payments.pages > 1 && (
                        <div style={{ display: "flex", justifyContent: "center", marginTop: "40px" }}>
                            <Pagination
                                count={payments.pages}
                                page={payments.page}
                                onChange={(e, page) => loadNotPayedAppointments(page, pageSize)}
                                color="primary"
                            />
                        </div>
                    )}

                    {/* Dialogs */}
                    <DialogWindow visible={dialogPayVisible} setVisible={setDialogPayVisible}>
                        <>
                            <DialogContent
                                style={{
                                    maxWidth: "500px",
                                    minWidth: "300px",
                                    margin: "auto",
                                }}
                            >
                                <>
                                    <TextObjectFilter
                                        placeholder="Método de pago"
                                        content={paymentMethodFilterContent}
                                        data={paymentMethhodFilterData}
                                        onChange={(id) => {
                                            setPaymentMethodId(
                                                id as CLIENT_ACCOUNT_PAYMENT_METHODS
                                            );
                                        }}
                                    />
                                    <TextObjectFilter
                                        placeholder="Fecha de pago"
                                        content={paymentProccessDateFilterContent}
                                        data={paymentProcessDateFilterData}
                                        onChange={(id) => {
                                            setPaymentProcessDateId(id as PAYMENT_PROCCESS_DATE);
                                        }}
                                    />
                                </>
                            </DialogContent>
                            <DialogActions>
                                <ButtonMaterial
                                    variant="contained"
                                    color="primary"
                                    onClick={handlePayAll}
                                >
                                    Pagar
                                </ButtonMaterial>
                                <ButtonMaterial
                                    variant="contained"
                                    color="secondary"
                                    onClick={() => {
                                        setDialogPayVisible(false);
                                    }}
                                >
                                    Cancelar
                                </ButtonMaterial>
                            </DialogActions>
                        </>
                    </DialogWindow>

                    <DialogWindow visible={dialogPayOneVisible} setVisible={setDialogPayOneVisible}>
                        <>
                            <DialogContent
                                style={{
                                    maxWidth: "500px",
                                    minWidth: "300px",
                                    margin: "auto",
                                }}
                            >
                                <>
                                    <TextObjectFilter
                                        placeholder="Método de pago"
                                        content={paymentMethodFilterContent}
                                        data={paymentMethhodFilterData}
                                        onChange={(id) => {
                                            setPaymentMethodId(
                                                id as CLIENT_ACCOUNT_PAYMENT_METHODS
                                            );
                                        }}
                                    />
                                    <TextObjectFilter
                                        placeholder="Fecha de pago"
                                        content={paymentProccessDateFilterContent}
                                        data={paymentProcessDateFilterData}
                                        onChange={(id) => {
                                            setPaymentProcessDateId(id as PAYMENT_PROCCESS_DATE);
                                        }}
                                    />
                                </>
                            </DialogContent>
                            <DialogActions>
                                <ButtonMaterial
                                    variant="contained"
                                    color="primary"
                                    onClick={createPaymentHandler}
                                >
                                    Pagar
                                </ButtonMaterial>
                                <ButtonMaterial
                                    variant="contained"
                                    color="secondary"
                                    onClick={() => {
                                        setDialogPayOneVisible(false);
                                    }}
                                >
                                    Cancelar
                                </ButtonMaterial>
                            </DialogActions>
                        </>
                    </DialogWindow>

                </div>
            </SecureByPlan>
        </>
    );
}
