import "./report-form.css";
import { useState, useEffect } from "react";
import useCategories from "./hooks/useCategories";
import useSubCategories from "./hooks/useSubCategories";
import useReports from "./hooks/useReport";
import useHistory from "./hooks/useHistory";
import useUpdateEditPermission from "./hooks/useUpdatePermission";
import Modal from "../../ui/modal/modal";
import regions from "./resources/regions.json";

import useSpecificReport from "./hooks/useSpecificReport";
import useGetConfigurations from "../configuration/hooks/useGetConfigurations"

// obtener usuario y prefijo del localStorage
const loginResponse = localStorage.getItem("loginResponse");
const user = loginResponse ? JSON.parse(loginResponse).user : null;
const tablePrefix = user?.table_prefix;
const companyId = user?.company_nit;

export default function ReportForm() {
    const { fetchSpecificReport, data: specificData, loading: specificLoading } = useSpecificReport();
    const [openSpecificModal, setOpenSpecificModal] = useState(false);
    const { data: configData, loading: loadingConfig } = useGetConfigurations(tablePrefix);


    const { categorias, loading: loadingCats, error: errorCats } = useCategories(tablePrefix);
    const { subCategories, loading: loadingSubs, error: errorSubs } = useSubCategories(tablePrefix);
    const { sendReports, loading: sending, error: sendError, response } = useReports();
    const { fetchReportHistory, data: historyData } = useHistory();
    const { updateEditPermission } = useUpdateEditPermission();

    useEffect(() => {
        if (tablePrefix && companyId) {
            fetchReportHistory({ table_prefix: tablePrefix, company_nit: companyId });
        }
    }, [tablePrefix, companyId]);

    // Estado del modal
    const [openModal, setOpenModal] = useState(false);
    const [modalData, setModalData] = useState({ year: null, month: null });

    const handleOpenModal = (year, month) => {
        setModalData({ year, month });
        setOpenModal(true);
    };
    const handleCloseModal = () => setOpenModal(false);

    const handleConfirmPermission = async () => {
        try {
            await updateEditPermission({
                table_prefix: tablePrefix,
                company_nit: companyId,
                year: modalData.year,
                month: modalData.month
            });
            alert(`Se solicitó permiso de edición para ${modalData.month}/${modalData.year}`);
            handleCloseModal();
            fetchReportHistory({ table_prefix: tablePrefix, company_nit: companyId });
        } catch (err) {
            alert("Error solicitando permiso de edición");
        }
    };

    const handleViewSpecificReport = async () => {
        try {
            const report = await fetchSpecificReport({
                table_prefix: tablePrefix,
                company_nit: companyId,
                year: modalData.year,
                month: modalData.month,
            });

            console.log("Reporte específico recibido:", report);
            setOpenSpecificModal(true);
        } catch (err) {
            alert("Error obteniendo el reporte específico");
        }
    };
    // Función para obtener el nombre de la región
    const getRegionName = (regionId) => {
        const region = regiones.find(r => r.id === Number(regionId));
        return region ? region.nombre : "Desconocida";
    };

    // Función para obtener el nombre de la categoría
    const getCategoryName = (catId) => {
        const cat =
            configData?.categories?.find(c => c.id === Number(catId)) ||
            categorias.find(c => c.id === Number(catId));
        return cat ? cat.name : `ID ${catId}`;
    };

    // Función para obtener el nombre de la subcategoría
    const getSubCategoryName = (subId) => {
        const sub =
            configData?.subcategories?.find(s => s.id === Number(subId)) ||
            subCategories.find(s => s.id === Number(subId));
        return sub ? sub.name : `ID ${subId}`;
    };



    // Calcular sumatorias de Colombia y de todas las regiones
    const calcularComparativo = () => {
        const resumen = categorias.map((cat) => {
            const subs = subCategories.filter((s) => s.category_id === cat.id);

            // Sumatoria nacional (Colombia)
            const totalColombia = subs.reduce(
                (acc, sub) => {
                    const valores = data?.[0]?.[cat.id]?.[sub.id] || {};
                    acc.produccion += Number(valores.produccion || 0);
                    acc.sales_cop += Number(valores.sales_cop || 0);
                    acc.sales_gal += Number(valores.sales_gal || 0);
                    return acc;
                },
                { produccion: 0, sales_cop: 0, sales_gal: 0 }
            );

            // Sumatoria regional (todas las regiones excepto id=0 y 6)
            const totalRegiones = subs.reduce(
                (acc, sub) => {
                    regiones
                        .filter((r) => r.id !== 0 && r.id !== 6)
                        .forEach((region) => {
                            const valores = data?.[region.id]?.[cat.id]?.[sub.id] || {};
                            acc.ventasPesos += Number(valores.ventasPesos || 0);
                            acc.ventasVolumen += Number(valores.ventasVolumen || 0);
                        });
                    return acc;
                },
                { ventasPesos: 0, ventasVolumen: 0 }
            );

            return { cat, totalColombia, totalRegiones };
        });

        return resumen;
    };

    const [checkedCells, setCheckedCells] = useState({});


    const handleCheck = (catId, subId, field, checked) => {
        setCheckedCells((prev) => ({
            ...prev,
            [`col-${catId}-${subId}-${field}`]: checked,
        }));
    };

    const allChecked = categorias.every((cat) => {
        const subs = subCategories.filter((s) => s.category_id === cat.id);
        return subs.every((sub) =>
            ["produccion", "sales_cop", "sales_gal"].every((field) =>
                checkedCells[`col-${cat.id}-${sub.id}-${field}`]
            )
        );
    });


    const regiones = [
        { id: 0, nombre: "Colombia" },
        { id: 1, nombre: "Caribe" },
        { id: 2, nombre: "Pacífico" },
        { id: 3, nombre: "Andina" },
        { id: 4, nombre: "Orinoquía" },
        { id: 5, nombre: "Amazonía" },
        { id: 6, nombre: "Revisar" }
    ];

    const nombresRegiones = regiones
        .filter(r => r.id !== 0 && r.id !== 6)
        .map(r => r.nombre);

    const textoRegiones = nombresRegiones.length > 1
        ? `${nombresRegiones.slice(0, -1).join(', ')} y ${nombresRegiones.slice(-1)}`
        : nombresRegiones[0];


    const formatMiles = (valor) => {
        if (!valor && valor !== 0) return "";
        return new Intl.NumberFormat("es-CO").format(valor);
    };

    const [selectedDate, setSelectedDate] = useState({
        year: new Date().getFullYear(),
        month: new Date().getMonth() + 1,
    });

    const [showForm, setShowForm] = useState(false);
    const handleOpenForm = () => {
        setShowForm(true);
        window.scrollTo({ top: 0, behavior: 'smooth' });
    };

    const [data, setData] = useState({});
    const [active, setActive] = useState(regiones[0]);
    const [selectedRegion, setSelectedRegion] = useState(regiones[0]);

    const handleSelectedRegion = (region) => {
        setActive(region);
        setSelectedRegion(region);
    };

    const regionesData = regions.colombia.regiones;

    const regionActiva = regionesData.find(r => r.id_region === active.id);
    const departamentosActivos = regionActiva ? Object.values(regionActiva.departamentos) : [];

    useEffect(() => {
        if (categorias.length > 0 && subCategories.length > 0) {
            const initData = regiones.reduce((acc, region) => {
                acc[region.id] = categorias.reduce((catAcc, cat) => {
                    const subs = subCategories.filter((s) => s.category_id === cat.id);
                    catAcc[cat.id] = subs.reduce((subAcc, sub) => {
                        subAcc[sub.id] = {
                            produccion: "",
                            ventasPesos: "",
                            ventasVolumen: "",
                            sales_cop: "",
                            sales_gal: "",
                        };
                        return subAcc;
                    }, {});
                    return catAcc;
                }, {});
                return acc;
            }, {});
            setData(initData);
        }
    }, [categorias, subCategories]);

    const handleChange = (regionId, categoriaId, subcategoriaId, field, value) => {
        setData((prev) => ({
            ...prev,
            [regionId]: {
                ...prev[regionId],
                [categoriaId]: {
                    ...prev[regionId][categoriaId],
                    [subcategoriaId]: {
                        ...prev[regionId][categoriaId][subcategoriaId],
                        [field]: value,
                    },
                },
            },
        }));
    };

    const handleSendReports = async () => {
        const regionReports = [];
        const countryReports = [];

        regiones
            .filter((r) => r.id !== 6)
            .forEach((region) => {
                const catData = data[region.id];
                if (!catData) return;

                Object.keys(catData).forEach((catId) => {
                    const subData = catData[catId];
                    Object.keys(subData).forEach((subId) => {
                        const values = subData[subId];

                        if (region.id === 0) {
                            countryReports.push({
                                year: selectedDate.year,
                                month: selectedDate.month,
                                category_id: Number(catId),
                                subcategory_id: Number(subId),
                                produccion: Number(values.produccion || 0),
                                sales_cop: Number(values.sales_cop || 0),
                                sales_gal: Number(values.sales_gal || 0),
                            });
                        } else {
                            regionReports.push({
                                year: selectedDate.year,
                                month: selectedDate.month,
                                category_id: Number(catId),
                                subcategory_id: Number(subId),
                                region: region.id,
                                produccion: Number(values.produccion || 0),
                                ventasPesos: Number(values.ventasPesos || 0),
                                ventasVolumen: Number(values.ventasVolumen || 0),
                            });
                        }
                    });
                });
            });

        if (countryReports.length > 0) {
            await sendReports({
                tablePrefix,
                companyId,
                reportType: "country",
                reports: countryReports,
            });
        }

        if (regionReports.length > 0) {
            await sendReports({
                tablePrefix,
                companyId,
                reportType: "region",
                reports: regionReports,
            });
        }

        if (!sendError) {
            alert("Reportes enviados correctamente (nacional y regional)");
        }
    };

    if (!showForm) {
        return (
            <>
                {/* Modal para solicitar permisos */}
                <Modal isOpen={openModal}>
                    <div className="create-edit-request">
                        <h3>¿Deseas solicitar permisos de edición?</h3>
                        <p>
                            Esto permitirá volver a editar el reporte de{" "}
                            <strong>{modalData.month}/{modalData.year}</strong>.
                        </p>
                        <div className="modal-actions">
                            <button onClick={handleViewSpecificReport}>Ver histórico de reporte</button>
                            <button onClick={handleConfirmPermission}>Confirmar</button>
                            <button onClick={handleCloseModal}>Cancelar</button>
                        </div>
                    </div>
                </Modal>

                {/* Modal para ver reporte específico */}
                <Modal isOpen={openSpecificModal}>
                    <div className="specific-report-modal">
                        <h2>Reporte de {modalData.month}/{modalData.year}</h2>

                        {specificLoading && <p>Cargando reporte...</p>}

                        {!specificLoading && specificData && (
                            <>
                                <p><strong>Total registros:</strong> {specificData.total}</p>

                                {/* Reportes Regionales */}
                                {specificData.region_reports > 0 && (
                                    <div className="report-section">
                                        <h3>Reportes Regionales</h3>
                                        <table className="resume-table">
                                            <thead>
                                                <tr>
                                                    <th>Región</th>
                                                    <th>Categoría</th>
                                                    <th>Subcategoría</th>
                                                    <th>Producción</th>
                                                    <th>Ventas (COP)</th>
                                                    <th>Ventas (Volumen)</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                {specificData.data
                                                    .filter((r) => r.report_type === "region")
                                                    .map((r) => (
                                                        <tr key={`region-${r.id}`}>
                                                            <td>{getRegionName(r.region)}</td>
                                                            <td>{getCategoryName(r.category_id)}</td>
                                                            <td>{getSubCategoryName(r.subcategory_id)}</td>
                                                            <td>{formatMiles(r.produccion)}</td>
                                                            <td>{formatMiles(r.ventas_pesos)}</td>
                                                            <td>{formatMiles(r.ventas_volumen)}</td>
                                                        </tr>
                                                    ))}
                                            </tbody>
                                        </table>
                                    </div>
                                )}

                                {/* Reporte Nacional */}
                                {specificData.country_reports > 0 && (
                                    <div className="report-section">
                                        <h3>Reporte Nacional (Colombia)</h3>
                                        <table className="resume-table">
                                            <thead>
                                                <tr>
                                                    <th>Categoría</th>
                                                    <th>Subcategoría</th>
                                                    <th>Producción</th>
                                                    <th>Ventas (COP)</th>
                                                    <th>Ventas (Volumen)</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                {specificData.data
                                                    .filter((r) => r.report_type === "country")
                                                    .map((r) => (
                                                        <tr key={`country-${r.id}`}>
                                                            <td>{getCategoryName(r.category_id)}</td>
                                                            <td>{getSubCategoryName(r.subcategory_id)}</td>
                                                            <td>{formatMiles(r.produccion)}</td>
                                                            <td>{formatMiles(r.ventas_pesos ?? "-")}</td>
                                                            <td>{formatMiles(r.ventas_volumen ?? "-")}</td>
                                                        </tr>
                                                    ))}
                                            </tbody>
                                        </table>
                                    </div>
                                )}
                            </>
                        )}

                        {!specificLoading && !specificData && (
                            <p>No hay datos disponibles para este mes.</p>
                        )}

                        <div className="modal-actions">
                            <button onClick={() => setOpenSpecificModal(false)}>Cerrar</button>
                        </div>
                    </div>
                </Modal>



                <div className="report-date-selection">
                    <div className="report-date-title">Seleccionar mes y año del reporte</div>
                    <div className="year-buttons-container">
                        {[2019, 2020, 2021, 2022, 2023, 2024, 2025].map((year) => (
                            <div key={year} className="year-block">
                                <h3>{year}</h3>
                                <div className="months-grid">
                                    {[
                                        "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio",
                                        "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre",
                                    ].map((mes, i) => {
                                        const monthNum = i + 1;
                                        const isDisabled =
                                            Array.isArray(historyData?.history) &&
                                            historyData.history.some(
                                                (r) => r.year === year && r.month === monthNum
                                            );

                                        return (
                                            <button
                                                key={`${year}-${monthNum}`}
                                                className={`month-button 
                                                    ${selectedDate.year === year && selectedDate.month === monthNum ? "selected" : ""}
                                                    ${isDisabled ? "disabled" : ""}
                                                `}
                                                onClick={() => {
                                                    if (isDisabled) {
                                                        handleOpenModal(year, monthNum);
                                                    } else {
                                                        setSelectedDate({ year, month: monthNum });
                                                    }
                                                }}
                                            >
                                                {mes}
                                            </button>
                                        );
                                    })}
                                </div>
                            </div>
                        ))}
                    </div>
                    <button
                        className="continue-button"
                        onClick={handleOpenForm}
                        disabled={!selectedDate.year || !selectedDate.month}
                    >
                        Continuar
                    </button>
                </div>
            </>
        );
    }

    if (loadingCats || loadingSubs) return <p>Cargando datos...</p>;
    if (errorCats || errorSubs) return <p>Error cargando datos</p>;

    return (
        <div className="report-form-container">
            <div className="selected-zone">
                {regiones.map((region) => (
                    <div
                        className="selected-zone-item"
                        key={region.id}
                        onClick={() => handleSelectedRegion(region)}
                    >
                        <button className={active.id === region.id ? "active" : ""}>
                            {region.id + 1}
                        </button>
                        <div className="selected-zone-content">
                            <div className="zone-name">
                                {region.id === 6
                                    ? "Revisar Reporte"
                                    : region.id === 0
                                        ? "Colombia"
                                        : `Región ${region.nombre}`}
                            </div>
                        </div>
                    </div>
                ))}
            </div>

            <div className="report-form-title">
                {active.id === 0
                    ? `Reportar Colombia - ${selectedDate.month}/${selectedDate.year}`
                    : `Reportar Región ${active.nombre} - ${selectedDate.month}/${selectedDate.year}`}
                <br />

                {/* Mostrar departamentos de la región activa */}
                {active.id !== 0 && active.id !== 6 && (
                    <div className="regions-depto-container">
                        <strong>Departamentos:</strong>{" "}
                        {departamentosActivos.join(", ")}
                    </div>
                )}
            </div>


            {selectedRegion.id === 6 ? (
                <div className="report-resume">
                    <h2 className="report-resume-title">Resumen de los Informes</h2>

                    <div className="resume-comparision">
                        <h3>Comparativo: Colombia vs Total Regiones</h3>
                        <table className="resume-table comparativo-table">
                            <thead>
                                <tr>
                                    <th>Categoría</th>
                                    <th>Producción Col(Gal) </th>
                                    <th>Ventas Col (COP)</th>
                                    <th>Ventas Col (Gal)</th>
                                    <th>Ventas (COP) Regiones</th>
                                    <th>Ventas (Gal) Regiones</th>
                                </tr>
                            </thead>
                            <tbody>
                                {calcularComparativo().map(({ cat, totalColombia, totalRegiones }) => (
                                    <tr key={cat.id}>
                                        <td>{cat.name}</td>
                                        <td>{formatMiles(totalColombia.produccion)}</td>
                                        <td
                                            className={
                                                totalColombia.sales_cop !== totalRegiones.ventasPesos ? "mismatch" : ""
                                            }
                                        >
                                            {formatMiles(totalColombia.sales_cop)}
                                        </td>
                                        <td
                                            className={
                                                totalColombia.sales_gal !== totalRegiones.ventasVolumen ? "mismatch" : ""
                                            }
                                        >
                                            {formatMiles(totalColombia.sales_gal)}
                                        </td>
                                        <td>{formatMiles(totalRegiones.ventasPesos)}</td>
                                        <td>{formatMiles(totalRegiones.ventasVolumen)}</td>

                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>


                    {/*Colombia */}
                    <div key={0} className="region-resume">
                        <h3 className="region-title">Colombia</h3>

                        {categorias.map((cat) => {
                            const subs = subCategories.filter((s) => s.category_id === cat.id);
                            if (subs.length === 0) return null;

                            return (
                                <div key={cat.id} className="resume-report-form-category">
                                    <div className="categoria-header">
                                        <span className="categoria-title">
                                            Categoría: <b>{cat.name}</b>
                                        </span>
                                    </div>

                                    <div className="table-container">
                                        <table className="resume-table">
                                            <thead>
                                                <tr>
                                                    <th>Subcategoría</th>
                                                    <th>Producción (Gal)</th>
                                                    <th>Ventas (COP)</th>
                                                    <th>Ventas (Gal)</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                {subs.map((sub) => {
                                                    const valores = data?.[0]?.[cat.id]?.[sub.id] || {};
                                                    return (
                                                        <tr key={sub.id}>
                                                            <td>{sub.name}</td>

                                                            {["produccion", "sales_cop", "sales_gal"].map((field) => (
                                                                <td key={field}>
                                                                    <div style={{ display: "flex", alignItems: "center", gap: "6px" }}>
                                                                        <span>{formatMiles(valores[field])}</span>
                                                                        <input
                                                                            type="checkbox"
                                                                            checked={checkedCells[`col-${cat.id}-${sub.id}-${field}`] || false}
                                                                            onChange={(e) =>
                                                                                handleCheck(cat.id, sub.id, field, e.target.checked)
                                                                            }
                                                                        />
                                                                    </div>
                                                                </td>
                                                            ))}
                                                        </tr>
                                                    );
                                                })}
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            );
                        })}
                    </div>

                    {/* Regiones */}
                    {regiones
                        .filter((r) => r.id !== 6 && r.id !== 0)
                        .map((region) => (
                            <div key={region.id} className="region-resume">
                                <h3 className="region-title">Región {region.nombre}</h3>

                                {categorias.map((cat) => {
                                    const subs = subCategories.filter((s) => s.category_id === cat.id);
                                    if (subs.length === 0) return null;

                                    return (
                                        <div key={cat.id} className="resume-report-form-category">
                                            <div className="categoria-header">
                                                <span className="categoria-title">
                                                    Categoría: <b>{cat.name}</b>
                                                </span>
                                            </div>

                                            <div className="table-container">
                                                <table className="resume-table">
                                                    <thead>
                                                        <tr>
                                                            <th>Subcategoría</th>
                                                            <th>Ventas (COP)</th>
                                                            <th>Ventas (Gal)</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        {subs.map((sub) => {
                                                            const valores = data?.[region.id]?.[cat.id]?.[sub.id] || {};
                                                            return (
                                                                <tr key={sub.id}>
                                                                    <td>{sub.name}</td>
                                                                    <td>{formatMiles(valores.ventasPesos)}</td>
                                                                    <td>{formatMiles(valores.ventasVolumen)}</td>
                                                                </tr>
                                                            );
                                                        })}
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                    );
                                })}
                            </div>
                        ))}

                    <div className="resume-actions">
                        <button
                            onClick={handleSendReports}
                            disabled={sending || !allChecked}
                            className={`send-report-btn ${!allChecked ? "disabled" : ""}`}
                        >
                            {sending
                                ? "Enviando..."
                                : !allChecked
                                    ? "Marca todas las casillas para enviar"
                                    : "Enviar Reportes"}
                        </button>

                    </div>
                </div>


            ) : (
                categorias.map((cat) => {
                    const subs = subCategories.filter((s) => s.category_id === cat.id);
                    if (subs.length === 0) return null;

                    return (
                        <div className="report-form" key={cat.id}>
                            <div className="report-form-content">
                                <div className="report-form-category">
                                    <div className="categoria-title">
                                        Categoría: <b>{cat.name}</b>
                                        {active.id === 0 ? (
                                            <span style={{ marginLeft: "1rem", color: "#666" }}>
                                                <b>Colombia</b>
                                            </span>
                                        ) : (
                                            <span style={{ marginLeft: "1rem", color: "#666" }}>
                                                Región: <b>{regiones.find(r => r.id === active.id)?.nombre}</b>
                                            </span>
                                        )}
                                    </div>

                                    <table className={`report-table ${active.id === 0 ? "cols-4" : "cols-3"}`}>
                                        <thead>
                                            <tr>
                                                <th>Subcategoría</th>
                                                {active.id === 0 ? (
                                                    <>
                                                        <th>Producción (Gal)</th>
                                                        <th>Ventas (COP)</th>
                                                        <th>Ventas (Gal)</th>
                                                    </>
                                                ) : (
                                                    <>
                                                        <th>Ventas (COP)</th>
                                                        <th>Ventas (Gal)</th>
                                                    </>
                                                )}
                                            </tr>
                                        </thead>

                                        <tbody>
                                            {subs.map((sub) => (
                                                <tr key={sub.id}>
                                                    <td>{sub.name}</td>
                                                    {active.id === 0 ? (
                                                        <>
                                                            <td>
                                                                <input
                                                                    type="text"
                                                                    value={formatMiles(
                                                                        data?.[active.id]?.[cat.id]?.[sub.id]?.produccion || "0"
                                                                    )}
                                                                    onChange={(e) => {
                                                                        const raw = e.target.value.replace(/\./g, "");
                                                                        const numericValue =
                                                                            raw === "" ? "" : parseInt(raw, 10);
                                                                        handleChange(active.id, cat.id, sub.id, "produccion", numericValue);
                                                                    }}
                                                                />
                                                            </td>

                                                            <td>
                                                                <input
                                                                    type="text"
                                                                    value={formatMiles(
                                                                        data?.[active.id]?.[cat.id]?.[sub.id]?.sales_cop || "0"
                                                                    )}
                                                                    onChange={(e) => {
                                                                        const raw = e.target.value.replace(/\./g, "");
                                                                        const numericValue =
                                                                            raw === "" ? "" : parseInt(raw, 10);
                                                                        handleChange(active.id, cat.id, sub.id, "sales_cop", numericValue);
                                                                    }}
                                                                />
                                                            </td>

                                                            <td>
                                                                <input
                                                                    type="text"
                                                                    value={formatMiles(
                                                                        data?.[active.id]?.[cat.id]?.[sub.id]?.sales_gal || "0"
                                                                    )}
                                                                    onChange={(e) => {
                                                                        const raw = e.target.value.replace(/\./g, "");
                                                                        const numericValue =
                                                                            raw === "" ? "" : parseInt(raw, 10);
                                                                        handleChange(active.id, cat.id, sub.id, "sales_gal", numericValue);
                                                                    }}
                                                                />
                                                            </td>
                                                        </>
                                                    ) : (
                                                        <>
                                                            {["ventasPesos", "ventasVolumen"].map((field) => (
                                                                <td key={field}>
                                                                    <input
                                                                        type="text"
                                                                        value={formatMiles(
                                                                            data?.[active.id]?.[cat.id]?.[sub.id]?.[field] || "0"
                                                                        )}
                                                                        onChange={(e) => {
                                                                            const raw = e.target.value.replace(/\./g, "");
                                                                            const numericValue =
                                                                                raw === "" ? "" : parseInt(raw, 10);
                                                                            handleChange(active.id, cat.id, sub.id, field, numericValue);
                                                                        }}
                                                                    />
                                                                </td>
                                                            ))}

                                                        </>
                                                    )}
                                                </tr>

                                            ))}
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    );
                })
            )}

            {sendError && <p style={{ color: "red" }}>Error: {sendError.message || sendError}</p>}
            {response && <p style={{ color: "green" }}>{response.message}</p>}
        </div>
    );
}
