import { Icon } from "@iconify/react/dist/iconify.js";
import {
    Box,
    Button,
    Card,
    CardContent,
    Checkbox,
    Chip,
    Collapse,
    Dialog,
    DialogActions,
    DialogContent,
    DialogTitle,
    FormControl,
    IconButton,
    InputLabel,
    ListItemIcon,
    ListItemText,
    Menu,
    MenuItem,
    Paper,
    Select,
    Skeleton,
    Snackbar,
    Table,
    TableBody,
    TableCell,
    TableContainer,
    TableHead,
    TableRow,
    TextField,
    Tooltip,
    Typography,
    useMediaQuery,
    useTheme,
} from "@mui/material";
import { DatePicker, LocalizationProvider } from "@mui/x-date-pickers";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import dayjs from "dayjs";
import "dayjs/locale/es";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useNavegacionListado } from "../../hooks/useNavegacionListado";
import { useNavigate, useSearchParams } from "react-router-dom";
import {
    enviarEventoCancelacionNC,
    enviarEventoInutilizacionNC,
    enviarNotasCreditoLoteMiddleware,
    getNotasCredito,
    sincronizarEstadoSifenNC,
} from "../../api/notasCredito.service";
import { formatMoney } from "../../utils/formatMoney";
import KudePreviewModal from "../organismos/KudePreviewModal";
import NotaCreditoDetalleDialog from "./NotaCreditoDetalleDialog";
import { SifenEstadoChip, ListToolbar, EventoSifenPendienteItem, tieneEventoSifenPendiente, AlertasEmpresaBanner, esAlertaEventoSifen, getSifenPipelineSteps } from "../_standards";
import { useAlertasEmpresaQuery } from "../../tanstack/AlertasEmpresaStack";
import { SifenSelectionBar } from "./SifenSelectionBar";
import { DocumentosHeaderActions } from "./DocumentosHeaderActions";
import { usePermission } from "../../hooks/usePermission";
import { useAuthStore } from "../../store/AuthStore";

const ESTADOS = [
  { value: "", label: "Todos los estados" },
  { value: "pendiente", label: "Pendiente", color: "warning" },
  { value: "aprobada", label: "Aprobada", color: "success" },
  { value: "anulada", label: "Anulada", color: "error" },
];

const FILTROS_RAPIDOS = [
  { label: "Hoy", value: "hoy" },
  { label: "Ayer", value: "ayer" },
  { label: "Esta semana", value: "semana" },
  { label: "Este mes", value: "mes" },
  { label: "Mes anterior", value: "mes_anterior" },
];

// Definición de todas las columnas disponibles
const COLUMNAS_DISPONIBLES = [
  { id: "numero", label: "Número", default: true },
  { id: "fecha", label: "Fecha", default: true },
  { id: "cliente", label: "Cliente", default: true },
  { id: "total", label: "Total", default: true },
  { id: "factura_asociada", label: "Factura Asociada", default: true },
  { id: "estado", label: "Estado", default: true },
  { id: "pipeline", label: "Pipeline", default: true },
  { id: "estado_sifen", label: "SIFEN", default: true },
  { id: "evento_aplicado", label: "Evento", default: false },
  { id: "estado_evento", label: "Estado Evento", default: false },
  { id: "cdc", label: "CDC", default: false },
  { id: "fecha_envio_sifen", label: "Fecha Envío SIFEN", default: false },
  { id: "fecha_firma_sifen", label: "Fecha Firma SIFEN", default: false },
  { id: "enlace_qr", label: "QR", default: false },
  { id: "acciones", label: "Acciones", default: true },
];

const COLUMNAS_DEFAULT = COLUMNAS_DISPONIBLES.filter((c) => c.default).map(
  (c) => c.id,
);

const COLUMNAS_STORAGE_KEY = "notas_credito_tab_columnas_visibles";

const getColumnasIniciales = () => {
  try {
    const guardadas = localStorage.getItem(COLUMNAS_STORAGE_KEY);
    if (guardadas) {
      const parsed = JSON.parse(guardadas);
      const idsValidos = new Set(COLUMNAS_DISPONIBLES.map((c) => c.id));
      if (Array.isArray(parsed) && parsed.every((id) => idsValidos.has(id))) {
        return parsed;
      }
    }
  } catch (_) {
    // ignore
  }
  return COLUMNAS_DEFAULT;
};

