import { Icon } from "@iconify/react";
import {
  Alert,
  Box,
  Chip,
  IconButton,
  MenuItem,
  Paper,
  Skeleton,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableFooter,
  TableHead,
  TableRow,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { useRef, useState } from "react";
import { toast } from "sonner";
import {
  useLibroRetencionesQuery,
  useMarcarDeclaradaMutation,
} from "../../../tanstack/RecibosMultiStack";
import { usePermission } from "../../../hooks/usePermission";
import {
  EmptyState,
  ScreenGuia,
  fmtMoneda,
  getTipoRetencionChip,
  getEstadoChip,
  TIPOS_RETENCION_LIST,
  ExportarMenuButton,
  descargarCSV,
  descargarExcel,
} from "../../_standards";
import { GUIA_LIBRO_RETENCIONES } from "./_guias";
import { fmtFechaCalendario } from "../../../utils/fecha";

// ─── Helpers ──────────────────────────────────────────────────────────────────
const fmtGs = (v) => fmtMoneda(v, "PYG");

// fecha_comprobante es una columna DATE: llega como "2026-10-01T00:00:00.000Z" y
// toLocaleDateString la corría un día para atrás en Paraguay. Ver docs/ui-standards.md.
const fmtFecha = (str) => fmtFechaCalendario(str);

const buildPeriodos = () => {
  const result = [];
  const now = new Date();
  for (let i = 0; i < 24; i++) {
    const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
    const val = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
    const label = d.toLocaleDateString("es-PY", { month: "long", year: "numeric" });
    result.push({ value: val, label: label.charAt(0).toUpperCase() + label.slice(1) });
  }
  return result;
};

const PERIODOS = buildPeriodos();

// ─── Componente ───────────────────────────────────────────────────────────────
export function LibroRetencionesPanel() {
  const { can } = usePermission("RETENCIONES");
  const [periodo, setPeriodo] = useState(PERIODOS[0].value);
  const guiaRef = useRef(null);
  const scrollToGuia = () => guiaRef.current?.scrollIntoView({ behavior: "smooth", block: "start" });

  const { data = [], isLoading } = useLibroRetencionesQuery(periodo);
  const marcarMutation = useMarcarDeclaradaMutation();

  const totalesPorTipo = TIPOS_RETENCION_LIST.map((t) => ({
    ...t,
    total: data.filter((r) => r.tipo === t.value).reduce((s, r) => s + Number(r.monto), 0),
  }));
  const totalGeneral = totalesPorTipo.reduce((s, t) => s + t.total, 0);
  const pendientes = data.filter((r) => !r.declarada).length;

  // Los montos van como número (no texto) para que el Excel los pueda sumar.
  const exportar = (formato) => {
    const encabezados = [
      "Tipo", "Razón Social", "RUC", "Nro. Comprobante", "Timbrado", "Fecha Comprobante",
      "% Retención", "Monto", "Factura", "Recibo", "Declarada",
    ];
    const filas = data.map((r) => [
      r.tipo,
      r.cliente_razon_social ?? "—",
      r.cliente_ruc ?? "—",
      r.numero_comprobante,
      r.timbrado,
      fmtFecha(r.fecha_comprobante),
      r.porcentaje != null && r.porcentaje !== "" ? Number(r.porcentaje) : "",
      Number(r.monto || 0),
      r.factura_numero || "—",
      r.recibo_numero || "—",
      r.declarada ? "Sí" : "No",
    ]);
    filas.push([]);
    filas.push(["TOTAL", "", "", "", "", "", "", totalGeneral, "", "", ""]);

    const tabla = { encabezados, filas, archivo: `retenciones_${periodo}` };
    if (formato === "xlsx") descargarExcel({ ...tabla, hoja: "Retenciones" });
    else descargarCSV(tabla);
    toast.success("Libro de retenciones exportado correctamente");
  };

  return (
    <Box sx={{ display: "flex", flexDirection: "column", gap: 2 }}>
      <ScreenGuia ref={guiaRef} titulo="¿Cómo funciona el Libro de Retenciones?" {...GUIA_LIBRO_RETENCIONES} />

      {/* Toolbar */}
      <Box sx={{ display: "flex", gap: 2, alignItems: "center", flexWrap: "wrap" }}>
        <TextField
          select
          label="Período"
          value={periodo}
          onChange={(e) => setPeriodo(e.target.value)}
          size="small"
          sx={{ width: 220 }}
        >
          {PERIODOS.map((p) => (
            <MenuItem key={p.value} value={p.value}>{p.label}</MenuItem>
          ))}
        </TextField>

        <Box sx={{ ml: "auto", display: "flex", gap: 1 }}>
          <ExportarMenuButton
            disabled={!data.length}
            onExcel={() => exportar("xlsx")}
            onCSV={() => exportar("csv")}
          />
        </Box>
      </Box>

      {/* Resumen */}
      {!isLoading && data.length > 0 && (
        <Box sx={{ display: "flex", gap: 2, flexWrap: "wrap" }}>
          {totalesPorTipo.map((t) => (
            <Paper key={t.value} variant="outlined" sx={{ p: 1.5, minWidth: 160 }}>
              <Typography variant="caption" color="text.secondary">{t.label}</Typography>
              <Typography fontWeight={600} color={`${t.color}.main`}>{fmtGs(t.total)}</Typography>
            </Paper>
          ))}
          <Paper variant="outlined" sx={{ p: 1.5, minWidth: 160 }}>
            <Typography variant="caption" color="text.secondary">Total</Typography>
            <Typography fontWeight={600}>{fmtGs(totalGeneral)}</Typography>
          </Paper>
          {pendientes > 0 && (
            <Paper variant="outlined" sx={{ p: 1.5, minWidth: 160, borderColor: "warning.main" }}>
              <Typography variant="caption" color="warning.main">Sin declarar</Typography>
              <Typography fontWeight={600} color="warning.main">{pendientes}</Typography>
            </Paper>
          )}
        </Box>
      )}

      {pendientes > 0 && (
        <Alert severity="warning" icon={<Icon icon="mdi:alert" />}>
          Hay <strong>{pendientes}</strong> retenciones del período que aún no fueron marcadas como declaradas en el SET.
        </Alert>
      )}

      {/* Tabla */}
      <TableContainer component={Paper} variant="outlined">
        <Table size="small">
          <TableHead>
            <TableRow sx={{ "& th": { fontWeight: 600, bgcolor: "action.hover" } }}>
              <TableCell>Tipo</TableCell>
              <TableCell>Cliente / RUC</TableCell>
              <TableCell>Comprobante</TableCell>
              <TableCell>Timbrado</TableCell>
              <TableCell>Fecha</TableCell>
              <TableCell align="right">%</TableCell>
              <TableCell align="right">Monto</TableCell>
              <TableCell>Factura</TableCell>
              <TableCell>Estado</TableCell>
              {can("COB_REC_LIBRO_RETENCIONES") && <TableCell align="center">Acción</TableCell>}
            </TableRow>
          </TableHead>
          <TableBody>
            {isLoading && (
              [...Array(6)].map((_, i) => (
                <TableRow key={i}>
                  {[...Array(10)].map((__, j) => (
                    <TableCell key={j}><Skeleton /></TableCell>
                  ))}
                </TableRow>
              ))
            )}

            {!isLoading && data.length === 0 && (
              <TableRow>
                <TableCell colSpan={10} sx={{ borderBottom: "none", py: 0 }}>
                  <EmptyState
                    icon="mdi:book-outline"
                    title="No hay retenciones en este período"
                    description="Las retenciones se generan automáticamente al cargar un recibo multi-factura con retenciones IVA o Renta. Probá con otro período."
                    onHelp={scrollToGuia}
                  />
                </TableCell>
              </TableRow>
            )}

            {data.map((r) => (
              <TableRow key={r.id} sx={{ opacity: r.recibo_estado === "ANULADO" ? 0.4 : 1 }}>
                <TableCell>
                  <Chip size="small" {...getTipoRetencionChip(r.tipo)} />
                </TableCell>
                <TableCell>
                  <Typography variant="body2">{r.cliente_razon_social ?? "—"}</Typography>
                  <Typography variant="caption" color="text.secondary">{r.cliente_ruc ?? ""}</Typography>
                </TableCell>
                <TableCell sx={{ fontFamily: "monospace" }}>{r.numero_comprobante}</TableCell>
                <TableCell sx={{ fontFamily: "monospace" }}>{r.timbrado}</TableCell>
                <TableCell>{fmtFecha(r.fecha_comprobante)}</TableCell>
                <TableCell align="right">{r.porcentaje ? `${r.porcentaje}%` : "—"}</TableCell>
                <TableCell align="right" sx={{ fontWeight: 600 }}>{fmtGs(r.monto)}</TableCell>
                <TableCell sx={{ fontFamily: "monospace" }}>{r.factura_numero ?? "—"}</TableCell>
                <TableCell>
                  <Chip size="small" variant="outlined" {...getEstadoChip(r.declarada ? "DECLARADA" : "PENDIENTE")} />
                </TableCell>
                {can("COB_REC_LIBRO_RETENCIONES") && (
                  <TableCell align="center">
                    {!r.declarada && r.recibo_estado !== "ANULADO" && (
                      <Tooltip title="Marcar como declarada al SET">
                        <IconButton
                          size="small"
                          color="success"
                          disabled={marcarMutation.isPending}
                          onClick={() => marcarMutation.mutate({ id: r.id, periodo })}
                        >
                          <Icon icon="mdi:check-circle-outline" />
                        </IconButton>
                      </Tooltip>
                    )}
                  </TableCell>
                )}
              </TableRow>
            ))}
          </TableBody>

          {!isLoading && data.length > 0 && (
            <TableFooter>
              <TableRow sx={{ "& td": { fontWeight: 600 } }}>
                <TableCell colSpan={6} align="right">Totales</TableCell>
                <TableCell align="right">{fmtGs(totalGeneral)}</TableCell>
                <TableCell colSpan={can("COB_REC_LIBRO_RETENCIONES") ? 3 : 2} />
              </TableRow>
            </TableFooter>
          )}
        </Table>
      </TableContainer>
    </Box>
  );
}
