import { CheckCircle, Download, FilterList, Person, Receipt, Refresh, Schedule, Search, Warning } from "@mui/icons-material";
import { Icon } from "@iconify/react";
import {
  Alert,
  Box,
  Button,
  Chip,
  CircularProgress,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  FormControlLabel,
  IconButton,
  InputAdornment,
  LinearProgress,
  Menu,
  MenuItem,
  Paper,
  Skeleton,
  Switch,
  Tab,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Tabs,
  TextField,
  ToggleButton,
  ToggleButtonGroup,
  Tooltip,
  Typography,
  useMediaQuery,
  useTheme,
} from "@mui/material";
import { useQuery } from "@tanstack/react-query";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import { toast } from "sonner";
import styled from "styled-components";
import {
  descargarDetalleCuentasPagar,
  descargarPlanPagosProveedores,
  getCuentasPagarCompleto,
  getCuentasPagarDashboard,
  getEstadoCuentaProveedor,
  getEstadoCuentaProveedorPdf,
} from "../api/pagos-proveedor.service";
import { AccesoRestringido } from "../components/common/AccesoRestringido";
import { usePermission } from "../hooks/usePermission";
import { fmtFechaCalendario, toFechaCalendarioISO } from "../utils/fecha";
import { sanitizeRecords } from "../components/_standards";
import * as XLSX from "xlsx";
import PropTypes from "prop-types";
import { ExtractoProveedor } from "../components/organismos/ComprasDesign/ExtractoProveedor";

const formatMoney = (value) =>
  new Intl.NumberFormat("es-PY", {
    style: "currency",
    currency: "PYG",
    minimumFractionDigits: 0,
  }).format(Number(value || 0));

// fecha_compra / fecha_vencimiento son fechas-CALENDARIO: formatear vía el estándar
// (extrae YMD por regex, sin `new Date(string)` que en UTC−3 corría el día — era la causa
// del "18/07 vs 19/07" entre la lista y el modal). Ver docs/ui-standards.md > Fechas.
const formatDate = (value) => fmtFechaCalendario(value, "-");

// "Hoy" como fecha-calendario local "YYYY-MM-DD" (partes locales, no toISOString → sin shift).
const hoyCalendarioISO = () => {
  const d = new Date();
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
};

// Vencida EN VIVO (TZ-safe): hay saldo pendiente y el vencimiento es anterior a hoy.
// Se calcula acá en vez de confiar en el `estado` guardado de la cuota (que puede quedar
// "pendiente" aunque ya venció, si el cron no lo actualizó) — así la lista, el grouping y
// el modal usan el mismo criterio que el KPI superior y el estado de cuenta.
const esCuotaVencida = (fechaVencimiento, saldoPendiente) => {
  if (!(Number(saldoPendiente) > 0)) return false;
  const venc = toFechaCalendarioISO(fechaVencimiento);
  return !!venc && venc < hoyCalendarioISO();
};

const formatCompraComprobante = (compra) => {
  if (!compra) return "S/N";
  const establecimiento = String(compra.establecimiento || "").trim();
  const punto = String(compra.punto_expedicion || "").trim();
  const numero = String(compra.numero_factura || "").trim();

  if (establecimiento && punto && numero) {
    return `${establecimiento.padStart(3, "0")}-${punto.padStart(3, "0")}-${numero.padStart(7, "0")}`;
  }

  return numero || "S/N";
};

const getHoy = () => {
  const d = new Date();
  return d.toISOString().slice(0, 10);
};

const estadoChip = (estadoRaw) => {
  const estado = String(estadoRaw || "").toLowerCase();
  if (estado === "pagada") return { label: "Pagada", color: "success" };
  if (estado === "parcial") return { label: "Parcial", color: "warning" };
  if (estado === "vencida") return { label: "Vencida", color: "error" };
  if (estado === "anulada") return { label: "Anulada", color: "default" };
  return { label: "Pendiente", color: "info" };
};

function TabPanel({ children, value, index }) {
  return (
    <div role="tabpanel" hidden={value !== index}>
      {value === index && <Box sx={{ pt: 0 }}>{children}</Box>}
    </div>
  );
}

const REPORTES_EXCEL = {
  detalle: {
    titulo: "Detalle por proveedor",
    ayuda: "Cada comprobante pendiente con sus cuotas, los pagos parciales que ya recibió y la antigüedad de la deuda.",
  },
  plan: {
    titulo: "Plan de pagos por mes",
    ayuda: "Lo pendiente ubicado en el mes en que vence, con el total a pagar de cada mes.",
  },
};

const MESES_PLAN = [3, 6, 12];

function ExportarReporteDialog({ tipo, proveedores, filtrado, onClose }) {
  const [soloEnPantalla, setSoloEnPantalla] = useState(filtrado && proveedores.length > 0);
  const [soloVencidas, setSoloVencidas] = useState(false);
  const [meses, setMeses] = useState(3);
  const [descargando, setDescargando] = useState(false);
  const reporte = REPORTES_EXCEL[tipo];

  const descargar = async () => {
    setDescargando(true);
    try {
      const proveedorIds = soloEnPantalla ? proveedores.map((p) => p.proveedor_id).filter(Boolean) : undefined;
      const blob =
        tipo === "detalle"
          ? await descargarDetalleCuentasPagar({ proveedorIds, soloVencidas })
          : await descargarPlanPagosProveedores({ proveedorIds, meses });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `${tipo === "detalle" ? "cuentas-pagar-detalle" : "plan-pagos-proveedores"}-${getHoy()}.xlsx`;
      a.click();
      URL.revokeObjectURL(url);
      toast.success(`${reporte.titulo} descargado`);
      onClose();
    } catch (e) {
      console.error(e);
      toast.error("No se pudo generar el reporte", { action: { label: "Reintentar", onClick: descargar } });
    } finally {
      setDescargando(false);
    }
  };

  return (
    <Dialog open onClose={() => !descargando && onClose()} maxWidth="xs" fullWidth>
      <DialogTitle>{reporte.titulo}</DialogTitle>
      <DialogContent sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}>
        <Typography variant="body2" color="text.secondary">{reporte.ayuda}</Typography>
        <FormControlLabel
          control={<Switch checked={soloEnPantalla} onChange={(e) => setSoloEnPantalla(e.target.checked)} disabled={!proveedores.length} />}
          label={
            proveedores.length
              ? `Solo los ${proveedores.length} proveedores que se ven en pantalla`
              : "No hay proveedores en pantalla: se exportan todos"
          }
        />
        {tipo === "detalle" && (
          <FormControlLabel
            control={<Switch checked={soloVencidas} onChange={(e) => setSoloVencidas(e.target.checked)} />}
            label="Solo cuotas vencidas"
          />
        )}
        {tipo === "plan" && (
          <TextField select size="small" label="Meses a mostrar" value={meses} onChange={(e) => setMeses(Number(e.target.value))}
            helperText="Desde el mes actual. Lo que vence después va en la columna «Después».">
            {MESES_PLAN.map((m) => <MenuItem key={m} value={m}>{m} meses</MenuItem>)}
          </TextField>
        )}
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose} disabled={descargando}>Cancelar</Button>
        <Button variant="contained" onClick={descargar} disabled={descargando}
          startIcon={descargando ? <CircularProgress size={16} color="inherit" /> : <Download />}>
          Descargar Excel
        </Button>
      </DialogActions>
    </Dialog>
  );
}

