import { Icon } from "@iconify/react";
import {
  Alert,
  Box,
  Button,
  Card,
  CardContent,
  Chip,
  Collapse,
  Divider,
  FormControl,
  IconButton,
  InputLabel,
  MenuItem,
  Paper,
  Select,
  Skeleton,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Tooltip,
  Typography,
  useMediaQuery,
  useTheme,
} from "@mui/material";
import { useQuery } from "@tanstack/react-query";
import { useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import { toast } from "sonner";
import api from "../api/api.config";
import { getEmpresaMonedas } from "../api/monedas.service";
import { AccesoRestringido } from "../components/common/AccesoRestringido";
import { usePermission } from "../hooks/usePermission";
import { MarangatuExportButton } from "../components/reportes/MarangatuExportButton";
import { descargarCSV, descargarExcel, ExportarMenuButton } from "../components/_standards";
import { fmtFechaCalendario } from "../utils/fecha";

// ==================== API ====================

const getLibroIVA = async (mes, anio, monedaId) => {
  const params = new URLSearchParams({ mes: String(mes), anio: String(anio) });
  if (monedaId) params.set("moneda_id", monedaId);
  const res = await api.get(`/facturas/libro-iva-ventas?${params.toString()}`);
  return res.data;
};

const getLibroIVAMarangatu = async (mes, anio, monedaId) => {
  const params = new URLSearchParams({ mes: String(mes), anio: String(anio) });
  if (monedaId) params.set("moneda_id", monedaId);
  const res = await api.get(`/facturas/libro-iva-ventas/marangatu?${params.toString()}`);
  return res.data;
};

// ==================== HELPERS ====================

const formatMoney = (amount, currency = "PYG") => {
  const cur = currency || "PYG";
  return new Intl.NumberFormat("es-PY", {
    style: "currency",
    currency: cur,
    minimumFractionDigits: cur === "PYG" ? 0 : 2,
  }).format(amount || 0);
};

// La fecha de emisión es una fecha-calendario, no un instante: se formatea con
// fmtFechaCalendario, que la lee por texto. Pasarla por new Date() y getDate()
// la corre un día para atrás en Paraguay (UTC-4), porque el backend la manda
// como medianoche UTC. Ver docs/ui-standards.md.
const formatFecha = (fecha) => fmtFechaCalendario(fecha, "-");

const MESES = [
  "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio",
  "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre",
];

const getAnioActual = () => new Date().getFullYear();
const getMesActual = () => new Date().getMonth() + 1;

// ==================== EXPORT ====================

// Los montos van como número (no texto) para que el Excel los pueda sumar.
const num = (v) => Number(v || 0);

const armarTabla = (data) => {
  const encabezados = [
    "Tipo", "Fecha", "Número", "Timbrado", "CDC", "Cliente", "RUC",
    "Condición", "Gravada 10%", "Gravada 5%", "Exentas",
    "IVA 10%", "IVA 5%", "Total",
  ];
  const filas = data.detalle.map((d) => [
    d.tipo, formatFecha(d.fecha), d.numero, d.timbrado, d.cdc || "", d.cliente, d.ruc,
    d.condicion, num(d.gravada_10), num(d.gravada_5), num(d.exentas),
    num(d.iva_10), num(d.iva_5), num(d.total),
  ]);

  // Fila de totales netos
  const n = data.resumen.neto;
  filas.push([]);
  filas.push([
    "TOTALES NETOS", "", "", "", "", "", "", "",
    num(n.gravada_10), num(n.gravada_5), num(n.exentas),
    num(n.iva_debito_10), num(n.iva_debito_5), num(n.total),
  ]);
  return { encabezados, filas };
};

const exportar = (formato, data, mes, anio) => {
  if (!data?.detalle) return;
  const archivo = `libro_iva_ventas_${anio}_${String(mes).padStart(2, "0")}`;
  if (formato === "xlsx") descargarExcel({ ...armarTabla(data), archivo, hoja: "Libro IVA Ventas" });
  else descargarCSV({ ...armarTabla(data), archivo });
  toast.success("Libro IVA exportado correctamente");
};

// ==================== COMPONENT ====================

export function ReporteLibroIVA() {
  const navigate = useNavigate();
  const muiTheme = useTheme();
  const isMobile = useMediaQuery(muiTheme.breakpoints.down("md"));
  const { canRead } = usePermission("REPORTES");
  const { can } = usePermission("VENTAS");
  const canReadFacturas = can("VEN_FAC_FACTURA_VER");

  const [mes, setMes] = useState(getMesActual());
  const [anio, setAnio] = useState(getAnioActual());
  const [monedaId, setMonedaId] = useState("");
  const [showHelp, setShowHelp] = useState(false);

  // Monedas de la empresa
  const { data: monedasData } = useQuery({
    queryKey: ["empresa-monedas-libro"],
    queryFn: getEmpresaMonedas,
    staleTime: 10 * 60 * 1000,
  });
  const monedas = useMemo(() => {
    const raw = monedasData?.data || monedasData || [];
    return raw.filter((m) => m.active !== false);
  }, [monedasData]);

  const monedaSeleccionada = useMemo(() => {
    if (!monedaId) return null;
    return monedas.find((m) => m.moneda_id === monedaId || m.moneda?.id === monedaId);
  }, [monedaId, monedas]);

  const codigoMoneda = monedaSeleccionada?.moneda?.codigo || "PYG";
  const fmt = (amount) => formatMoney(amount, monedaId ? codigoMoneda : "PYG");

  const { data, isLoading, error } = useQuery({
    queryKey: ["libro-iva-ventas", mes, anio, monedaId],
    queryFn: () => getLibroIVA(mes, anio, monedaId || undefined),
  });

  const resumen = data?.resumen || {};
  const neto = resumen.neto || {};
  const detalle = useMemo(() => data?.detalle || [], [data]);

  const anios = useMemo(() => {
    const actual = getAnioActual();
    return Array.from({ length: 5 }, (_, i) => actual - i);
  }, []);

  if (!canRead || !canReadFacturas) {
    return <AccesoRestringido mensaje="No tienes permisos para ver este reporte." />;
  }

  // Sin esto, un error de la API dejaba `data` en undefined y los `|| {}` de arriba
  // pintaban todo en Gs. 0: el reporte parecia vacio cuando en realidad la consulta
  // habia fallado. El caso tipico es un 403 por alcance de sucursal.
  const mensajeError = error
    ? error?.response?.data?.message || error?.message || "No se pudo cargar el Libro IVA Ventas."
    : null;

  return (
    <Box sx={{ maxWidth: 1400, mx: "auto", p: { xs: 2, md: 3 } }}>
      {mensajeError && (
        <Alert severity="error" sx={{ mb: 2 }}>
          {mensajeError}
        </Alert>
      )}
      {/* ── Header ── */}
      <Box
        sx={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "flex-start",
          mb: 1,
          flexWrap: "wrap",
          gap: 1,
        }}
      >
        <Box sx={{ display: "flex", alignItems: "center", gap: 1.5 }}>
          <Button size="small" onClick={() => navigate("/reportes")} sx={{ minWidth: 32, p: 0.5 }}>
            <Icon icon="lucide:arrow-left" width={20} />
          </Button>
          <Box>
            <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
              <Icon icon="lucide:receipt" width={22} />
              <Typography variant="h6" fontWeight={700}>
                Libro IVA Ventas
              </Typography>
            </Box>
            <Typography variant="caption" color="text.secondary">
              Registro fiscal de IVA Débito por período mensual
            </Typography>
          </Box>
        </Box>
        <Box sx={{ display: "flex", gap: 1, flexWrap: "wrap" }}>
          <ExportarMenuButton
            disabled={!detalle.length}
            onExcel={() => exportar("xlsx", data, mes, anio)}
            onCSV={() => exportar("csv", data, mes, anio)}
          />
          <MarangatuExportButton
            disabled={!detalle.length}
            fetchData={() => getLibroIVAMarangatu(mes, anio, monedaId || undefined)}
          />
        </Box>
      </Box>

      <Box sx={{ display: "flex", alignItems: "center", gap: 1, mb: 2 }}>
        <Typography variant="caption" color="text.secondary">
          <span style={{ cursor: "pointer" }} onClick={() => navigate("/reportes")}>Reportes</span>
          {" > "}Libro IVA Ventas
        </Typography>
        <Tooltip title={showHelp ? "Ocultar ayuda" : "Ver explicación del reporte"}>
          <IconButton
            size="small"
            onClick={() => setShowHelp(!showHelp)}
            color={showHelp ? "primary" : "default"}
            sx={{ ml: 0.5 }}
          >
            <Icon icon="lucide:help-circle" width={16} />
          </IconButton>
        </Tooltip>
      </Box>

      <Collapse in={showHelp}>
        <Paper
          variant="outlined"
          sx={{ p: 2.5, mb: 2, borderRadius: 2, borderColor: "info.main" }}
        >
          <Box sx={{ display: "flex", alignItems: "flex-start", gap: 1.5, mb: 2 }}>
            <Icon icon="lucide:book-open" width={20} style={{ color: "#3b82f6", marginTop: 2 }} />
            <Box>
              <Typography variant="subtitle2" fontWeight={700} sx={{ mb: 0.5 }}>
                ¿Qué es el Libro IVA Ventas?
              </Typography>
              <Typography variant="body2" color="text.secondary" sx={{ lineHeight: 1.7 }}>
                Es el registro fiscal mensual que detalla todo el IVA (Impuesto al Valor Agregado) que tu empresa
                cobró a sus clientes. Este monto se conoce como <strong>IVA Débito Fiscal</strong> y es lo que
                debes declarar a la SET en el <strong>Formulario 120</strong>.
              </Typography>
            </Box>
          </Box>

          <Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", md: "repeat(3, 1fr)" }, gap: 2 }}>
            <Alert severity="info" variant="outlined" icon={<Icon icon="lucide:file-text" width={18} />} sx={{ "& .MuiAlert-message": { width: "100%" } }}>
              <Typography variant="caption" fontWeight={700} sx={{ display: "block", mb: 0.5 }}>
                Factura
              </Typography>
              <Typography variant="caption" color="text.secondary">
                Comprobante de venta. Genera <strong>IVA Débito</strong> que se suma a tu obligación fiscal del mes.
                Cada factura tiene IVA al 10%, 5% o es exenta según el producto/servicio.
              </Typography>
            </Alert>

            <Alert severity="warning" variant="outlined" icon={<Icon icon="lucide:file-minus" width={18} />} sx={{ "& .MuiAlert-message": { width: "100%" } }}>
              <Typography variant="caption" fontWeight={700} sx={{ display: "block", mb: 0.5 }}>
                Nota de Crédito
              </Typography>
              <Typography variant="caption" color="text.secondary">
                Se emite por devoluciones, descuentos posteriores o correcciones a favor del cliente.
                <strong> Resta del IVA Débito</strong>, reduciendo el impuesto a pagar en el período.
              </Typography>
            </Alert>

            <Alert severity="error" variant="outlined" icon={<Icon icon="lucide:file-plus" width={18} />} sx={{ "& .MuiAlert-message": { width: "100%" } }}>
              <Typography variant="caption" fontWeight={700} sx={{ display: "block", mb: 0.5 }}>
                Nota de Débito
              </Typography>
              <Typography variant="caption" color="text.secondary">
                Se emite por cargos adicionales, intereses por mora o ajustes a cargo del cliente.
                <strong> Suma al IVA Débito</strong>, aumentando el impuesto a declarar.
              </Typography>
            </Alert>
          </Box>

          <Divider sx={{ my: 2 }} />

          <Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", md: "repeat(2, 1fr)" }, gap: 2 }}>
            <Box>
              <Typography variant="caption" fontWeight={700} color="primary.main" sx={{ display: "flex", alignItems: "center", gap: 0.5, mb: 0.5 }}>
                <Icon icon="lucide:calculator" width={14} /> Cálculo del IVA Débito Neto
              </Typography>
              <Typography variant="caption" color="text.secondary" component="div" sx={{ lineHeight: 1.8 }}>
                IVA de Facturas <strong>−</strong> IVA de Notas de Crédito <strong>+</strong> IVA de Notas de Débito <strong>=</strong> IVA Débito Fiscal del mes
              </Typography>
            </Box>
            <Box>
              <Typography variant="caption" fontWeight={700} color="warning.main" sx={{ display: "flex", alignItems: "center", gap: 0.5, mb: 0.5 }}>
                <Icon icon="lucide:alert-triangle" width={14} /> Importante para la declaración
              </Typography>
              <Typography variant="caption" color="text.secondary" component="div" sx={{ lineHeight: 1.8 }}>
                El <strong>Total IVA Débito</strong> es el monto que se traslada al Formulario 120 de la SET.
                Para calcular el IVA a pagar, se resta el IVA Crédito (compras) cuando esté disponible.
              </Typography>
            </Box>
          </Box>
        </Paper>
      </Collapse>

      {/* ── Filtro período ── */}
      <Paper variant="outlined" sx={{ p: 2, mb: 2, borderRadius: 2 }}>
        <Box sx={{ display: "flex", gap: 2, alignItems: "center", flexWrap: "wrap" }}>
          <FormControl size="small" sx={{ minWidth: 160 }}>
            <InputLabel>Mes</InputLabel>
            <Select value={mes} label="Mes" onChange={(e) => setMes(e.target.value)}>
              {MESES.map((m, i) => (
                <MenuItem key={i} value={i + 1}>{m}</MenuItem>
              ))}
            </Select>
          </FormControl>
          <FormControl size="small" sx={{ minWidth: 120 }}>
            <InputLabel>Año</InputLabel>
            <Select value={anio} label="Año" onChange={(e) => setAnio(e.target.value)}>
              {anios.map((a) => (
                <MenuItem key={a} value={a}>{a}</MenuItem>
              ))}
            </Select>
          </FormControl>
          <FormControl size="small" sx={{ minWidth: 160 }}>
            <InputLabel>Moneda</InputLabel>
            <Select
              value={monedaId}
              label="Moneda"
              onChange={(e) => setMonedaId(e.target.value)}
            >
              <MenuItem value="">Todas las monedas</MenuItem>
              {monedas.map((m) => (
                <MenuItem key={m.moneda_id || m.moneda?.id} value={m.moneda_id || m.moneda?.id}>
                  {m.moneda?.codigo || m.codigo} - {m.moneda?.descripcion || m.descripcion}
                </MenuItem>
              ))}
            </Select>
          </FormControl>
          <Chip
            label={`${MESES[mes - 1]} ${anio}${monedaId ? ` • ${codigoMoneda}` : ""}`}
            color="primary"
            variant="outlined"
            icon={<Icon icon="lucide:calendar" width={14} />}
          />
        </Box>
      </Paper>

      {/* ── Resumen Fiscal ── */}
      {isLoading ? (
        <Box sx={{ display: "flex", flexDirection: "column", gap: 1, mb: 2 }}>
          {[...Array(3)].map((_, i) => <Skeleton key={i} variant="rounded" height={80} />)}
        </Box>
      ) : (
        <>
          {/* KPIs principales - IVA a pagar */}
          <Paper
            variant="outlined"
            sx={{
              p: 3, mb: 2, borderRadius: 2,
              background: (theme) => theme.palette.mode === "dark" ? "rgba(37, 99, 235, 0.06)" : "rgba(37, 99, 235, 0.03)",
              borderColor: "primary.main",
            }}
          >
            <Box sx={{ display: "flex", alignItems: "center", gap: 1, mb: 1 }}>
              <Typography variant="overline" color="primary.main" fontWeight={600}>
                IVA Débito Fiscal — {MESES[mes - 1]} {anio}
              </Typography>
              <Tooltip title="Este es el impuesto que cobraste a tus clientes en el período. Se traslada al Formulario 120 para la declaración mensual del IVA ante la SET." arrow>
                <Box sx={{ display: "flex", cursor: "help" }}>
                  <Icon icon="lucide:help-circle" width={15} style={{ color: "#3b82f6" }} />
                </Box>
              </Tooltip>
            </Box>
            <Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", sm: "repeat(3, 1fr)" }, gap: 3 }}>
              <Box>
                <Typography variant="caption" color="text.secondary">IVA Débito 10%</Typography>
                <Typography variant="h5" fontWeight={800} color="primary.main">
                  {fmt(neto.iva_debito_10)}
                </Typography>
              </Box>
              <Box>
                <Typography variant="caption" color="text.secondary">IVA Débito 5%</Typography>
                <Typography variant="h5" fontWeight={800} color="primary.main">
                  {fmt(neto.iva_debito_5)}
                </Typography>
              </Box>
              <Box>
                <Typography variant="caption" color="text.secondary">Total IVA Débito</Typography>
                <Typography variant="h4" fontWeight={800} color="warning.main">
                  {fmt(neto.iva_debito_total)}
                </Typography>
              </Box>
            </Box>
          </Paper>

          {/* Desglose */}
          <Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", md: "repeat(3, 1fr)" }, gap: 2, mb: 2 }}>
            {/* Facturas */}
            <Card variant="outlined" sx={{ borderRadius: 2 }}>
              <CardContent sx={{ p: "16px !important" }}>
                <Box sx={{ display: "flex", alignItems: "center", gap: 1, mb: 1.5 }}>
                  <Icon icon="lucide:file-text" width={18} style={{ opacity: 0.6 }} />
                  <Typography variant="subtitle2" fontWeight={700}>Facturas</Typography>
                  <Tooltip title="Comprobantes de venta que generan IVA Débito Fiscal" arrow>
                    <Box sx={{ display: "flex", cursor: "help" }}>
                      <Icon icon="lucide:info" width={14} style={{ opacity: 0.4 }} />
                    </Box>
                  </Tooltip>
                  <Chip label={resumen.facturas?.cantidad || 0} size="small" color="primary" sx={{ ml: "auto" }} />
                </Box>
                <Divider sx={{ mb: 1.5 }} />
                {[
                  { label: "Base Gravada 10%", value: resumen.facturas?.gravada_10 },
                  { label: "Base Gravada 5%", value: resumen.facturas?.gravada_5 },
                  { label: "Exentas", value: resumen.facturas?.exentas },
                  { label: "IVA Débito 10%", value: resumen.facturas?.iva_debito_10, bold: true },
                  { label: "IVA Débito 5%", value: resumen.facturas?.iva_debito_5, bold: true },
                  { label: "Total", value: resumen.facturas?.total, bold: true },
                ].map((r, i) => (
                  <Box key={i} sx={{ display: "flex", justifyContent: "space-between", py: 0.4 }}>
                    <Typography variant="caption" color="text.secondary">{r.label}</Typography>
                    <Typography variant="caption" fontWeight={r.bold ? 700 : 400}>
                      {fmt(r.value)}
                    </Typography>
                  </Box>
                ))}
              </CardContent>
            </Card>

            {/* Notas de Crédito */}
            <Card variant="outlined" sx={{ borderRadius: 2 }}>
              <CardContent sx={{ p: "16px !important" }}>
                <Box sx={{ display: "flex", alignItems: "center", gap: 1, mb: 1.5 }}>
                  <Icon icon="lucide:file-minus" width={18} style={{ opacity: 0.6 }} />
                  <Typography variant="subtitle2" fontWeight={700}>Notas de Crédito</Typography>
                  <Tooltip title="Devoluciones o descuentos que restan del IVA Débito. Reducen el impuesto a pagar." arrow>
                    <Box sx={{ display: "flex", cursor: "help" }}>
                      <Icon icon="lucide:info" width={14} style={{ opacity: 0.4 }} />
                    </Box>
                  </Tooltip>
                  <Chip label={resumen.notas_credito?.cantidad || 0} size="small" color="error" sx={{ ml: "auto" }} />
                </Box>
                <Divider sx={{ mb: 1.5 }} />
                {[
                  { label: "Base Gravada 10%", value: resumen.notas_credito?.gravada_10 },
                  { label: "Base Gravada 5%", value: resumen.notas_credito?.gravada_5 },
                  { label: "Exentas", value: resumen.notas_credito?.exentas },
                  { label: "IVA Restado 10%", value: resumen.notas_credito?.iva_10, bold: true },
                  { label: "IVA Restado 5%", value: resumen.notas_credito?.iva_5, bold: true },
                  { label: "Total", value: resumen.notas_credito?.total, bold: true },
                ].map((r, i) => (
                  <Box key={i} sx={{ display: "flex", justifyContent: "space-between", py: 0.4 }}>
                    <Typography variant="caption" color="text.secondary">{r.label}</Typography>
                    <Typography variant="caption" fontWeight={r.bold ? 700 : 400} color="error.main">
                      {r.value ? `- ${fmt(r.value)}` : fmt(0)}
                    </Typography>
                  </Box>
                ))}
              </CardContent>
            </Card>

            {/* Neto */}
            <Card variant="outlined" sx={{ borderRadius: 2, borderColor: "primary.main" }}>
              <CardContent sx={{ p: "16px !important" }}>
                <Box sx={{ display: "flex", alignItems: "center", gap: 1, mb: 1.5 }}>
                  <Icon icon="lucide:calculator" width={18} style={{ opacity: 0.6 }} />
                  <Typography variant="subtitle2" fontWeight={700}>Totales Netos</Typography>
                  <Tooltip title="Facturas menos Notas de Crédito. Este es el IVA Débito que se declara en el Formulario 120 de la SET." arrow>
                    <Box sx={{ display: "flex", cursor: "help" }}>
                      <Icon icon="lucide:info" width={14} style={{ opacity: 0.4 }} />
                    </Box>
                  </Tooltip>
                </Box>
                <Divider sx={{ mb: 1.5 }} />
                {[
                  { label: "Base Gravada 10%", value: neto.gravada_10 },
                  { label: "Base Gravada 5%", value: neto.gravada_5 },
                  { label: "Exentas", value: neto.exentas },
                  { label: "IVA Débito 10%", value: neto.iva_debito_10, bold: true, color: "primary.main" },
                  { label: "IVA Débito 5%", value: neto.iva_debito_5, bold: true, color: "primary.main" },
                  { label: "Total IVA Débito", value: neto.iva_debito_total, bold: true, color: "warning.main" },
                  { label: "Total Operaciones", value: neto.total, bold: true },
                ].map((r, i) => (
                  <Box key={i} sx={{ display: "flex", justifyContent: "space-between", py: 0.4 }}>
                    <Typography variant="caption" color="text.secondary">{r.label}</Typography>
                    <Typography variant="caption" fontWeight={r.bold ? 700 : 400} color={r.color || "text.primary"}>
                      {fmt(r.value)}
                    </Typography>
                  </Box>
                ))}
              </CardContent>
            </Card>
          </Box>

          {/* ── Detalle ── */}
          {detalle.length === 0 ? (
            <Paper variant="outlined" sx={{ p: 6, textAlign: "center", borderRadius: 2 }}>
              <Icon icon="lucide:inbox" width={48} style={{ opacity: 0.3, marginBottom: 12 }} />
              <Typography color="text.secondary">
                No hay documentos en {MESES[mes - 1]} {anio}
              </Typography>
            </Paper>
          ) : isMobile ? (
            <Box sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
              {detalle.map((d, i) => (
                <Card key={i} variant="outlined" sx={{ borderRadius: 2 }}>
                  <CardContent sx={{ p: "12px !important" }}>
                    <Box sx={{ display: "flex", justifyContent: "space-between", mb: 0.5 }}>
                      <Typography variant="body2" fontWeight={600}>{d.numero || "-"}</Typography>
                      <Chip
                        label={d.tipo === "NOTA_CREDITO" ? "N/C" : "Fact."}
                        size="small"
                        color={d.tipo === "NOTA_CREDITO" ? "error" : "primary"}
                        sx={{ fontSize: "0.68rem", height: 20 }}
                      />
                    </Box>
                    <Typography variant="caption" color="text.secondary">
                      {d.cliente} {d.ruc ? `• ${d.ruc}` : ""}
                    </Typography>
                    <Box sx={{ display: "flex", justifyContent: "space-between", mt: 1 }}>
                      <Typography variant="caption">{formatFecha(d.fecha)}</Typography>
                      <Typography variant="body2" fontWeight={700} color={d.total < 0 ? "error.main" : "success.main"}>
                        {fmt(d.total)}
                      </Typography>
                    </Box>
                  </CardContent>
                </Card>
              ))}
            </Box>
          ) : (
            <TableContainer component={Paper} variant="outlined" sx={{ borderRadius: 2 }}>
              <Table size="small">
                <TableHead>
                  <TableRow>
                    <TableCell sx={{ fontWeight: 600 }}>Tipo</TableCell>
                    <TableCell sx={{ fontWeight: 600 }}>Fecha</TableCell>
                    <TableCell sx={{ fontWeight: 600 }}>Número</TableCell>
                    <TableCell sx={{ fontWeight: 600 }}>CDC</TableCell>
                    <TableCell sx={{ fontWeight: 600 }}>Cliente</TableCell>
                    <TableCell sx={{ fontWeight: 600 }}>RUC</TableCell>
                    <TableCell sx={{ fontWeight: 600 }}>Cond.</TableCell>
                    <TableCell sx={{ fontWeight: 600 }} align="right">Grav. 10%</TableCell>
                    <TableCell sx={{ fontWeight: 600 }} align="right">Grav. 5%</TableCell>
                    <TableCell sx={{ fontWeight: 600 }} align="right">Exentas</TableCell>
                    <TableCell sx={{ fontWeight: 600 }} align="right">IVA 10%</TableCell>
                    <TableCell sx={{ fontWeight: 600 }} align="right">IVA 5%</TableCell>
                    <TableCell sx={{ fontWeight: 600 }} align="right">Total</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {detalle.map((d, i) => (
                    <TableRow
                      key={i}
                      hover
                      sx={{
                        backgroundColor: d.tipo === "NOTA_CREDITO" ? "rgba(239,68,68,0.04)" : "inherit",
                        "&:last-child td": { borderBottom: 0 },
                      }}
                    >
                      <TableCell>
                        <Chip
                          label={d.tipo === "NOTA_CREDITO" ? "N/C" : "Fact."}
                          size="small"
                          color={d.tipo === "NOTA_CREDITO" ? "error" : "primary"}
                          variant="outlined"
                          sx={{ fontSize: "0.7rem" }}
                        />
                      </TableCell>
                      <TableCell sx={{ whiteSpace: "nowrap" }}>{formatFecha(d.fecha)}</TableCell>
                      <TableCell>
                        <Typography variant="body2" fontWeight={600}>{d.numero || "-"}</Typography>
                      </TableCell>
                      <TableCell>
                        <Tooltip title={d.cdc || "Sin CDC"} placement="top">
                          <Typography variant="caption" color="text.secondary" sx={{ fontFamily: "monospace", cursor: d.cdc ? "help" : "default" }}>
                            {d.cdc ? `${d.cdc.slice(0, 8)}…` : "—"}
                          </Typography>
                        </Tooltip>
                      </TableCell>
                      <TableCell>
                        <Typography variant="body2" noWrap sx={{ maxWidth: 180 }}>{d.cliente}</Typography>
                      </TableCell>
                      <TableCell>
                        <Typography variant="caption" color="text.secondary">{d.ruc || "-"}</Typography>
                      </TableCell>
                      <TableCell>
                        <Typography variant="caption">{d.condicion}</Typography>
                      </TableCell>
                      <TableCell align="right">{fmt(d.gravada_10)}</TableCell>
                      <TableCell align="right">{fmt(d.gravada_5)}</TableCell>
                      <TableCell align="right">{fmt(d.exentas)}</TableCell>
                      <TableCell align="right">
                        <Typography variant="body2" fontWeight={600} color="primary.main">
                          {fmt(d.iva_10)}
                        </Typography>
                      </TableCell>
                      <TableCell align="right">
                        <Typography variant="body2" fontWeight={600} color="primary.main">
                          {fmt(d.iva_5)}
                        </Typography>
                      </TableCell>
                      <TableCell align="right">
                        <Typography variant="body2" fontWeight={700} color={d.total < 0 ? "error.main" : "text.primary"}>
                          {fmt(d.total)}
                        </Typography>
                      </TableCell>
                    </TableRow>
                  ))}
                  {/* Fila de totales */}
                  <TableRow sx={{ backgroundColor: "action.hover" }}>
                    <TableCell colSpan={6}>
                      <Typography variant="body2" fontWeight={700}>TOTALES NETOS</Typography>
                    </TableCell>
                    <TableCell align="right"><Typography variant="body2" fontWeight={700}>{fmt(neto.gravada_10)}</Typography></TableCell>
                    <TableCell align="right"><Typography variant="body2" fontWeight={700}>{fmt(neto.gravada_5)}</Typography></TableCell>
                    <TableCell align="right"><Typography variant="body2" fontWeight={700}>{fmt(neto.exentas)}</Typography></TableCell>
                    <TableCell align="right"><Typography variant="body2" fontWeight={700} color="primary.main">{fmt(neto.iva_debito_10)}</Typography></TableCell>
                    <TableCell align="right"><Typography variant="body2" fontWeight={700} color="primary.main">{fmt(neto.iva_debito_5)}</Typography></TableCell>
                    <TableCell align="right"><Typography variant="body2" fontWeight={700} color="warning.main">{fmt(neto.total)}</Typography></TableCell>
                  </TableRow>
                </TableBody>
              </Table>
            </TableContainer>
          )}
        </>
      )}
    </Box>
  );
}
