"use client";
import { useParams } from "next/navigation";
import { useState, useEffect, useRef } from "react";
import Location from "@components/Location/Location";
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 { IconButton } from "@mui/material";
import ButtonMaterial from "@mui/material/Button";
import {
    FindPaymentsParams,
    PaginatePaymentsView,
    PaginatePaymentsViewParams,
    PaginatePaymentsViewResults,
    PAYMENT_METHODS,
    paymentMethods,
} from "@core/Models/Payments.model";
import dayjs, { Dayjs } from "dayjs";
import { formatPrice } from "@core/app/helpers/Numbers";
import { loadPaymentsView, loadPaymentsViewTotal, deletePayment } from "../Org.Service";
import { getPaymentIcon } from "@core/app/components/PaymentIcons/PaymentIcons";
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 { FindServicesParams } from "@core/Models/Service.model";
import { FindClientsParams } from "@core/Models/Clients.model";
import TextRangeDateModern from "@core/app/components/TextRangeDateModern/TextRangeDateModern";
import { useNavigation } from "@core/app/hooks/goto";
import DeleteIcon from "@mui/icons-material/DeleteOutlineOutlined";
import PictureAsPdfIcon from "@mui/icons-material/PictureAsPdf";
import { useAlert } from "@core/Store/Alert.Store";
import { useConfirmStore } from "@core/Store/Confirm.Store";
import { GetPaymentsReport } from "../Org.Service";
import SecureByPlan, { SECURE_CONTENTS } from "@core/app/components/SecureByPlan/SecureByPlan";
import { motion, AnimatePresence } from "motion/react";
import Pagination from "@mui/material/Pagination";
import SearchOffIcon from "@mui/icons-material/SearchOff";
import UnfoldLessIcon from "@mui/icons-material/UnfoldLess";
import UnfoldMoreIcon from "@mui/icons-material/UnfoldMore";
import FilterAltOutlinedIcon from "@mui/icons-material/FilterAltOutlined";

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;
    clientIds: string[];
}

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="Cliente"
                content={clientFilterContent}
                data={props.clientData}
                onChange={(ids) => props.setClientIds(ids)}
                selectedIds={props.clientIds}
            />
            <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 OrganizationEdit() {
    const data = useParams<UrlData>();
    const id = data.id;
    const location = useLocationStore();
    const eventHandler = useEventHandlerStore();
    const SessionInfo = useSessionStore();
    const filter = useFilterStore();
    const alert = useAlert();
    const confirm = useConfirmStore();
    const { goTo } = useNavigation();

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

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

    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 [pageSize] = useState<number>(10);
    const [payments, setPayments] = useState<PaginatePaymentsViewResults>();
    const paymentsRef = useRef(payments);
    const [isScrolled, setIsScrolled] = useState(false);
    const [forceMinimized, setForceMinimized] = useState(false);
    const sentinelRef = useRef<HTMLDivElement>(null);

    const isMinimized = forceMinimized || isScrolled;

    const generarReporte = async () => {
        try {

            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;

            const report = await GetPaymentsReport({
                companyId: id,
                startDate: dateFrom.toDate(),
                endDate: dateTo.toDate(),
                clientIds: clientIds.length > 0 ? clientIds : undefined,
                serviceId: serviceId ? serviceId : undefined,
                employeeId: collaboratorId ? collaboratorId : undefined,
                method: methodId ? (methodId as any) : undefined,
                sessionUser: SessionInfo.userId
            });

            if (!report.items || report.items.length === 0) {
                alert.showError("No hay datos para generar el reporte");
                return;
            }

            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\nMétodo: ${item.method || "-"}`
                        ],
                        fontSize: 10
                    },
                    { text: "$" + item.price.toLocaleString("es-AR"), alignment: "right" }
                ]);
            });

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

            const docDefinition: unknown = {
                content: [
                    {
                        columns: [
                            { text: "Reporte de Cobros Procesados", 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-procesados.pdf`);
                });
            } else {
                pdfMake.createPdf(docDefinition as any).download(`reporte-procesados.pdf`);
            }
        } catch (error: unknown) {
            console.error(error);
            alert.showError((error as { format?: () => string }).format ? (error as { format: () => string }).format() : "Error generando PDF");
        }
    };

    useEffect(() => {
        
    const handleScroll = (e: Event) => {
            const target = e.target as HTMLElement;
            // Check if it's a DOM element scrolling
            if (target && target.scrollTop !== undefined) {
                // Ignore small scroll containers like dropdowns by ensuring the container is large
                if (target.clientHeight > 300) {
                    setIsScrolled(target.scrollTop > 50);
                }
            } else if ((target as unknown) === document || (target as unknown) === window) {
                // If it's the window/document scrolling
                setIsScrolled(window.scrollY > 50);
            }
        };

        // Use capture: true to catch all scroll events in the app regardless of where they happen
        window.addEventListener("scroll", handleScroll, { capture: true, passive: true });
        
        return () => {
            window.removeEventListener("scroll", handleScroll, { capture: true });
        };
    }, []);

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

        const filterData: PaginatePaymentsViewParams = {
            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;
        if (methodId) filterData.method = methodId as PAYMENT_METHODS;

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

    const loadPaymentsTotal = () => {
        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;
        if (methodId) filterData.method = methodId as PAYMENT_METHODS;

        loadPaymentsViewTotal(filterData)
            .then((res) => setPaymentsTotal(res))
            .catch(() => setPaymentsTotal(0));
    };

    const deletePaymentHandler = (paymentId: string) => {
        if (!paymentId || !SessionInfo.userId) return;

        eventHandler.setEventType(EVENT_TYPES.LOADING);
        deletePayment({
            id: paymentId,
            sessionUser: SessionInfo.userId,
        })
            .then(() => {
                alert.showSuccess("Pago eliminado");
                setReloadPayments(true);
            })
            .catch((error) => alert.showError(error.format()))
            .finally(() => eventHandler.setEventType(EVENT_TYPES.CLEAR));
    };

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

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

        const sFilter: FindServicesParams = { companyId: id };
        filterObjects<FindServicesParams>("services/filter-all", sFilter).then((res) => setServiceFilterData(res));

        setMethodFilterData(paymentMethods.map((m) => ({ id: m.id, text: m.name, name: m.name, image: "" })));
    }, []);

    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}
                                clientIds={clientIds}
            />
        );
        filter.setOnFilter(() => { });
    }, [collaboratorFilterData, serviceFilterData, methodFilterData, clientFilterData]);

    useEffect(() => {
        eventHandler.setEventType(EVENT_TYPES.SLEEP);
        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: "Pagos", icon: <PaymentsIcon sx={{ fontSize: "32px", mr: "10px" }} /> });
    }, []);

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

    useEffect(() => {
        const loadPage = paymentsRef.current?.page || 1;
        loadPayments(loadPage, pageSize);
        loadPaymentsTotal();
    }, [clientIds, collaboratorId, serviceId, methodId, dateFrom, dateTo, reloadPayments]);

    const dataList = payments?.data || [];

    return (
        <>
            <Location />

            <SecureByPlan content={SECURE_CONTENTS.PAYMENTS} companyId={id}>
                <div style={{ maxWidth: "800px", margin: "0 auto", paddingBottom: "100px", marginTop: "0px" }}>
                    
                    {/* Sentinel element to detect scroll */}
                    <div ref={sentinelRef} style={{ height: "1px", width: "100%" }}></div>

                    {/* 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="contained" 
                                    style={{ borderRadius: "25px", boxShadow: "0 2px 8px rgba(0,0,0,0.1)", fontWeight: "bold", padding: "8px 25px" }}
                                >
                                    Pagados
                                </ButtonMaterial>
                                <ButtonMaterial
                                    variant="text"
                                    onClick={() => goTo(`/admin/org/profile/${id}/payments/not-payed`)}
                                    style={{ borderRadius: "25px", color: "#666", 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, #4b6cb7 0%, #182848 100%)",
                                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 Recaudado
                            </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={{ fontSize: "14px", opacity: 0.8 }}
                                >
                                    <div style={{ display: "flex", gap: "10px", alignItems: "center", flexWrap: "wrap", justifyContent: "center", marginTop: "10px" }}>
                                        <div style={{ width: "250px", maxWidth: "100%" }}>
                                            <TextRangeDateModern
                                                label="Período"
                                                dateFrom={dateFrom}
                                                dateTo={dateTo}
                                                setDateFrom={setDateFrom}
                                                setDateTo={setDateTo}
                                            />
                                        </div>
                                        <ButtonMaterial
                                            variant="outlined"
                                            onClick={generarReporte}
                                            style={{
                                                color: "white",
                                                borderColor: "rgba(255,255,255,0.5)",
                                                fontWeight: "bold",
                                                borderRadius: "20px",
                                                padding: "8px 20px",
                                                textTransform: "none",
                                                height: "56px"
                                            }}
                                        >
                                            <PictureAsPdfIcon style={{ fontSize: "18px", marginRight: "5px" }} /> PDF
                                        </ButtonMaterial>
                                    </div>
                                </motion.div>
                            )}
                        </motion.div>
                    </div>

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

                    {/* Payments List */}
                    <div style={{ display: "flex", flexDirection: "column", gap: "12px", paddingTop: "15px" }}>
                        {dataList.length > 0 ? (
                            <AnimatePresence>
                                {dataList.map((payment, index) => (
                                    <motion.div
                                        key={payment.id}
                                        initial={{ opacity: 0, y: 20 }}
                                        animate={{ opacity: 1, y: 0 }}
                                        exit={{ opacity: 0, scale: 0.95 }}
                                        transition={{ duration: 0.2, delay: index * 0.03 }}
                                        style={{
                                            display: "flex",
                                            flexDirection: "row",
                                            alignItems: "center",
                                            justifyContent: "space-between",
                                            backgroundColor: "#fff",
                                            borderRadius: "15px",
                                            padding: "16px 20px",
                                            boxShadow: "0 4px 12px rgba(0,0,0,0.05)",
                                            borderLeft: "5px solid #28a745",
                                            position: "relative"
                                        }}
                                    >
                                        <div style={{ display: "flex", alignItems: "center", gap: "15px", flex: 1 }}>
                                            <div style={{ 
                                                width: "50px", 
                                                height: "50px", 
                                                borderRadius: "12px", 
                                                backgroundColor: "rgba(40, 167, 69, 0.1)", 
                                                display: "flex", 
                                                alignItems: "center", 
                                                justifyContent: "center",
                                                color: "#28a745"
                                            }}>
                                                {getPaymentIcon(payment.method)}
                                            </div>
                                            <div style={{ flex: 1 }}>
                                                <div style={{ fontSize: "16px", fontWeight: "bold", color: "#333", marginBottom: "2px" }}>
                                                    {payment.clientName}
                                                </div>
                                                <div style={{ fontSize: "14px", color: "var(--wine-dark)", fontWeight: "bold", marginBottom: "4px" }}>
                                                    {payment.serviceName}
                                                </div>
                                                <div style={{ display: "flex", gap: "10px", fontSize: "12px", color: "#888" }}>
                                                    <span>{dayjs(payment.createdAt).format("DD MMMM YYYY • HH:mm")}</span>
                                                    <span>•</span>
                                                    <span>{payment.employeeName}</span>
                                                </div>
                                            </div>
                                        </div>
                                        <div style={{ display: "flex", alignItems: "center", gap: "15px" }}>
                                            <div style={{
                                                fontSize: "20px",
                                                fontWeight: "900",
                                                color: "#28a745",
                                                textAlign: "right"
                                            }}>
                                                +{formatPrice(payment.price)}
                                            </div>
                                            <IconButton
                                                color="error"
                                                size="small"
                                                onClick={() => {
                                                    confirm.show(
                                                        "¿Estás seguro que quieres eliminar el pago de " + payment.clientName + "?",
                                                        () => deletePaymentHandler(payment.id),
                                                        () => { }
                                                    );
                                                }}
                                                sx={{ 
                                                    backgroundColor: "rgba(220, 53, 69, 0.05)",
                                                    "&:hover": { backgroundColor: "rgba(220, 53, 69, 0.15)" } 
                                                }}
                                            >
                                                <DeleteIcon fontSize="small" />
                                            </IconButton>
                                        </div>
                                    </motion.div>
                                ))}
                            </AnimatePresence>
                        ) : (
                            <motion.div 
                                initial={{ opacity: 0, scale: 0.9 }} 
                                animate={{ opacity: 1, scale: 1 }}
                                style={{ textAlign: "center", padding: "60px 20px", backgroundColor: "#fff", borderRadius: "15px", border: "1px dashed #ccc" }}
                            >
                                <SearchOffIcon sx={{ fontSize: "64px", color: "#ccc", marginBottom: "15px" }} />
                                <h2 style={{ margin: 0, color: "#999" }}>Sin Pagos</h2>
                                <p style={{ color: "#aaa" }}>No se encontraron pagos registrados para este período.</p>
                            </motion.div>
                        )}
                    </div>

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