function ExportButton({ proveedoresData, cuotasData, filtrado }) {
  const [anchor, setAnchor] = useState(null);
  const [reporte, setReporte] = useState(null); // "detalle" | "plan"

  // Excel con las dos vistas, sea cual sea la pestaña abierta: el resumen por proveedor y
  // todas las cuotas con saldo (vencidas y por vencer), con los filtros de la pantalla.
  // Mismo criterio que Cuentas por Cobrar (pedido Misterhome, oct-2026); antes era un CSV
  // de la pestaña activa con el estado interno ("pendiente", "parcial").
  const handleExport = () => {
    try {
      if (!proveedoresData?.length && !cuotasData?.length) {
        toast.info("No hay datos para exportar");
        return;
      }
      const hoy = hoyCalendarioISO();
      const estadoCuota = (r) => {
        if (r.vencida) return "Vencida";
        if (Number(r.saldo_pendiente) > 0) return "Por vencer";
        return estadoChip(r.estado).label;
      };
      const diasMora = (r) => {
        const venc = toFechaCalendarioISO(r.fecha_vencimiento);
        if (!r.vencida || !venc) return 0;
        return Math.max(0, Math.round((new Date(`${hoy}T00:00:00`) - new Date(`${venc}T00:00:00`)) / 86400000));
      };

      const proveedoresRows = (proveedoresData || []).map((r) => ({
        Proveedor: r.razon_social || "",
        RUC: r.ruc || "",
        Cuotas: r.cuotas_totales || 0,
        Vencidas: r.cuotas_vencidas || 0,
        "Saldo Total (Gs)": Math.round(Number(r.saldo_total || 0)),
        "Saldo Vencido (Gs)": Math.round(Number(r.saldo_vencido || 0)),
        "Monto Pagado (Gs)": Math.round(Number(r.monto_pagado || 0)),
      }));
      const cuotasRows = [...(cuotasData || [])]
        .sort((a, b) => String(toFechaCalendarioISO(a.fecha_vencimiento) || "").localeCompare(String(toFechaCalendarioISO(b.fecha_vencimiento) || "")))
        .map((r) => ({
          Proveedor: r.proveedor?.razon_social || "",
          RUC: r.proveedor?.ruc || "",
          Factura: r.factura || "",
          "Fecha Compra": r.fecha_compra ? formatDate(r.fecha_compra) : "",
          Cuota: r.numero_cuota || 1,
          Vencimiento: r.fecha_vencimiento ? formatDate(r.fecha_vencimiento) : "",
          Estado: estadoCuota(r),
          "Días Mora": diasMora(r),
          "Monto Original (Gs)": Math.round(Number(r.monto_original || 0)),
          "Monto Pagado (Gs)": Math.round(Number(r.monto_pagado || 0)),
          "Saldo Pendiente (Gs)": Math.round(Number(r.saldo_pendiente || 0)),
        }));

      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, XLSX.utils.json_to_sheet(sanitizeRecords(proveedoresRows)), "Proveedores");
      XLSX.utils.book_append_sheet(wb, XLSX.utils.json_to_sheet(sanitizeRecords(cuotasRows)), "Cuotas pendientes");
      XLSX.writeFile(wb, `cuentas_pagar_${getHoy()}.xlsx`);
      toast.success("Exportado correctamente");
    } catch (e) {
      console.error(e);
      toast.error("No se pudo exportar");
    }
  };

  const abrir = (tipo) => {
    setAnchor(null);
    if (tipo === "resumen") handleExport();
    else setReporte(tipo);
  };

  return (
    <>
      <ExportBtn onClick={(e) => setAnchor(e.currentTarget)} aria-haspopup="menu">
        <Download style={{ width: 15, height: 15 }} />
        Exportar
      </ExportBtn>
      <Menu anchorEl={anchor} open={Boolean(anchor)} onClose={() => setAnchor(null)}>
        <MenuItem onClick={() => abrir("resumen")}>
          Proveedores y cuotas pendientes (Excel)
        </MenuItem>
        <MenuItem onClick={() => abrir("detalle")}>{REPORTES_EXCEL.detalle.titulo} (Excel)</MenuItem>
        <MenuItem onClick={() => abrir("plan")}>{REPORTES_EXCEL.plan.titulo} (Excel)</MenuItem>
      </Menu>
      {reporte && (
        <ExportarReporteDialog tipo={reporte} proveedores={proveedoresData || []} filtrado={filtrado} onClose={() => setReporte(null)} />
      )}
    </>
  );
}

ExportButton.propTypes = {
  proveedoresData: PropTypes.array,
  cuotasData: PropTypes.array,
  filtrado: PropTypes.bool,
};