export function NotasCreditoTab() {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down("sm"));

  // Permisos
  const { can } = usePermission("VENTAS");
  const canCancelarNC = can("VEN_NC_SIFEN_CANCELAR");
  const canInutilizarNC = can("VEN_NC_SIFEN_INUTILIZAR");
  const canEventoSifenNC = canCancelarNC || canInutilizarNC;
  const sifenActivo = useAuthStore((s) => s.empresa?.sifen_activo !== false);

  // Estados de filtros - inicializar con fecha de hoy
  const [search, setSearch] = useState("");
  const [searchDebounced, setSearchDebounced] = useState("");
  // `?buscar=` viene del link de una alerta ("Ir al documento"): arranca filtrado.
  const [searchParams] = useSearchParams();
  const buscarInicial = searchParams.get("buscar");
  useEffect(() => {
    if (!buscarInicial) return;
    setSearch(buscarInicial);
    setSearchDebounced(buscarInicial);
  }, [buscarInicial]);
  const { data: alertasEmpresa = [] } = useAlertasEmpresaQuery();
  const alertaPorDocumento = useMemo(
    () => new Map(alertasEmpresa.filter(esAlertaEventoSifen).map((a) => [a.datos?.documentoId, a])),
    [alertasEmpresa],
  );
  const [estado, setEstado] = useState("");
  const [fechaDesde, setFechaDesde] = useState(dayjs().startOf("week"));
  const [fechaHasta, setFechaHasta] = useState(dayjs().endOf("day"));
  const [filtroRapido, setFiltroRapido] = useState("semana");
  const [showFilters, setShowFilters] = useState(false);
  const [page, setPage] = useState(1);
  const [limit] = useState(20);

  // Estados para selección múltiple y acciones
  const [selectedNotas, setSelectedNotas] = useState([]);
  const [snackbar, setSnackbar] = useState({
    open: false,
    message: "",
    severity: "success",
  });

  // Estado para columnas visibles y menú
  const [columnasVisibles, setColumnasVisibles] = useState(getColumnasIniciales);
  const [columnMenuAnchor, setColumnMenuAnchor] = useState(null);

  // Estado para menú de eventos SIFEN
  const [eventoMenuAnchor, setEventoMenuAnchor] = useState(null);
  const [notaSeleccionada, setNotaSeleccionada] = useState(null);
  const [dialogEvento, setDialogEvento] = useState({
    open: false,
    tipo: null,
    motivo: "",
  });

  // Estado para diálogo de detalle
  const [detalleDialog, setDetalleDialog] = useState({
    open: false,
    notaCredito: null,
  });

  // Estado para preview KUDE (PDF)
  const [kudePreview, setKudePreview] = useState({
    open: false,
    notaId: null,
  });

  // Debounce para búsqueda
  useEffect(() => {
    const timer = setTimeout(() => {
      setSearchDebounced(search);
      setPage(1);
    }, 500);
    return () => clearTimeout(timer);
  }, [search]);

  // Aplicar filtros rápidos
  const aplicarFiltroRapido = useCallback((filtro) => {
    const hoy = dayjs();
    setFiltroRapido(filtro);

    switch (filtro) {
      case "hoy":
        setFechaDesde(hoy.startOf("day"));
        setFechaHasta(hoy.endOf("day"));
        break;
      case "ayer": {
        const ayer = hoy.subtract(1, "day");
        setFechaDesde(ayer.startOf("day"));
        setFechaHasta(ayer.endOf("day"));
        break;
      }
      case "semana":
        setFechaDesde(hoy.startOf("week"));
        setFechaHasta(hoy.endOf("week"));
        break;
      case "mes":
        setFechaDesde(hoy.startOf("month"));
        setFechaHasta(hoy.endOf("month"));
        break;
      case "mes_anterior": {
        const mesAnterior = hoy.subtract(1, "month");
        setFechaDesde(mesAnterior.startOf("month"));
        setFechaHasta(mesAnterior.endOf("month"));
        break;
      }
      default:
        break;
    }
    setPage(1);
  }, []);

  // Limpiar filtros
  const limpiarFiltros = useCallback(() => {
    setSearch("");
    setSearchDebounced("");
    setEstado("");
    setFiltroRapido("semana");
    aplicarFiltroRapido("semana");
    setPage(1);
  }, [aplicarFiltroRapido]);

  // Mutation para enviar notas de crédito en lote al middleware
  const enviarLoteMutation = useMutation({
    mutationFn: enviarNotasCreditoLoteMiddleware,
    onSuccess: (data) => {
      setSnackbar({
        open: true,
        message: `${data.data?.enviadas || 0} nota(s) de crédito enviadas al middleware`,
        severity: "success",
      });
      setSelectedNotas([]);
      queryClient.invalidateQueries(["notas-credito"]);
      setTimeout(() => {
        queryClient.invalidateQueries(["notas-credito"]);
      }, 5000);
    },
    onError: (error) => {
      setSnackbar({
        open: true,
        message:
          error.response?.data?.message || "Error al enviar notas de crédito",
        severity: "error",
      });
    },
  });

  // Mutation para sincronizar estado SIFEN manualmente
  const sincronizarSifenMutation = useMutation({
    mutationFn: sincronizarEstadoSifenNC,
    onSuccess: (data) => {
      setSnackbar({
        open: true,
        message:
          data.actualizados > 0
            ? `Estado SIFEN actualizado: ${data.actualizados} nota(s) de crédito`
            : "Sincronización completada",
        severity: data.actualizados > 0 ? "success" : "info",
      });
      queryClient.invalidateQueries(["notas-credito"]);
    },
    onError: (error) => {
      setSnackbar({
        open: true,
        message:
          error.response?.data?.message || "Error al sincronizar estado SIFEN",
        severity: "error",
      });
    },
  });

  // Mutation para evento de inutilización SIFEN
  const inutilizacionMutation = useMutation({
    mutationFn: ({ notaId, motivo }) =>
      enviarEventoInutilizacionNC(notaId, motivo),
    onSuccess: (data) => {
      setSnackbar({
        open: true,
        message:
          data.message || "Evento de inutilización enviado correctamente",
        severity: data.success ? "success" : "warning",
      });
      setDialogEvento({ open: false, tipo: null, motivo: "" });
      setNotaSeleccionada(null);
      queryClient.invalidateQueries(["notas-credito"]);
    },
    onError: (error) => {
      setSnackbar({
        open: true,
        message:
          error.response?.data?.message ||
          "Error al enviar evento de inutilización",
        severity: "error",
      });
    },
  });

  // Mutation para evento de cancelación SIFEN
  const cancelacionMutation = useMutation({
    mutationFn: ({ notaId, motivo }) =>
      enviarEventoCancelacionNC(notaId, motivo),
    onSuccess: (data) => {
      setSnackbar({
        open: true,
        message: data.message || "Evento de cancelación enviado correctamente",
        severity: data.success ? "success" : "warning",
      });
      setDialogEvento({ open: false, tipo: null, motivo: "" });
      setNotaSeleccionada(null);
      queryClient.invalidateQueries(["notas-credito"]);
    },
    onError: (error) => {
      setSnackbar({
        open: true,
        message:
          error.response?.data?.message ||
          "Error al enviar evento de cancelación",
        severity: "error",
      });
    },
  });

  // Handlers para eventos SIFEN
  const handleEventoSifen = (nota, tipo) => {
    setNotaSeleccionada(nota);
    setDialogEvento({ open: true, tipo, motivo: "" });
    setEventoMenuAnchor(null);
  };

  // Handlers para diálogo de detalle
  const handleOpenDetalle = (notaCredito) => {
    setDetalleDialog({ open: true, notaCredito });
  };

  const handleCloseDetalle = () => {
    setDetalleDialog({ open: false, notaCredito: null });
  };

  const handleConfirmarEvento = () => {
    if (!dialogEvento.motivo.trim()) {
      setSnackbar({
        open: true,
        message: "Debe ingresar un motivo",
        severity: "warning",
      });
      return;
    }

    if (dialogEvento.tipo === "inutilizacion") {
      inutilizacionMutation.mutate({
        notaId: notaSeleccionada.id,
        motivo: dialogEvento.motivo,
      });
    } else if (dialogEvento.tipo === "cancelacion") {
      cancelacionMutation.mutate({
        notaId: notaSeleccionada.id,
        motivo: dialogEvento.motivo,
      });
    }
  };

  // Una NC es reenviable a SIFEN si no está aprobada ni anulada.
  // El estado local se sincroniza con SIFEN en el rechazo (ver middleware-sifen.service.ts).
  const esReenviable = (nc) =>
    nc.estado === "Pendiente" ||
    nc.estado === "Error" ||
    nc.estado === "Rechazado";
  const esCancelableECAN = (nc) => {
    if (!nc.fecha_envio_sifen) return false;
    // SIFEN: la cancelación (ECAN) de notas de crédito/débito admite 168 horas (7 días)
    // desde el envío. Las 48 horas aplican solo a facturas.
    return (Date.now() - new Date(nc.fecha_envio_sifen).getTime()) / 3600000 <= 168;
  };

  // Handlers para selección
  const handleSelectAll = (event) => {
    if (event.target.checked) {
      const reenviablesIds = notasCredito.filter(esReenviable).map((nc) => nc.id);
      setSelectedNotas(reenviablesIds);
    } else {
      setSelectedNotas([]);
    }
  };

  const handleSelectNota = (notaId) => {
    setSelectedNotas((prev) =>
      prev.includes(notaId)
        ? prev.filter((id) => id !== notaId)
        : [...prev, notaId],
    );
  };

  const handleEnviarLote = () => {
    if (selectedNotas.length === 0) return;
    enviarLoteMutation.mutate(selectedNotas);
  };

  const toggleColumna = (columnaId) => {
    setColumnasVisibles((prev) => {
      const next = prev.includes(columnaId)
        ? prev.filter((id) => id !== columnaId)
        : [...prev, columnaId];
      try {
        localStorage.setItem(COLUMNAS_STORAGE_KEY, JSON.stringify(next));
      } catch (_) {
        // ignore
      }
      return next;
    });
  };

  const isColumnaVisible = (columnaId) => columnasVisibles.includes(columnaId);

  const getSifenPipeline = getSifenPipelineSteps;

  // Construir parámetros de consulta
  const queryParams = useMemo(
    () => ({
      page,
      limit,
      search: searchDebounced || undefined,
      estado: estado || undefined,
      ...(searchDebounced
        ? {}
        : {
            fechaDesde: fechaDesde ? fechaDesde.format("YYYY-MM-DD") : undefined,
            fechaHasta: fechaHasta ? fechaHasta.format("YYYY-MM-DD") : undefined,
          }),
    }),
    [page, limit, searchDebounced, estado, fechaDesde, fechaHasta],
  );

  // Query para obtener notas de crédito
  const {
    data: notasCreditoData,
    isLoading,
    refetch,
  } = useQuery({
    queryKey: ["notas-credito", queryParams],
    queryFn: () => getNotasCredito(queryParams),
    keepPreviousData: true,
  });

  const notasCredito = useMemo(
    () => notasCreditoData?.data || [],
    [notasCreditoData],
  );
  const total = notasCreditoData?.total || 0;
  const lastPage = notasCreditoData?.lastPage || 1;

  // Navegación anterior/siguiente del modal de detalle.
  const navegacionDetalle = useNavegacionListado({
    items: notasCredito,
    idActual: detalleDialog.open ? (detalleDialog.notaCredito?.id ?? null) : null,
    onSeleccionar: useCallback((notaCredito) => setDetalleDialog({ open: true, notaCredito }), []),
    page,
    lastPage,
    limit,
    total,
    setPage,
    paginaCargada: notasCreditoData?.page,
  });

  // Calcular resumen
  const resumen = useMemo(() => {
    const hoy = dayjs().format("YYYY-MM-DD");
    const notasHoy = notasCredito.filter(
      (nc) => dayjs(nc.dfeemide).format("YYYY-MM-DD") === hoy,
    );

    // Totales del día agrupados por moneda
    const totalesPorMoneda = notasHoy.reduce((acc, nc) => {
      const monedaCodigo = nc.moneda?.codigo || "PYG";
      if (!acc[monedaCodigo]) {
        acc[monedaCodigo] = 0;
      }
      acc[monedaCodigo] += nc.nota_credito_subtotales?.[0]?.dtotope || 0;
      return acc;
    }, {});

    // Contar estados SIFEN
    const pendientesSifen = notasCredito.filter(
      (nc) => !nc.estado_sifen || nc.estado_sifen === "Pendiente",
    ).length;
    const aprobadosSifen = notasCredito.filter(
      (nc) => nc.estado_sifen === "Aprobado",
    ).length;
    const rechazadosSifen = notasCredito.filter(
      (nc) => nc.estado_sifen === "Rechazado",
    ).length;

    return {
      notasHoy: notasHoy.length,
      totalesPorMoneda,
      totalGeneral: notasCredito.length,
      pendientesSifen,
      aprobadosSifen,
      rechazadosSifen,
    };
  }, [notasCredito]);

  const filtrosActivos = [
    searchDebounced,
    estado,
    fechaDesde,
    fechaHasta,
  ].filter(Boolean).length;

  return (
    <LocalizationProvider dateAdapter={AdapterDayjs} adapterLocale="es">
      <Box sx={{ overflowX: "hidden", width: "100%" }}>
        <AlertasEmpresaBanner tipoDocumento="nota_credito" />
        {/* Header */}
        <Box
          sx={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            mb: 3,
          }}
        >
          <Typography variant="h4" fontWeight={600}>
            Notas de Crédito
          </Typography>
          <Button
            variant="contained"
            startIcon={<Icon icon="mdi:plus" />}
            onClick={() => navigate("/ventas/notas-credito/nueva")}
            size={isMobile ? "small" : "medium"}
          >
            {isMobile ? "Nueva" : "Nueva Nota de Crédito"}
          </Button>
        </Box>

        {/* Barra superior estándar: búsqueda + acciones (fila 1) y filtros de período (fila 2) */}
        <ListToolbar
          searchText={search}
          onSearchChange={(v) => {
            setSearch(v);
            setPage(1);
          }}
          searchPlaceholder="Buscar por número, cliente..."
          searchHelper={searchDebounced ? "Buscando en todo el historial" : undefined}
          showFilters={showFilters}
          onToggleFilters={() => setShowFilters((p) => !p)}
          filtrosActivos={filtrosActivos}
          showColumns={false}
          quickFilters={FILTROS_RAPIDOS}
          quickFilterActive={filtroRapido}
          onQuickFilter={aplicarFiltroRapido}
          onClearFilters={limpiarFiltros}
          extraActions={
            <DocumentosHeaderActions
              onRefetch={() => refetch()}
              onSyncSifen={
                sifenActivo ? () => sincronizarSifenMutation.mutate() : undefined
              }
              onColumns={(e) => setColumnMenuAnchor(e.currentTarget)}
              loadingSync={sincronizarSifenMutation.isPending}
              canSyncSifen={sifenActivo}
              showLabels={!isMobile}
            />
          }
        />

        {/* Barra de acciones para selección — compartida con Facturas */}
        {sifenActivo && (
          <SifenSelectionBar
            selectedCount={selectedNotas.length}
            rechazadosCount={notasCredito.filter(
              (nc) => selectedNotas.includes(nc.id) && nc.estado === "Rechazado",
            ).length}
            entityLabel="nota de crédito"
            canSend
            sending={enviarLoteMutation.isPending || enviarLoteMutation.isLoading}
            onSend={handleEnviarLote}
            onCancel={() => setSelectedNotas([])}
          />
        )}

        {/* Menú de selección de columnas */}
        <Menu
          anchorEl={columnMenuAnchor}
          open={Boolean(columnMenuAnchor)}
          onClose={() => setColumnMenuAnchor(null)}
          PaperProps={{ sx: { maxHeight: 400, width: 250 } }}
        >
          <Box sx={{ px: 2, py: 1 }}>
            <Typography variant="subtitle2" fontWeight={600}>
              Columnas visibles
            </Typography>
          </Box>
          {COLUMNAS_DISPONIBLES.map((col) => (
            <MenuItem key={col.id} onClick={() => toggleColumna(col.id)} dense>
              <Checkbox
                checked={isColumnaVisible(col.id)}
                size="small"
                sx={{ p: 0.5, mr: 1 }}
              />
              <ListItemText primary={col.label} />
            </MenuItem>
          ))}
        </Menu>

        {/* Panel de filtros expandible */}
        <Collapse in={showFilters}>
          <Paper sx={{ p: { xs: 1.5, sm: 2 }, mb: 2 }} variant="outlined">
            <Box sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}>
              <Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap" }}>
                <Box sx={{ flex: 1, minWidth: { xs: "100%", sm: 160 } }}>
                  <DatePicker
                    label="Fecha desde"
                    value={fechaDesde}
                    onChange={(date) => {
                      setFechaDesde(date);
                      setFiltroRapido("");
                      setPage(1);
                    }}
                    slotProps={{
                      textField: { size: "small", fullWidth: true },
                    }}
                  />
                </Box>
                <Box sx={{ flex: 1, minWidth: { xs: "100%", sm: 160 } }}>
                  <DatePicker
                    label="Fecha hasta"
                    value={fechaHasta}
                    onChange={(date) => {
                      setFechaHasta(date);
                      setFiltroRapido("");
                      setPage(1);
                    }}
                    slotProps={{
                      textField: { size: "small", fullWidth: true },
                    }}
                  />
                </Box>
              </Box>
              <Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap" }}>
                <FormControl
                  sx={{ flex: 1, minWidth: { xs: "100%", sm: 160 } }}
                  size="small"
                >
                  <InputLabel>Estado</InputLabel>
                  <Select
                    value={estado}
                    label="Estado"
                    onChange={(e) => {
                      setEstado(e.target.value);
                      setPage(1);
                    }}
                  >
                    {ESTADOS.map((e) => (
                      <MenuItem key={e.value} value={e.value}>
                        {e.label}
                      </MenuItem>
                    ))}
                  </Select>
                </FormControl>
                <Button
                  variant="outlined"
                  onClick={limpiarFiltros}
                  startIcon={<Icon icon="mdi:filter-off" />}
                  sx={{
                    flex: { xs: 1, sm: "none" },
                    minWidth: { xs: 0, sm: 120 },
                  }}
                >
                  Limpiar
                </Button>
              </Box>
            </Box>
          </Paper>
        </Collapse>

        {/* Resumen */}
        <Box sx={{ display: "flex", gap: { xs: 1, sm: 2 }, mb: { xs: 2, sm: 3 }, flexWrap: "wrap" }}>
          {[
            { label: isMobile ? "Hoy" : "Notas Hoy", icon: "mdi:file-document-outline", value: resumen.notasHoy, color: undefined },
            { label: "Pendiente SIFEN", icon: "mdi:clock-outline", value: resumen.pendientesSifen, color: "warning.main" },
            { label: "Aprobados SIFEN", icon: "mdi:check-circle", value: resumen.aprobadosSifen, color: "success.main" },
            { label: "Rechazados SIFEN", icon: "mdi:close-circle", value: resumen.rechazadosSifen, color: "error.main" },
            { label: isMobile ? "Total" : "Total General", icon: "mdi:file-multiple", value: resumen.totalGeneral, color: undefined },
          ].map((kpi) => (
            <Card key={kpi.label} variant="outlined" sx={{ flex: "1 1 0", minWidth: 90 }}>
              <CardContent sx={{ p: { xs: 1, sm: 1.5 }, "&:last-child": { pb: { xs: 1, sm: 1.5 } } }}>
                <Typography color="text.secondary" variant="caption" sx={{ display: "flex", alignItems: "center", gap: 0.5, fontSize: { xs: "0.65rem", sm: "0.75rem" } }}>
                  <Icon icon={kpi.icon} width={isMobile ? 14 : 16} />
                  {kpi.label}
                </Typography>
                <Typography variant={isMobile ? "h6" : "h5"} fontWeight={600} color={kpi.color}>
                  {isLoading ? <Skeleton width={60} /> : kpi.value}
                </Typography>
              </CardContent>
            </Card>
          ))}
        </Box>

        {/* Vista mobile: cards */}
        {isMobile ? (
          <Box sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
            {isLoading ? (
              [...Array(4)].map((_, i) => (
                <Paper
                  key={i}
                  variant="outlined"
                  sx={{ p: 1.5, borderRadius: 2 }}
                >
                  <Skeleton width="60%" />
                  <Skeleton width="40%" />
                  <Skeleton width="80%" />
                </Paper>
              ))
            ) : notasCredito.length === 0 ? (
              <Paper variant="outlined" sx={{ p: 4, textAlign: "center" }}>
                <Icon
                  icon="mdi:file-document-outline"
                  width={48}
                  style={{ opacity: 0.3 }}
                />
                <Typography color="text.secondary" sx={{ mt: 1 }}>
                  No se encontraron notas de crédito
                </Typography>
              </Paper>
            ) : (
              notasCredito.map((nota) => (
                <Paper
                  key={nota.id}
                  variant="outlined"
                  onClick={() => handleOpenDetalle(nota)}
                  sx={{
                    p: 1.5,
                    borderRadius: 2,
                    cursor: "pointer",
                    "&:active": { bgcolor: "action.hover" },
                  }}
                >
                  {/* Fila 1: número + chips de estado */}
                  <Box
                    sx={{
                      display: "flex",
                      justifyContent: "space-between",
                      alignItems: "flex-start",
                      mb: 0.5,
                    }}
                  >
                    <Typography
                      variant="body2"
                      fontWeight={600}
                      sx={{ fontFamily: "monospace" }}
                    >
                      {`${nota.dest}-${nota.dpunexp}-${nota.dnumdoc}`}
                    </Typography>
                    <Box
                      sx={{
                        display: "flex",
                        gap: 0.5,
                        flexWrap: "wrap",
                        justifyContent: "flex-end",
                      }}
                    >
                      <Chip
                        label={nota.estado || "Pendiente"}
                        size="small"
                        variant="outlined"
                        color={
                          nota.estado === "Aprobada" || nota.estado === "Pagada"
                            ? "success"
                            : nota.estado === "Anulada"
                              ? "error"
                              : "warning"
                        }
                      />
                      <SifenEstadoChip
                        estadoSifen={nota.estado_sifen}
                        mensajeSifen={nota.mensaje_sifen}
                        showDash={false}
                      />
                    </Box>
                  </Box>
                  {/* Fila 2: cliente */}
                  <Typography variant="body2" fontWeight={500} noWrap>
                    {nota.clientes?.personas?.razon_social || "Sin nombre"}
                  </Typography>
                  <Typography variant="caption" color="text.secondary">
                    {nota.clientes?.cod_cliente || ""}
                  </Typography>
                  {/* Fila 3: factura asociada */}
                  {nota.factura_cab && (
                    <Typography
                      variant="caption"
                      color="text.secondary"
                      display="block"
                    >
                      Factura:{" "}
                      {`${nota.factura_cab.dest}-${nota.factura_cab.dpunexp}-${nota.factura_cab.dnumdoc}`}
                    </Typography>
                  )}
                  {/* Fila 4: total + fecha + acciones */}
                  <Box
                    sx={{
                      display: "flex",
                      justifyContent: "space-between",
                      alignItems: "center",
                      mt: 0.75,
                    }}
                  >
                    <Box>
                      <Typography
                        variant="body2"
                        fontWeight={700}
                        color="primary.main"
                      >
                        {formatMoney(
                          nota.nota_credito_subtotal?.[0]?.dtotope || 0,
                          nota.moneda?.codigo || "PYG",
                        )}
                      </Typography>
                      <Typography variant="caption" color="text.secondary">
                        {dayjs(nota.dfeemide).format("DD/MM/YYYY HH:mm")}
                      </Typography>
                    </Box>
                    <Box
                      sx={{ display: "flex", gap: 0.25 }}
                      onClick={(e) => e.stopPropagation()}
                    >
                      <Tooltip title="Ver detalle">
                        <IconButton
                          size="small"
                          onClick={() => handleOpenDetalle(nota)}
                        >
                          <Icon icon="mdi:eye" width={18} />
                        </IconButton>
                      </Tooltip>
                      <Tooltip title="Ver KUDE">
                        <IconButton
                          size="small"
                          color="primary"
                          onClick={(e) => {
                            e.stopPropagation();
                            setKudePreview({ open: true, notaId: nota.id });
                          }}
                        >
                          <Icon icon="mdi:file-pdf-box" width={18} />
                        </IconButton>
                      </Tooltip>
                      {!nota.estado_sifen && (
                        <Tooltip title="Editar">
                          <IconButton
                            size="small"
                            onClick={(e) => {
                              e.stopPropagation();
                              navigate(
                                `/ventas/notas-credito/${nota.id}/editar`,
                              );
                            }}
                          >
                            <Icon icon="mdi:pencil" width={18} />
                          </IconButton>
                        </Tooltip>
                      )}
                      {canEventoSifenNC &&
                        (nota.estado_sifen === "Rechazado" ||
                          nota.estado_sifen === "Aprobado") && (
                        <Tooltip title="Eventos SIFEN">
                          <IconButton
                            size="small"
                            color="warning"
                            onClick={(e) => {
                              e.stopPropagation();
                              setNotaSeleccionada(nota);
                              setEventoMenuAnchor(e.currentTarget);
                            }}
                          >
                            <Icon icon="mdi:file-document-alert" width={18} />
                          </IconButton>
                        </Tooltip>
                      )}
                    </Box>
                  </Box>
                </Paper>
              ))
            )}
          </Box>
        ) : (
          /* Vista desktop: tabla */
          <TableContainer
            component={Paper}
            variant="outlined"
            sx={{ overflowX: "auto" }}
          >
            <Table size="medium" sx={{ minWidth: 650 }}>
              <TableHead>
                <TableRow sx={{ bgcolor: "action.hover" }}>
                  <TableCell padding="checkbox">
                    <Checkbox
                      indeterminate={
                        selectedNotas.length > 0 &&
                        selectedNotas.length <
                          notasCredito.filter(esReenviable).length
                      }
                      checked={
                        notasCredito.filter(esReenviable).length > 0 &&
                        selectedNotas.length ===
                          notasCredito.filter(esReenviable).length
                      }
                      onChange={handleSelectAll}
                      size="small"
                    />
                  </TableCell>
                  {isColumnaVisible("numero") && (
                    <TableCell sx={{ fontWeight: 600, whiteSpace: "nowrap" }}>
                      Número
                    </TableCell>
                  )}
                  {isColumnaVisible("fecha") && (
                    <TableCell sx={{ fontWeight: 600, whiteSpace: "nowrap" }}>
                      Fecha
                    </TableCell>
                  )}
                  {isColumnaVisible("cliente") && (
                    <TableCell sx={{ fontWeight: 600, whiteSpace: "nowrap" }}>
                      Cliente
                    </TableCell>
                  )}
                  {isColumnaVisible("total") && (
                    <TableCell
                      sx={{ fontWeight: 600, whiteSpace: "nowrap" }}
                      align="right"
                    >
                      Total
                    </TableCell>
                  )}
                  {isColumnaVisible("factura_asociada") && (
                    <TableCell sx={{ fontWeight: 600 }}>
                      Factura Asociada
                    </TableCell>
                  )}
                  {isColumnaVisible("estado") && (
                    <TableCell sx={{ fontWeight: 600 }} align="center">
                      Estado
                    </TableCell>
                  )}
                  {isColumnaVisible("pipeline") && (
                    <TableCell sx={{ fontWeight: 600 }} align="center" />
                  )}
                  {isColumnaVisible("estado_sifen") && (
                    <TableCell sx={{ fontWeight: 600 }} align="center">
                      SIFEN
                    </TableCell>
                  )}
                  {isColumnaVisible("evento_aplicado") && (
                    <TableCell sx={{ fontWeight: 600 }} align="center">
                      Evento
                    </TableCell>
                  )}
                  {isColumnaVisible("estado_evento") && (
                    <TableCell sx={{ fontWeight: 600 }} align="center">
                      Estado Evento
                    </TableCell>
                  )}
                  {isColumnaVisible("cdc") && (
                    <TableCell sx={{ fontWeight: 600 }}>CDC</TableCell>
                  )}
                  {isColumnaVisible("acciones") && (
                    <TableCell sx={{ fontWeight: 600 }} align="center">
                      Acciones
                    </TableCell>
                  )}
                </TableRow>
              </TableHead>
              <TableBody>
                {isLoading ? (
                  [...Array(5)].map((_, i) => (
                    <TableRow key={i}>
                      <TableCell>
                        <Skeleton />
                      </TableCell>
                      <TableCell>
                        <Skeleton />
                      </TableCell>
                      <TableCell>
                        <Skeleton />
                      </TableCell>
                      <TableCell>
                        <Skeleton />
                      </TableCell>
                      {!isMobile && (
                        <TableCell>
                          <Skeleton />
                        </TableCell>
                      )}
                      <TableCell>
                        <Skeleton />
                      </TableCell>
                      <TableCell>
                        <Skeleton />
                      </TableCell>
                    </TableRow>
                  ))
                ) : notasCredito.length === 0 ? (
                  <TableRow>
                    <TableCell
                      colSpan={isMobile ? 6 : 7}
                      align="center"
                      sx={{ py: 4 }}
                    >
                      <Box
                        sx={{
                          display: "flex",
                          flexDirection: "column",
                          alignItems: "center",
                          gap: 2,
                        }}
                      >
                        <Icon
                          icon="mdi:file-document-outline"
                          width={48}
                          color="text.secondary"
                        />
                        <Typography variant="body1" color="text.secondary">
                          No se encontraron notas de crédito
                        </Typography>
                      </Box>
                    </TableCell>
                  </TableRow>
                ) : (
                  notasCredito.map((nota) => (
                    <TableRow
                      key={nota.id}
                      hover
                      onClick={() => handleOpenDetalle(nota)}
                      sx={{ cursor: "pointer" }}
                    >
                      <TableCell
                        padding="checkbox"
                        onClick={(e) => e.stopPropagation()}
                      >
                        <Checkbox
                          checked={selectedNotas.includes(nota.id)}
                          onChange={() => handleSelectNota(nota.id)}
                          disabled={!esReenviable(nota)}
                          size="small"
                        />
                      </TableCell>
                      {isColumnaVisible("numero") && (
                        <TableCell sx={{ whiteSpace: "nowrap" }}>
                          {`${nota.dest}-${nota.dpunexp}-${nota.dnumdoc}`}
                        </TableCell>
                      )}
                      {isColumnaVisible("fecha") && (
                        <TableCell sx={{ whiteSpace: "nowrap" }}>
                          {dayjs(nota.dfeemide).format("DD/MM/YYYY")}
                          <Typography
                            variant="caption"
                            display="block"
                            color="text.secondary"
                          >
                            {dayjs(nota.dfeemide).format("HH:mm")}
                          </Typography>
                        </TableCell>
                      )}
                      {isColumnaVisible("cliente") && (
                        <TableCell
                          sx={{
                            maxWidth: 200,
                            overflow: "hidden",
                            textOverflow: "ellipsis",
                          }}
                        >
                          {nota.clientes?.personas?.razon_social ||
                            "Sin nombre"}
                          <Typography
                            variant="caption"
                            display="block"
                            color="text.secondary"
                          >
                            {nota.clientes?.cod_cliente}
                          </Typography>
                        </TableCell>
                      )}
                      {isColumnaVisible("total") && (
                        <TableCell align="right" sx={{ whiteSpace: "nowrap" }}>
                          {formatMoney(
                            nota.nota_credito_subtotal?.[0]?.dtotope || 0,
                            nota.moneda?.codigo || "PYG",
                          )}
                        </TableCell>
                      )}
                      {isColumnaVisible("factura_asociada") && (
                        <TableCell>
                          {nota.factura_cab ? (
                            <Chip
                              label={`${nota.factura_cab.dest}-${nota.factura_cab.dpunexp}-${nota.factura_cab.dnumdoc}`}
                              size="small"
                              variant="outlined"
                            />
                          ) : (
                            "-"
                          )}
                        </TableCell>
                      )}
                      {isColumnaVisible("estado") && (
                        <TableCell align="center">
                          <Chip
                            label={nota.estado || "Pendiente"}
                            size="small"
                            variant="outlined"
                            color={
                              nota.estado === "Pagada" ||
                              nota.estado === "Aprobada"
                                ? "success"
                                : nota.estado === "Anulada"
                                  ? "error"
                                  : "warning"
                            }
                          />
                        </TableCell>
                      )}
                      {isColumnaVisible("pipeline") && (
                        <TableCell align="center" sx={{ px: 0.5 }}>
                          <Box sx={{ display: "flex", alignItems: "center", justifyContent: "center", gap: "2px" }}>
                            {getSifenPipeline(nota).map((step, i, arr) => (
                              <Box key={i} sx={{ display: "flex", alignItems: "center", gap: "2px" }}>
                                <Tooltip title={step.label + (step.date ? ` (${step.date})` : "")} arrow>
                                  <Box component="span" sx={{ display: "inline-flex", cursor: "default" }}>
                                    <Icon
                                      icon={step.icon}
                                      width={15}
                                      style={{ color: step.done ? step.color : "#555", opacity: step.done ? 1 : 0.3 }}
                                    />
                                  </Box>
                                </Tooltip>
                                {i < arr.length - 1 && (
                                  <Icon icon="mdi:chevron-right" width={9} style={{ color: "#555", opacity: 0.4 }} />
                                )}
                              </Box>
                            ))}
                          </Box>
                        </TableCell>
                      )}
                      {isColumnaVisible("estado_sifen") && (
                        <TableCell align="center">
                          <SifenEstadoChip
                            estadoSifen={nota.estado_sifen}
                            mensajeSifen={nota.mensaje_sifen}
                          />
                        </TableCell>
                      )}
                      {isColumnaVisible("evento_aplicado") && (
                        <TableCell align="center">
                          {nota.evento_aplicado ? (
                            <Chip
                              label={
                                nota.evento_aplicado === "EINU"
                                  ? "Inutilización"
                                  : nota.evento_aplicado === "ECAN"
                                    ? "Cancelación"
                                    : nota.evento_aplicado
                              }
                              size="small"
                              variant="outlined"
                              color={
                                nota.evento_aplicado === "EINU"
                                  ? "warning"
                                  : nota.evento_aplicado === "ECAN"
                                    ? "error"
                                    : "default"
                              }
                            />
                          ) : (
                            <Typography
                              variant="caption"
                              color="text.secondary"
                            >
                              -
                            </Typography>
                          )}
                        </TableCell>
                      )}
                      {isColumnaVisible("estado_evento") && (
                        <TableCell align="center">
                          {nota.estado_evento ? (
                            <Chip
                              label={nota.estado_evento}
                              title={alertaPorDocumento.get(nota.id)?.titulo || nota.mensaje_evento || undefined}
                              icon={alertaPorDocumento.has(nota.id) ? <Icon icon="mdi:alert" width={16} /> : undefined}
                              size="small"
                              variant="outlined"
                              color={
                                nota.estado_evento === "Aprobado"
                                  ? "success"
                                  : nota.estado_evento === "Rechazado"
                                    ? "error"
                                    : "warning"
                              }
                            />
                          ) : (
                            <Typography
                              variant="caption"
                              color="text.secondary"
                            >
                              -
                            </Typography>
                          )}
                        </TableCell>
                      )}
                      {isColumnaVisible("cdc") && (
                        <TableCell>
                          {nota.cdc ? (
                            <Tooltip title={nota.cdc}>
                              <Typography
                                variant="caption"
                                sx={{ fontFamily: "monospace" }}
                              >
                                {nota.cdc.substring(0, 20)}...
                              </Typography>
                            </Tooltip>
                          ) : (
                            <Typography
                              variant="caption"
                              color="text.secondary"
                            >
                              -
                            </Typography>
                          )}
                        </TableCell>
                      )}
                      {isColumnaVisible("acciones") && (
                        <TableCell
                          align="center"
                          onClick={(e) => e.stopPropagation()}
                        >
                          <Box
                            sx={{
                              display: "flex",
                              gap: 0.5,
                              justifyContent: "center",
                            }}
                          >
                            <Tooltip title="Ver detalle">
                              <IconButton
                                size="small"
                                onClick={() => handleOpenDetalle(nota)}
                              >
                                <Icon icon="mdi:eye" width={18} />
                              </IconButton>
                            </Tooltip>
                            <Tooltip title="Ver KUDE / Imprimir">
                              <IconButton
                                size="small"
                                color="primary"
                                onClick={(e) => {
                                  e.stopPropagation();
                                  setKudePreview({
                                    open: true,
                                    notaId: nota.id,
                                  });
                                }}
                              >
                                <Icon icon="mdi:file-pdf-box" width={18} />
                              </IconButton>
                            </Tooltip>
                            {!nota.estado_sifen && (
                              <Tooltip title="Editar">
                                <IconButton
                                  size="small"
                                  onClick={() =>
                                    navigate(
                                      `/ventas/notas-credito/${nota.id}/editar`,
                                    )
                                  }
                                >
                                  <Icon icon="mdi:pencil" width={18} />
                                </IconButton>
                              </Tooltip>
                            )}
                            {/* Menú de eventos SIFEN - solo para Aprobado o Rechazado */}
                            {canEventoSifenNC &&
                              (nota.estado_sifen === "Rechazado" ||
                                nota.estado_sifen === "Aprobado") && (
                              <Tooltip title="Eventos SIFEN">
                                <IconButton
                                  size="small"
                                  color="warning"
                                  onClick={(e) => {
                                    setNotaSeleccionada(nota);
                                    setEventoMenuAnchor(e.currentTarget);
                                  }}
                                >
                                  <Icon
                                    icon="mdi:file-document-alert"
                                    width={18}
                                  />
                                </IconButton>
                              </Tooltip>
                            )}
                          </Box>
                        </TableCell>
                      )}
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </TableContainer>
        )}

        {/* Paginación */}
        {total > limit && (
          <Box sx={{ display: "flex", justifyContent: "center", mt: 3 }}>
            <Button
              disabled={page === 1}
              onClick={() => setPage(page - 1)}
              startIcon={<Icon icon="mdi:chevron-left" />}
              size="small"
            >
              Anterior
            </Button>
            <Typography sx={{ mx: 2, alignSelf: "center" }}>
              Página {page} de {lastPage}
            </Typography>
            <Button
              disabled={page === lastPage}
              onClick={() => setPage(page + 1)}
              endIcon={<Icon icon="mdi:chevron-right" />}
              size="small"
            >
              Siguiente
            </Button>
          </Box>
        )}

        {/* Menú de eventos SIFEN */}
        <Menu
          anchorEl={eventoMenuAnchor}
          open={Boolean(eventoMenuAnchor)}
          onClose={() => setEventoMenuAnchor(null)}
        >
          {tieneEventoSifenPendiente(notaSeleccionada) && (
            <EventoSifenPendienteItem documento={notaSeleccionada} tipoDocumento="nota_credito" onCerrar={() => setEventoMenuAnchor(null)} />
          )}
          {canInutilizarNC && !tieneEventoSifenPendiente(notaSeleccionada) && notaSeleccionada?.estado_sifen === "Rechazado" && (
            <MenuItem
              onClick={() =>
                handleEventoSifen(notaSeleccionada, "inutilizacion")
              }
            >
              <ListItemIcon>
                <Icon icon="mdi:file-remove" width={20} />
              </ListItemIcon>
              <ListItemText
                primary="Inutilizar (EINU)"
                secondary="Para documentos rechazados"
              />
            </MenuItem>
          )}
          {canCancelarNC && !tieneEventoSifenPendiente(notaSeleccionada) && notaSeleccionada?.estado_sifen === "Aprobado" && (() => {
            const cancelable = !sifenActivo || esCancelableECAN(notaSeleccionada);
            return (
              <Tooltip title={sifenActivo && !cancelable ? "Han pasado más de 168 horas (7 días) desde el envío" : ""} placement="left">
                <span>
                  <MenuItem
                    disabled={!cancelable}
                    onClick={() => handleEventoSifen(notaSeleccionada, "cancelacion")}
                  >
                    <ListItemIcon>
                      <Icon icon="mdi:file-cancel" width={20} />
                    </ListItemIcon>
                    <ListItemText
                      primary="Cancelar (ECAN)"
                      secondary={sifenActivo ? "Dentro de 168h (7 días) del envío" : "Cancelación local (sin SIFEN)"}
                    />
                  </MenuItem>
                </span>
              </Tooltip>
            );
          })()}
        </Menu>

        {/* Diálogo de confirmación de evento */}
        <Dialog
          open={dialogEvento.open}
          onClose={() =>
            setDialogEvento({ open: false, tipo: null, motivo: "" })
          }
          maxWidth="sm"
          fullWidth
        >
          <DialogTitle>
            Confirmar{" "}
            {dialogEvento.tipo === "cancelacion"
              ? "Cancelación"
              : "Inutilización"}
          </DialogTitle>
          <DialogContent>
            <TextField
              autoFocus
              margin="dense"
              label="Motivo"
              fullWidth
              multiline
              rows={3}
              value={dialogEvento.motivo}
              onChange={(e) =>
                setDialogEvento((prev) => ({ ...prev, motivo: e.target.value }))
              }
              placeholder="Ingrese el motivo del evento..."
            />
          </DialogContent>
          <DialogActions>
            <Button
              onClick={() =>
                setDialogEvento({ open: false, tipo: null, motivo: "" })
              }
            >
              Cancelar
            </Button>
            <Button
              onClick={handleConfirmarEvento}
              variant="contained"
              disabled={
                !dialogEvento.motivo.trim() ||
                inutilizacionMutation.isLoading ||
                cancelacionMutation.isLoading
              }
            >
              Confirmar
            </Button>
          </DialogActions>
        </Dialog>

        {/* Diálogo de detalle de nota de crédito */}
        <NotaCreditoDetalleDialog
          open={detalleDialog.open}
          onClose={handleCloseDetalle}
          notaCredito={detalleDialog.notaCredito}
          navegacion={navegacionDetalle}
        />

        {/* Modal de preview KUDE */}
        <KudePreviewModal
          open={kudePreview.open}
          onClose={() => setKudePreview({ open: false, notaId: null })}
          documentoId={kudePreview.notaId}
          tipoDocumento={5}
          numeroDocumento={(() => {
            const nc = notasCredito.find((n) => n.id === kudePreview.notaId);
            return nc?.dnumdoc ? `${nc.dest}-${nc.dpunexp}-${nc.dnumdoc}` : undefined;
          })()}
        />

        {/* Snackbar para notificaciones */}
        <Snackbar
          open={snackbar.open}
          autoHideDuration={6000}
          onClose={() => setSnackbar({ ...snackbar, open: false })}
          message={snackbar.message}
          anchorOrigin={{ vertical: "top", horizontal: "right" }}
        />
      </Box>
    </LocalizationProvider>
  );
}