export default function CuentasPagar() {
  const theme = useTheme();
  const navigate = useNavigate();
  const isMobile = useMediaQuery(theme.breakpoints.down("sm"));
  const isTablet = useMediaQuery(theme.breakpoints.down("md"));
  const { canRead: canReadReportes } = usePermission("REPORTES");
  const { canRead: canReadCompras } = usePermission("COMPRAS");
  const { canRead: canReadTesoreria } = usePermission("TESORERIA");

  const [tabValue, setTabValue] = useState(0);
  const [search, setSearch] = useState("");
  const [filtroEstado, setFiltroEstado] = useState("todos");
  const [filtroVencimiento, setFiltroVencimiento] = useState("todos");
  // Sin fechas por defecto: la deuda no depende del mes en que se emitió la factura.
  // Con el mes actual, la pantalla mostraba solo lo emitido este mes (p. ej. 11 M de 467 M).
  const [fechaDesde, setFechaDesde] = useState("");
  const [fechaHasta, setFechaHasta] = useState("");
  const [pageProveedores, setPageProveedores] = useState(1);
  const [pageCuotas, setPageCuotas] = useState(1);
  const [estadoCuenta, setEstadoCuenta] = useState(null); // { proveedorId, nombre }
  const [proveedorDetalle, setProveedorDetalle] = useState(null); // fila proveedor
  const ROWS_PER_PAGE = 15;

  const cuentasParams = useMemo(
    () => ({
      fecha_desde: fechaDesde || undefined,
      fecha_hasta: fechaHasta || undefined,
      fecha_tipo: "emision",
      estado: filtroEstado === "todos" ? undefined : filtroEstado,
      busqueda: search || undefined,
    }),
    [fechaDesde, fechaHasta, filtroEstado, search],
  );

  const {
    data: dashboardData,
    isLoading: loadingDashboard,
    refetch: refetchDashboard,
  } = useQuery({
    queryKey: ["cxp-dashboard-report", fechaDesde, fechaHasta],
    queryFn: () =>
      getCuentasPagarDashboard({
        fecha_desde: fechaDesde || undefined,
        fecha_hasta: fechaHasta || undefined,
        fecha_tipo: "emision",
      }),
    staleTime: 2 * 60 * 1000,
  });

  const {
    data: cuentasData,
    isLoading: loadingCuentas,
    refetch: refetchCuentas,
  } = useQuery({
    queryKey: ["cxp-resumen", cuentasParams],
    queryFn: () => getCuentasPagarCompleto(cuentasParams),
  });

  const cuentasRaw = useMemo(() => cuentasData?.items || [], [cuentasData]);

  const cuotasFiltradas = useMemo(() => {
    let list = cuentasRaw.map((c) => {
      const proveedorRuc = c?.proveedores?.personas?.ruc ? `${c.proveedores.personas.ruc}-${c.proveedores.personas.dv || 0}` : "";
      return {
        id: c.id,
        proveedor: {
          id: c?.proveedor_id || c?.proveedores?.id || null,
          razon_social: c?.proveedores?.personas?.razon_social || "Sin proveedor",
          ruc: proveedorRuc,
        },
        factura: formatCompraComprobante(c?.compra_cab),
        fecha_compra: c?.compra_cab?.fecha_emision,
        numero_cuota: c?.numero_cuota || 1,
        fecha_vencimiento: c?.fecha_vencimiento,
        estado: c?.estado || "pendiente",
        vencida: esCuotaVencida(c?.fecha_vencimiento, Number(c?.saldo_pendiente || 0)),
        monto_original: Number(c?.monto_original || 0),
        monto_pagado: Number(c?.monto_pagado || 0),
        saldo_pendiente: Number(c?.saldo_pendiente || 0),
      };
    });

    // Con filtro "todos" mostramos solo lo que realmente se debe (saldo > 0):
    // las pagadas/anuladas no son cuentas por pagar. Si el usuario elige un
    // estado explícito (ej. "pagada"), el backend ya devuelve ese conjunto.
    if (filtroEstado === "todos") {
      list = list.filter((c) => c.saldo_pendiente > 0 && String(c.estado || "").toLowerCase() !== "anulada");
    }

    if (search.trim()) {
      const q = search.toLowerCase();
      list = list.filter((c) => c.proveedor.razon_social.toLowerCase().includes(q) || c.proveedor.ruc.toLowerCase().includes(q) || c.factura.toLowerCase().includes(q));
    }

    if (filtroVencimiento !== "todos") {
      const hoy = new Date();
      hoy.setHours(0, 0, 0, 0);
      const dias = filtroVencimiento === "manana" ? 1 : filtroVencimiento === "7d" ? 7 : filtroVencimiento === "15d" ? 15 : 30;
      const limite = new Date(hoy);
      limite.setDate(limite.getDate() + dias);

      list = list.filter((c) => {
        if (!c.fecha_vencimiento) return false;
        const fv = new Date(c.fecha_vencimiento);
        if (Number.isNaN(fv.getTime())) return false;
        fv.setHours(0, 0, 0, 0);
        return fv >= hoy && fv <= limite;
      });
    }

    return list;
  }, [cuentasRaw, search, filtroVencimiento, filtroEstado]);

  const proveedoresFiltrados = useMemo(() => {
    const map = new Map();

    cuotasFiltradas.forEach((c) => {
      const key = `${c.proveedor.razon_social}|${c.proveedor.ruc}`;
      if (!map.has(key)) {
        map.set(key, {
          id: key,
          proveedor_id: c.proveedor.id,
          razon_social: c.proveedor.razon_social,
          ruc: c.proveedor.ruc,
          cuotas_totales: 0,
          cuotas_vencidas: 0,
          saldo_total: 0,
          saldo_vencido: 0,
          monto_pagado: 0,
        });
      }
      const row = map.get(key);
      row.cuotas_totales += 1;
      row.saldo_total += c.saldo_pendiente;
      row.monto_pagado += c.monto_pagado;
      if (c.vencida) {
        row.cuotas_vencidas += 1;
        row.saldo_vencido += c.saldo_pendiente;
      }
    });

    return Array.from(map.values()).sort((a, b) => b.saldo_total - a.saldo_total);
  }, [cuotasFiltradas]);

  const totalPagesProveedores = Math.ceil(proveedoresFiltrados.length / ROWS_PER_PAGE) || 1;
  const totalPagesCuotas = Math.ceil(cuotasFiltradas.length / ROWS_PER_PAGE) || 1;

  const proveedoresPaginados = useMemo(() => {
    const start = (pageProveedores - 1) * ROWS_PER_PAGE;
    return proveedoresFiltrados.slice(start, start + ROWS_PER_PAGE);
  }, [proveedoresFiltrados, pageProveedores]);

  const cuotasPaginadas = useMemo(() => {
    const start = (pageCuotas - 1) * ROWS_PER_PAGE;
    return cuotasFiltradas.slice(start, start + ROWS_PER_PAGE);
  }, [cuotasFiltradas, pageCuotas]);

  const isLoading = loadingCuentas;

  const handleRefresh = () => {
    refetchDashboard();
    refetchCuentas();
  };

  if (!canReadReportes || (!canReadCompras && !canReadTesoreria)) {
    return <AccesoRestringido mensaje="No tienes permisos para ver cuentas por pagar." />;
  }

  return (
    <Container>
      <Header>
        <HeaderContent>
          <BackBtn onClick={() => navigate("/reportes")}>
            <Icon icon="lucide:arrow-left" />
          </BackBtn>
          <TitleSection>
            <MainTitle>
              <Icon icon="lucide:wallet-cards" />
              Cuentas por Pagar
            </MainTitle>
            <Subtitle>Análisis de obligaciones, vencimientos y estado de pagos a proveedores</Subtitle>
          </TitleSection>
          <HeaderActions>
            <ExportButton proveedoresData={proveedoresFiltrados} cuotasData={cuotasFiltradas}
              filtrado={Boolean(search) || filtroEstado !== "todos" || filtroVencimiento !== "todos"} />
            <Tooltip title="Actualizar datos">
              <IconButton size="small" onClick={handleRefresh} sx={{ color: "inherit" }}>
                <Refresh fontSize="small" />
              </IconButton>
            </Tooltip>
          </HeaderActions>
        </HeaderContent>
        <Breadcrumb>
          <BreadcrumbLink onClick={() => navigate("/reportes")}>Reportes</BreadcrumbLink>
          <Icon icon="lucide:chevron-right" style={{ width: 12, height: 12, opacity: 0.5 }} />
          <BreadcrumbCurrent>Cuentas por Pagar</BreadcrumbCurrent>
        </Breadcrumb>
      </Header>

      <Content>
        <Paper
          elevation={0}
          sx={{
            p: { xs: 1.5, sm: 2 },
            borderRadius: 2,
            border: "1px solid",
            borderColor: "divider",
            mb: 2,
          }}
        >
          <Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr 1fr", md: "repeat(6, 1fr)" }, gap: 1.5 }}>
            <MetricCard title="Total Cuentas" value={loadingDashboard ? <Skeleton width={40} /> : dashboardData?.total || 0} icon={<Receipt fontSize="small" />} />
            <MetricCard title="Pendientes" value={loadingDashboard ? <Skeleton width={40} /> : dashboardData?.pendientes || 0} icon={<Schedule fontSize="small" />} color="info.main" />
            <MetricCard title="Pagadas" value={loadingDashboard ? <Skeleton width={40} /> : dashboardData?.pagadas || 0} icon={<CheckCircle fontSize="small" />} color="success.main" />
            <MetricCard title="Vencidas" value={loadingDashboard ? <Skeleton width={40} /> : dashboardData?.vencidas || 0} icon={<Warning fontSize="small" />} color="error.main" />
            <MetricCard title="Saldo Pendiente" value={loadingDashboard ? <Skeleton width={80} /> : formatMoney(dashboardData?.saldo_pendiente_total)} color="warning.main" />
            <MetricCard title="Monto Pagado" value={loadingDashboard ? <Skeleton width={80} /> : formatMoney(dashboardData?.monto_pagado_total)} color="success.main" />
          </Box>
        </Paper>

        <Paper
          elevation={0}
          sx={{
            borderRadius: 2,
            border: "1px solid",
            borderColor: "divider",
            overflow: "hidden",
          }}
        >
          <Box
            sx={{
              p: { xs: 1.5, sm: 2 },
              display: "flex",
              flexWrap: "wrap",
              gap: 1.2,
              borderBottom: "1px solid",
              borderColor: "divider",
            }}
          >
            <TextField
              size="small"
              placeholder="Buscar proveedor, RUC o factura..."
              value={search}
              onChange={(e) => {
                setSearch(e.target.value);
                setPageProveedores(1);
                setPageCuotas(1);
              }}
              sx={{ flex: 1, minWidth: 200 }}
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start">
                    <Search fontSize="small" color="action" />
                  </InputAdornment>
                ),
              }}
            />
            <TextField
              select
              size="small"
              value={filtroEstado}
              onChange={(e) => {
                setFiltroEstado(e.target.value);
                setPageProveedores(1);
                setPageCuotas(1);
              }}
              sx={{ minWidth: 160 }}
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start">
                    <FilterList fontSize="small" color="action" />
                  </InputAdornment>
                ),
              }}
            >
              <MenuItem value="todos">Todos los estados</MenuItem>
              <MenuItem value="pendiente">Pendiente</MenuItem>
              <MenuItem value="parcial">Parcial</MenuItem>
              <MenuItem value="pagada">Pagada</MenuItem>
              <MenuItem value="vencida">Vencida</MenuItem>
              <MenuItem value="anulada">Anulada</MenuItem>
            </TextField>
            <TextField
              select
              size="small"
              value={filtroVencimiento}
              onChange={(e) => {
                setFiltroVencimiento(e.target.value);
                setPageCuotas(1);
              }}
              sx={{ minWidth: 170 }}
            >
              <MenuItem value="todos">Todos los plazos</MenuItem>
              <MenuItem value="manana">Vence mañana</MenuItem>
              <MenuItem value="7d">Próximos 7 días</MenuItem>
              <MenuItem value="15d">Próximos 15 días</MenuItem>
              <MenuItem value="30d">Próximos 30 días</MenuItem>
            </TextField>
            <TextField size="small" type="date" label="Emitidas desde" value={fechaDesde} onChange={(e) => setFechaDesde(e.target.value)} InputLabelProps={{ shrink: true }} sx={{ minWidth: 155 }} />
            <TextField size="small" type="date" label="Emitidas hasta" value={fechaHasta} onChange={(e) => setFechaHasta(e.target.value)} InputLabelProps={{ shrink: true }} sx={{ minWidth: 155 }} />
            {(fechaDesde || fechaHasta) && (
              <Button size="small" onClick={() => { setFechaDesde(""); setFechaHasta(""); }} sx={{ textTransform: "none" }} startIcon={<Icon icon="lucide:x" width={14} />}>
                Todas las fechas
              </Button>
            )}
          </Box>

          <Box
            sx={{
              display: "flex",
              alignItems: "center",
              borderBottom: 1,
              borderColor: "divider",
              px: { xs: 1, sm: 2 },
            }}
          >
            <Tabs value={tabValue} onChange={(e, v) => setTabValue(v)} sx={{ flex: 1 }} variant={isMobile ? "fullWidth" : "standard"}>
              <Tab icon={<Person sx={{ fontSize: 18 }} />} iconPosition="start" label={isMobile ? "Prov." : "Por Proveedor"} sx={{ textTransform: "none", fontWeight: 600, minHeight: 48 }} />
              <Tab icon={<Receipt sx={{ fontSize: 18 }} />} iconPosition="start" label={isMobile ? "Cuotas" : "Todas las Cuotas"} sx={{ textTransform: "none", fontWeight: 600, minHeight: 48 }} />
            </Tabs>
          </Box>

          <TabPanel value={tabValue} index={0}>
            <TableContainer sx={{ maxHeight: "calc(100vh - 520px)" }}>
              <Table size="small" stickyHeader>
                <TableHead>
                  <TableRow>
                    <TableCell sx={{ fontWeight: 700 }}>Proveedor</TableCell>
                    {!isMobile && <TableCell sx={{ fontWeight: 700 }}>RUC</TableCell>}
                    <TableCell align="center" sx={{ fontWeight: 700 }}>
                      Cuotas
                    </TableCell>
                    <TableCell align="center" sx={{ fontWeight: 700 }}>
                      Vencidas
                    </TableCell>
                    <TableCell align="right" sx={{ fontWeight: 700 }}>
                      Saldo Total
                    </TableCell>
                    <TableCell align="right" sx={{ fontWeight: 700 }}>
                      Saldo Vencido
                    </TableCell>
                    {!isTablet && (
                      <TableCell sx={{ fontWeight: 700 }} align="center">
                        Salud
                      </TableCell>
                    )}
                    {!isMobile && (
                      <TableCell sx={{ fontWeight: 700 }} align="center">
                        Acciones
                      </TableCell>
                    )}
                  </TableRow>
                </TableHead>
                <TableBody>
                  {isLoading ? (
                    <TableRow>
                      <TableCell colSpan={8}>
                        <Skeleton height={38} />
                        <Skeleton height={38} />
                        <Skeleton height={38} />
                      </TableCell>
                    </TableRow>
                  ) : proveedoresPaginados.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={8} align="center" sx={{ py: 4 }}>
                        <Alert severity="info" sx={{ justifyContent: "center" }}>
                          No se encontraron cuentas por pagar con los filtros aplicados
                        </Alert>
                      </TableCell>
                    </TableRow>
                  ) : (
                    proveedoresPaginados.map((p) => {
                      const healthPct = p.saldo_total > 0 ? Math.round((p.saldo_vencido / p.saldo_total) * 100) : 0;
                      const healthColor = healthPct === 0 ? "success" : healthPct < 50 ? "warning" : "error";

                      return (
                        <TableRow
                          key={p.id}
                          onClick={() => p.proveedor_id && setProveedorDetalle(p)}
                          sx={{
                            cursor: p.proveedor_id ? "pointer" : "default",
                            borderLeft: 3,
                            borderLeftColor: p.saldo_vencido > 0 ? "error.main" : "success.main",
                            "&:hover": { bgcolor: "action.hover" },
                          }}
                        >
                          <TableCell>
                            <Typography variant="body2" fontWeight={600}>
                              {p.razon_social}
                            </Typography>
                          </TableCell>
                          {!isMobile && (
                            <TableCell>
                              <Typography variant="body2">{p.ruc || "-"}</Typography>
                            </TableCell>
                          )}
                          <TableCell align="center">
                            <Chip label={`${p.cuotas_totales}`} size="small" variant="outlined" sx={{ fontWeight: 600, minWidth: 32 }} />
                          </TableCell>
                          <TableCell align="center">
                            {p.cuotas_vencidas > 0 ? (
                              <Chip label={p.cuotas_vencidas} color="error" size="small" sx={{ fontWeight: 700, minWidth: 32 }} />
                            ) : (
                              <Chip label="0" color="success" size="small" variant="outlined" sx={{ minWidth: 32 }} />
                            )}
                          </TableCell>
                          <TableCell align="right">
                            <Typography variant="body2" fontWeight={600}>
                              {formatMoney(p.saldo_total)}
                            </Typography>
                          </TableCell>
                          <TableCell align="right">
                            {p.saldo_vencido > 0 ? (
                              <Typography variant="body2" fontWeight={700} color="error.main">
                                {formatMoney(p.saldo_vencido)}
                              </Typography>
                            ) : (
                              <Typography variant="body2" color="success.main" fontWeight={500}>
                                Al día
                              </Typography>
                            )}
                          </TableCell>
                          {!isTablet && (
                            <TableCell align="center">
                              <Box
                                sx={{
                                  display: "flex",
                                  alignItems: "center",
                                  gap: 1,
                                }}
                              >
                                <LinearProgress
                                  variant="determinate"
                                  value={healthPct}
                                  color={healthColor}
                                  sx={{
                                    flex: 1,
                                    height: 6,
                                    borderRadius: 3,
                                    bgcolor: "action.hover",
                                  }}
                                />
                                <Typography variant="caption" fontWeight={600} color={`${healthColor}.main`} sx={{ minWidth: 28 }}>
                                  {healthPct}%
                                </Typography>
                              </Box>
                            </TableCell>
                          )}
                          {!isMobile && (
                            <TableCell align="center" onClick={(e) => e.stopPropagation()}>
                              <Tooltip title="Estado de Cuenta PDF">
                                <span>
                                  <IconButton size="small" disabled={!p.proveedor_id} onClick={() => setEstadoCuenta({ proveedorId: p.proveedor_id, nombre: p.razon_social })}>
                                    <Icon icon="mdi:printer" width={18} />
                                  </IconButton>
                                </span>
                              </Tooltip>
                            </TableCell>
                          )}
                        </TableRow>
                      );
                    })
                  )}
                </TableBody>
              </Table>
            </TableContainer>
            {proveedoresFiltrados.length > ROWS_PER_PAGE && (
              <PaginationBar page={pageProveedores} totalPages={totalPagesProveedores} totalItems={proveedoresFiltrados.length} rowsPerPage={ROWS_PER_PAGE} onPageChange={setPageProveedores} />
            )}
          </TabPanel>

          <TabPanel value={tabValue} index={1}>
            <TableContainer sx={{ maxHeight: "calc(100vh - 520px)" }}>
              <Table size="small" stickyHeader>
                <TableHead>
                  <TableRow>
                    <TableCell sx={{ fontWeight: 700 }}>Proveedor</TableCell>
                    {!isMobile && <TableCell sx={{ fontWeight: 700 }}>Factura</TableCell>}
                    {!isMobile && <TableCell sx={{ fontWeight: 700 }}>F. compra</TableCell>}
                    <TableCell align="center" sx={{ fontWeight: 700 }}>
                      Cuota
                    </TableCell>
                    <TableCell sx={{ fontWeight: 700 }}>Vencimiento</TableCell>
                    <TableCell align="center" sx={{ fontWeight: 700 }}>
                      Estado
                    </TableCell>
                    <TableCell align="right" sx={{ fontWeight: 700 }}>
                      Monto
                    </TableCell>
                    <TableCell align="right" sx={{ fontWeight: 700 }}>
                      Pagado
                    </TableCell>
                    <TableCell align="right" sx={{ fontWeight: 700 }}>
                      Saldo
                    </TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {isLoading ? (
                    <TableRow>
                      <TableCell colSpan={9}>
                        <Skeleton height={38} />
                        <Skeleton height={38} />
                        <Skeleton height={38} />
                      </TableCell>
                    </TableRow>
                  ) : cuotasPaginadas.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={9} align="center" sx={{ py: 4 }}>
                        <Alert severity="info" sx={{ justifyContent: "center" }}>
                          No se encontraron cuotas con los filtros aplicados
                        </Alert>
                      </TableCell>
                    </TableRow>
                  ) : (
                    cuotasPaginadas.map((c) => {
                      // Vencida en vivo tiene prioridad sobre el estado guardado (que puede
                      // seguir "pendiente"/"parcial" aunque ya venció). Consistente con el modal.
                      const chip = c.vencida ? estadoChip("vencida") : estadoChip(c.estado);
                      return (
                        <TableRow
                          key={c.id}
                          sx={{
                            borderLeft: 3,
                            borderLeftColor: chip.color === "error" ? "error.main" : chip.color === "success" ? "success.main" : "warning.main",
                            "&:hover": { bgcolor: "action.hover" },
                          }}
                        >
                          <TableCell>
                            <Typography variant="body2" fontWeight={500}>
                              {c.proveedor.razon_social}
                            </Typography>
                            {isMobile && (
                              <Box sx={{ display: "flex", flexDirection: "column" }}>
                                <Typography variant="caption" color="text.secondary">
                                  {c.factura}
                                </Typography>
                                <Typography variant="caption" color="text.secondary">
                                  Compra: {formatDate(c.fecha_compra)}
                                </Typography>
                              </Box>
                            )}
                          </TableCell>
                          {!isMobile && (
                            <TableCell>
                              <Typography variant="body2" sx={{ fontFamily: "monospace", fontSize: "0.8rem" }}>
                                {c.factura}
                              </Typography>
                            </TableCell>
                          )}
                          {!isMobile && (
                            <TableCell>
                              <Typography variant="body2">{formatDate(c.fecha_compra)}</Typography>
                            </TableCell>
                          )}
                          <TableCell align="center">
                            <Chip label={`#${c.numero_cuota}`} size="small" variant="outlined" sx={{ fontWeight: 600 }} />
                          </TableCell>
                          <TableCell>
                            <Typography variant="body2">{formatDate(c.fecha_vencimiento)}</Typography>
                          </TableCell>
                          <TableCell align="center">
                            <Chip label={chip.label} color={chip.color} size="small" sx={{ fontWeight: 600, fontSize: "0.7rem" }} />
                          </TableCell>
                          <TableCell align="right">
                            <Typography variant="body2">{formatMoney(c.monto_original)}</Typography>
                          </TableCell>
                          <TableCell align="right">
                            <Typography variant="body2" color="success.main">
                              {formatMoney(c.monto_pagado)}
                            </Typography>
                          </TableCell>
                          <TableCell align="right">
                            <Typography variant="body2" fontWeight={700}>
                              {formatMoney(c.saldo_pendiente)}
                            </Typography>
                          </TableCell>
                        </TableRow>
                      );
                    })
                  )}
                </TableBody>
              </Table>
            </TableContainer>
            {cuotasFiltradas.length > ROWS_PER_PAGE && (
              <PaginationBar page={pageCuotas} totalPages={totalPagesCuotas} totalItems={cuotasFiltradas.length} rowsPerPage={ROWS_PER_PAGE} onPageChange={setPageCuotas} />
            )}
          </TabPanel>
        </Paper>
      </Content>

      <EstadoCuentaProveedorModal open={!!estadoCuenta} proveedorId={estadoCuenta?.proveedorId} nombre={estadoCuenta?.nombre} onClose={() => setEstadoCuenta(null)} />

      <ProveedorDetalleModal
        proveedor={proveedorDetalle}
        onClose={() => setProveedorDetalle(null)}
        onEstadoCuenta={(p) => {
          setProveedorDetalle(null);
          setEstadoCuenta({ proveedorId: p.proveedor_id, nombre: p.razon_social });
        }}
      />
    </Container>
  );
}

// ─── Modal de detalle del proveedor (cuotas por pagar) ────────────────────────
function ProveedorDetalleModal({ proveedor, onClose, onEstadoCuenta }) {
  const open = !!proveedor;
  const { data, isLoading } = useQuery({
    queryKey: ["cxp-estado-cuenta", proveedor?.proveedor_id],
    queryFn: () => getEstadoCuentaProveedor(proveedor.proveedor_id),
    enabled: open && !!proveedor?.proveedor_id,
  });

  const resumen = data?.resumen;
  const documentos = data?.facturas || [];
  // KPIs desde el MISMO endpoint que alimenta el detalle de cuotas (cálculo de "vencida" en
  // vivo). Antes se priorizaba `proveedor.saldo_vencido` (de la lista, con estado guardado):
  // daba 0 y, como `0 ?? x` no cae al fallback, el KPI mostraba "Al día" contradiciendo su
  // propio detalle "Vencida". Ahora ambos salen de `resumen`, así no se contradicen.
  const saldoTotal = resumen?.total_pendiente ?? proveedor?.saldo_total ?? 0;
  const saldoVencido = resumen?.total_vencido ?? proveedor?.saldo_vencido ?? 0;
  const healthPct = saldoTotal > 0 ? Math.round((saldoVencido / saldoTotal) * 100) : 0;
  const healthColor = healthPct === 0 ? "success" : healthPct < 50 ? "warning" : "error";

  // Aplanar cuotas de todos los documentos.
  const cuotas = documentos.flatMap((d) => (d.cuotas || []).map((c) => ({ ...c, documento: d.numero, tipo_doc: d.tipo_doc })));
  const cuotasVencidas = cuotas.filter((c) => c.estado === "Vencida").length;

  return (
    <Dialog open={open} onClose={onClose} maxWidth="md" fullWidth>
      <DialogTitle sx={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", pb: 1 }}>
        <Box sx={{ display: "flex", alignItems: "center", gap: 1.5 }}>
          <Box sx={{ width: 40, height: 40, borderRadius: 2, bgcolor: "primary.main", display: "flex", alignItems: "center", justifyContent: "center" }}>
            <Person sx={{ color: "white" }} />
          </Box>
          <Box>
            <Typography variant="h6" fontWeight={700} sx={{ lineHeight: 1.2 }}>
              {proveedor?.razon_social}
            </Typography>
            <Typography variant="caption" color="text.secondary">
              RUC: {proveedor?.ruc || "-"}
            </Typography>
          </Box>
        </Box>
        <IconButton onClick={onClose} size="small">
          <Icon icon="mdi:close" width={20} />
        </IconButton>
      </DialogTitle>
      <DialogContent dividers>
        {/* KPIs */}
        <Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr 1fr", sm: "repeat(4, 1fr)" }, gap: 1.5, mb: 2.5 }}>
          <Paper elevation={0} sx={{ p: 2, borderRadius: 2, border: "1px solid", borderColor: "divider", textAlign: "center" }}>
            <Typography variant="caption" color="text.secondary">
              Saldo Total
            </Typography>
            <Typography variant="h6" fontWeight={700} color="primary.main">
              {formatMoney(saldoTotal)}
            </Typography>
          </Paper>
          <Paper
            elevation={0}
            sx={{ p: 2, borderRadius: 2, border: "1px solid", borderColor: saldoVencido > 0 ? "error.main" : "divider", textAlign: "center", bgcolor: saldoVencido > 0 ? "error.main" : "transparent" }}
          >
            <Typography variant="caption" sx={{ color: saldoVencido > 0 ? "white" : "text.secondary" }}>
              Saldo Vencido
            </Typography>
            <Typography variant="h6" fontWeight={700} sx={{ color: saldoVencido > 0 ? "white" : "success.main" }}>
              {saldoVencido > 0 ? formatMoney(saldoVencido) : "Al día"}
            </Typography>
          </Paper>
          <Paper elevation={0} sx={{ p: 2, borderRadius: 2, border: "1px solid", borderColor: "divider", textAlign: "center" }}>
            <Typography variant="caption" color="text.secondary">
              Comprobantes
            </Typography>
            <Typography variant="h6" fontWeight={700}>
              {resumen?.facturas_pendientes ?? documentos.length}
            </Typography>
          </Paper>
          <Paper elevation={0} sx={{ p: 2, borderRadius: 2, border: "1px solid", borderColor: "divider", textAlign: "center" }}>
            <Typography variant="caption" color="text.secondary">
              Cuotas
            </Typography>
            <Typography variant="h6" fontWeight={700}>
              {resumen?.cuotas_pendientes ?? cuotas.length}
              {cuotasVencidas > 0 && (
                <Typography component="span" variant="body2" color="error.main" fontWeight={700} sx={{ ml: 0.5 }}>
                  ({cuotasVencidas} vencidas)
                </Typography>
              )}
            </Typography>
          </Paper>
        </Box>

        {/* Barra de salud */}
        <Paper elevation={0} sx={{ p: 1.5, mb: 2.5, borderRadius: 2, border: "1px solid", borderColor: "divider" }}>
          <Box sx={{ display: "flex", justifyContent: "space-between", mb: 0.5 }}>
            <Typography variant="caption" color="text.secondary">
              Estado de cuenta
            </Typography>
            <Typography variant="caption" fontWeight={600} color={`${healthColor}.main`}>
              {healthPct === 0 ? "Al día" : healthPct < 30 ? "Bueno" : healthPct < 60 ? "Atención" : "Crítico"} — {healthPct}% vencido
            </Typography>
          </Box>
          <LinearProgress variant="determinate" value={healthPct} color={healthColor} sx={{ height: 8, borderRadius: 4, bgcolor: "action.hover" }} />
        </Paper>

        {/* Acción */}
        <Box sx={{ display: "flex", gap: 1, mb: 2.5, flexWrap: "wrap" }}>
          <Button variant="outlined" size="small" startIcon={<Icon icon="mdi:printer" />} sx={{ textTransform: "none", borderRadius: 2 }} onClick={() => onEstadoCuenta?.(proveedor)}>
            Estado de Cuenta
          </Button>
        </Box>

        {/* Detalle de cuotas */}
        <Typography
          variant="subtitle2"
          fontWeight={700}
          sx={{ mb: 1, display: "flex", alignItems: "center", gap: 0.5, textTransform: "uppercase", letterSpacing: 0.5, color: "text.secondary", fontSize: "0.7rem" }}
        >
          <Receipt sx={{ fontSize: 16 }} /> Detalle de Cuotas
        </Typography>
        {isLoading ? (
          <Box sx={{ py: 2 }}>
            {[1, 2, 3].map((i) => (
              <Skeleton key={i} variant="rectangular" height={40} sx={{ mb: 0.5, borderRadius: 1 }} />
            ))}
          </Box>
        ) : cuotas.length === 0 ? (
          <Alert severity="info" sx={{ borderRadius: 2 }}>
            No hay cuotas pendientes para este proveedor
          </Alert>
        ) : (
          <TableContainer component={Paper} elevation={0} sx={{ maxHeight: 340, borderRadius: 2, border: "1px solid", borderColor: "divider" }}>
            <Table size="small" stickyHeader>
              <TableHead>
                <TableRow>
                  <TableCell sx={{ fontWeight: 700, fontSize: "0.75rem" }}>Comprobante</TableCell>
                  <TableCell align="center" sx={{ fontWeight: 700, fontSize: "0.75rem" }}>
                    Cuota
                  </TableCell>
                  <TableCell sx={{ fontWeight: 700, fontSize: "0.75rem" }}>Vencimiento</TableCell>
                  <TableCell align="center" sx={{ fontWeight: 700, fontSize: "0.75rem" }}>
                    Estado
                  </TableCell>
                  <TableCell align="right" sx={{ fontWeight: 700, fontSize: "0.75rem" }}>
                    Monto
                  </TableCell>
                  <TableCell align="right" sx={{ fontWeight: 700, fontSize: "0.75rem" }}>
                    Saldo
                  </TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {cuotas.map((c, i) => {
                  const vencida = c.estado === "Vencida";
                  return (
                    <TableRow key={i} sx={{ borderLeft: 3, borderLeftColor: vencida ? "error.main" : "success.main", "&:hover": { bgcolor: "action.hover" } }}>
                      <TableCell>
                        <Typography variant="body2" sx={{ fontFamily: "monospace", fontSize: "0.8rem" }}>
                          {c.documento}
                        </Typography>
                      </TableCell>
                      <TableCell align="center">
                        <Chip label={`#${c.nro_cuota}`} size="small" variant="outlined" sx={{ fontWeight: 600, fontSize: "0.75rem" }} />
                      </TableCell>
                      <TableCell>
                        <Typography variant="body2">{c.fecha_vencimiento}</Typography>
                        {vencida && c.dias_vencido > 0 && (
                          <Typography variant="caption" color="error.main" fontWeight={600}>
                            {c.dias_vencido} días vencido
                          </Typography>
                        )}
                      </TableCell>
                      <TableCell align="center">
                        <Chip label={vencida ? "Vencida" : "Pendiente"} color={vencida ? "error" : "success"} size="small" sx={{ fontWeight: 600, fontSize: "0.7rem" }} />
                      </TableCell>
                      <TableCell align="right">
                        <Typography variant="body2">{formatMoney(c.monto_cuota)}</Typography>
                      </TableCell>
                      <TableCell align="right">
                        <Typography variant="body2" fontWeight={700}>
                          {formatMoney(c.saldo_pendiente)}
                        </Typography>
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          </TableContainer>
        )}
      </DialogContent>
    </Dialog>
  );
}

// ─── Modal PDF estado de cuenta del proveedor ─────────────────────────────────
function EstadoCuentaProveedorModal({ open, proveedorId, nombre, onClose }) {
  const [pdfUrl, setPdfUrl] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [incluirTodas, setIncluirTodas] = useState(false);
  // "pendientes": PDF de cuotas con saldo (lo de siempre). "extracto": movimientos con saldo corrido.
  const [vista, setVista] = useState("pendientes");

  const loadPdf = useCallback(async () => {
    if (!proveedorId) return;
    setLoading(true);
    setError(null);
    try {
      const blob = await getEstadoCuentaProveedorPdf(proveedorId, { incluir_todas: incluirTodas });
      setPdfUrl((prev) => {
        if (prev) URL.revokeObjectURL(prev);
        return URL.createObjectURL(blob);
      });
    } catch (err) {
      const msg = err?.response?.data?.message || err?.message || "No se pudo generar el estado de cuenta.";
      setError(msg);
      toast.error(msg);
    } finally {
      setLoading(false);
    }
  }, [proveedorId, incluirTodas]);

  useEffect(() => {
    if (open && vista === "pendientes") loadPdf();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open, proveedorId, incluirTodas, vista]);

  useEffect(() => {
    return () => {
      if (pdfUrl) URL.revokeObjectURL(pdfUrl);
    };
  }, [pdfUrl]);

  const handleClose = () => {
    if (pdfUrl) URL.revokeObjectURL(pdfUrl);
    setPdfUrl(null);
    setError(null);
    setIncluirTodas(false);
    setVista("pendientes");
    onClose?.();
  };

  return (
    <Dialog
      open={open}
      onClose={handleClose}
      maxWidth={vista === "extracto" ? "lg" : "md"}
      fullWidth
      PaperProps={{ sx: { height: "92vh", maxHeight: "92vh", display: "flex", flexDirection: "column" } }}
    >
      <DialogTitle sx={{ display: "flex", alignItems: "center", justifyContent: "space-between", flexWrap: "wrap", gap: 1, pb: 1 }}>
        <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
          <Icon icon={vista === "extracto" ? "lucide:scroll-text" : "mdi:file-pdf-box"} width={24} color={vista === "extracto" ? undefined : "#e53935"} />
          <Typography variant="h6" fontWeight={600}>
            Estado de Cuenta — {nombre || "Proveedor"}
          </Typography>
        </Box>
        <Box sx={{ display: "flex", alignItems: "center", gap: 1, flexWrap: "wrap", justifyContent: "flex-end" }}>
          <ToggleButtonGroup size="small" exclusive color="primary" value={vista} onChange={(_, v) => v && setVista(v)}>
            <ToggleButton value="pendientes" sx={{ px: 1.5, textTransform: "none" }} title="Cuotas con saldo (PDF)">
              <Icon icon="mdi:file-pdf-box" width={16} style={{ marginRight: 4 }} /> Pendientes
            </ToggleButton>
            <ToggleButton value="extracto" sx={{ px: 1.5, textTransform: "none" }} title="Movimientos con saldo corrido">
              <Icon icon="lucide:scroll-text" width={16} style={{ marginRight: 4 }} /> Extracto
            </ToggleButton>
          </ToggleButtonGroup>
          {vista === "pendientes" && (
            <ToggleButtonGroup size="small" exclusive value={incluirTodas ? "todas" : "vencidas"} onChange={(_, v) => v && setIncluirTodas(v === "todas")}>
              <ToggleButton value="vencidas" sx={{ px: 1.5 }} title="Solo cuotas vencidas">
                <Icon icon="lucide:alert-triangle" width={16} style={{ marginRight: 4 }} /> Vencidas
              </ToggleButton>
              <ToggleButton value="todas" sx={{ px: 1.5 }} title="Todas las cuotas con saldo">
                <Icon icon="lucide:list" width={16} style={{ marginRight: 4 }} /> Todas
              </ToggleButton>
            </ToggleButtonGroup>
          )}
          <IconButton onClick={handleClose} size="small" aria-label="Cerrar">
            <Icon icon="mdi:close" width={20} />
          </IconButton>
        </Box>
      </DialogTitle>
      {vista === "extracto" ? (
        <DialogContent dividers sx={{ flex: 1, overflow: "auto" }}>
          {proveedorId && <ExtractoProveedor proveedorId={proveedorId} nombre={nombre} />}
        </DialogContent>
      ) : (
        <DialogContent sx={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center", p: 0, overflow: "hidden", bgcolor: "#525659" }}>
          {loading ? (
            <Box sx={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 2 }}>
              <CircularProgress size={48} sx={{ color: "white" }} />
              <Typography color="white">Generando estado de cuenta…</Typography>
            </Box>
          ) : error ? (
            <Alert severity="error" sx={{ m: 2 }}>
              {error}
            </Alert>
          ) : pdfUrl ? (
            <iframe title="Estado de cuenta proveedor" src={pdfUrl} style={{ width: "100%", height: "100%", border: "none" }} />
          ) : null}
        </DialogContent>
      )}
    </Dialog>
  );
}

function MetricCard({ title, value, icon, color = "text.primary" }) {
  return (
    <Paper
      elevation={0}
      sx={{
        p: 1.5,
        borderRadius: 2,
        border: "1px solid",
        borderColor: "divider",
      }}
    >
      <Typography variant="caption" color="text.secondary" sx={{ display: "flex", alignItems: "center", gap: 0.6 }}>
        {icon}
        {title}
      </Typography>
      <Typography variant="h6" fontWeight={700} color={color}>
        {value}
      </Typography>
    </Paper>
  );
}

function PaginationBar({ page, totalPages, totalItems, rowsPerPage, onPageChange }) {
  const from = totalItems === 0 ? 0 : (page - 1) * rowsPerPage + 1;
  const to = Math.min(page * rowsPerPage, totalItems);

  return (
    <Box
      sx={{
        display: "flex",
        justifyContent: "space-between",
        alignItems: "center",
        p: 1.5,
        borderTop: "1px solid",
        borderColor: "divider",
        flexWrap: "wrap",
        gap: 1,
      }}
    >
      <Typography variant="caption" color="text.secondary">
        Mostrando {from}-{to} de {totalItems}
      </Typography>
      <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
        <Button size="small" variant="outlined" disabled={page <= 1} onClick={() => onPageChange((p) => p - 1)}>
          <Icon icon="mdi:chevron-left" />
        </Button>
        <Chip label={page} color="primary" size="small" />
        <Button size="small" variant="outlined" disabled={page >= totalPages} onClick={() => onPageChange((p) => p + 1)}>
          <Icon icon="mdi:chevron-right" />
        </Button>
      </Box>
    </Box>
  );
}

const Container = styled.div`
  background: ${({ theme }) => theme.body};
  min-height: 100%;
`;

const Header = styled.div`
  background: linear-gradient(135deg, ${({ theme }) => theme.bg3} 0%, ${({ theme }) => theme.bg4} 100%);
  border-bottom: 1px solid ${({ theme }) => theme.bg4};
  padding: 0.6rem 1.5rem 0.4rem;
  @media (max-width: 768px) {
    padding: 0.5rem 1rem 0.3rem;
  }
`;

const HeaderContent = styled.div`
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  gap: 0.75rem;
`;

const BackBtn = styled.button`
  background: ${({ theme }) => theme.bg4}60;
  border: 1px solid ${({ theme }) => theme.bg4};
  border-radius: 8px;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: ${({ theme }) => theme.text};
  transition: all 0.15s;
  flex-shrink: 0;
  &:hover {
    background: ${({ theme }) => theme.bg4};
  }
  svg {
    width: 1rem;
    height: 1rem;
  }
`;

const TitleSection = styled.div`
  flex: 1;
`;

const MainTitle = styled.h1`
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 1.3rem;
  font-weight: 700;
  color: ${({ theme }) => theme.text};
  margin: 0 0 0.1rem 0;
  svg {
    color: #f88533;
    width: 1.3rem;
    height: 1.3rem;
  }
  @media (max-width: 768px) {
    font-size: 1.1rem;
    svg {
      width: 1.1rem;
      height: 1.1rem;
    }
  }
`;

const Subtitle = styled.p`
  font-size: 0.78rem;
  color: ${({ theme }) => theme.text}cc;
  margin: 0;
  @media (max-width: 768px) {
    font-size: 0.7rem;
  }
`;

const HeaderActions = styled.div`
  display: flex;
  gap: 0.5rem;
  align-items: center;
`;

const ExportBtn = styled.button`
  display: flex;
  align-items: center;
  gap: 0.4rem;
  padding: 0.4rem 0.9rem;
  border-radius: 8px;
  border: 1px solid #22d3ee40;
  background: transparent;
  color: #22d3ee;
  font-size: 0.8rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.15s;
  white-space: nowrap;
  &:hover {
    background: #22d3ee15;
    border-color: #22d3ee;
  }
`;

const Breadcrumb = styled.div`
  max-width: 1200px;
  margin: 0.3rem auto 0;
  display: flex;
  align-items: center;
  gap: 0.4rem;
  font-size: 0.7rem;
`;

const BreadcrumbLink = styled.span`
  color: #22d3ee;
  cursor: pointer;
  &:hover {
    text-decoration: underline;
  }
`;

const BreadcrumbCurrent = styled.span`
  color: ${({ theme }) => theme.text}80;
`;

const Content = styled.div`
  max-width: 1200px;
  margin: 0 auto;
  padding: 1rem 1.5rem;
  @media (max-width: 768px) {
    padding: 0.75rem 1rem;
  }
`;
