import { Icon } from "@iconify/react";
import {
  Box, Button, CircularProgress, FormControl, InputLabel, MenuItem,
  Paper, Select, Tab, Table, TableBody, TableCell, TableHead, TableRow, Tabs, TextField, Typography,
} from "@mui/material";
import { useMemo, useState } from "react";
import * as XLSX from "xlsx";
import styled from "styled-components";
import {
  useTesReporteExtractoCuentaQuery,
  useTesReporteCarteraChequesQuery,
  useTesCuentasQuery,
} from "../../tanstack/TesoreriaStack";
import { usePermission } from "../../hooks/usePermission";
import { fmtFechaCalendario, fmtFechaHoraSoloFecha, hoyISO } from "../../utils/fecha";
import { sanitizeRecords } from "../_standards";

const hoy = () => hoyISO();
const primerDiaMes = () => {
  const d = new Date();
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-01`;
};
const fmtGs = (v, moneda = "PYG") => {
  const n = Number(v || 0);
  if (moneda === "PYG") return `Gs. ${n.toLocaleString("es-PY", { maximumFractionDigits: 0 })}`;
  return `${moneda} ${n.toLocaleString("es-PY", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
};
const fmtFecha = (val) => fmtFechaCalendario(val);

const ESTADO_COLORS = {
  EN_CARTERA: "#3b82f6",
  DEPOSITADO: "#22c55e",
  DEBITADO: "#9333ea",
  RECHAZADO: "#ef4444",
  DEVUELTO: "#f59e0b",
  ANULADO: "#6b7280",
};

export function TesReportesTab() {
  const { can } = usePermission("TESORERIA");
  const [subTab, setSubTab] = useState(0);

  // ── Extracto de cuenta ────────────────────────────────────────────────────
  const { data: cuentasData } = useTesCuentasQuery();
  const cuentas = Array.isArray(cuentasData) ? cuentasData : (cuentasData?.data || []);

  const [exFilters, setExFilters] = useState({ cuenta_id: "", fecha_desde: primerDiaMes(), fecha_hasta: hoy() });
  const [exApplied, setExApplied] = useState(null);
  const [exSearch, setExSearch] = useState("");

  const { data: extracto, isLoading: loadingEx } = useTesReporteExtractoCuentaQuery(
    exApplied,
    subTab === 0 && !!exApplied?.cuenta_id,
  );

  const lineasFiltradas = useMemo(() => {
    const lineas = extracto?.lineas || [];
    if (!exSearch.trim()) return lineas;
    const q = exSearch.toLowerCase();
    return lineas.filter(l =>
      (l.descripcion || "").toLowerCase().includes(q) ||
      (l.categorias || []).join(" ").toLowerCase().includes(q)
    );
  }, [extracto, exSearch]);

  const exportarExtracto = () => {
    if (!extracto) return;
    const rows = extracto.lineas.map(l => ({
      Fecha: fmtFecha(l.fecha),
      Descripción: l.descripcion || "—",
      Categorías: (l.categorias || []).join(", ") || "—",
      Tipo: l.tipo,
      Ingreso: l.ingreso || 0,
      Egreso: l.egreso || 0,
      Saldo: l.saldo,
    }));
    const ws = XLSX.utils.json_to_sheet(sanitizeRecords(rows));
    ws["!cols"] = [10, 30, 25, 10, 14, 14, 14].map(w => ({ wch: w }));
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "Extracto");
    XLSX.writeFile(wb, `extracto-${extracto.cuenta?.nombre || "cuenta"}-${exApplied.fecha_desde}.xlsx`);
  };

  // ── Cartera de cheques ────────────────────────────────────────────────────
  const [chFilters, setChFilters] = useState({ tipo_cheque: "", estado: "", cuenta_id: "", fecha_desde: "", fecha_hasta: "" });
  const [chApplied, setChApplied] = useState({});
  const [chSearch, setChSearch] = useState("");

  const { data: cartera, isLoading: loadingCh } = useTesReporteCarteraChequesQuery(chApplied, subTab === 1);

  const chequesFiltrados = useMemo(() => {
    const list = cartera?.cheques || [];
    if (!chSearch.trim()) return list;
    const q = chSearch.toLowerCase();
    return list.filter(c =>
      (c.numero || "").toLowerCase().includes(q) ||
      (c.titular || "").toLowerCase().includes(q) ||
      (c.banco || "").toLowerCase().includes(q) ||
      (c.cuenta || "").toLowerCase().includes(q)
    );
  }, [cartera, chSearch]);

  const exportarCartera = () => {
    if (!cartera) return;
    const rows = (cartera.cheques || []).map(c => ({
      Número: c.numero,
      Tipo: c.tipo,
      Banco: c.banco || "—",
      Titular: c.titular || "—",
      Monto: c.monto,
      Moneda: c.moneda,
      Emisión: fmtFecha(c.emision),
      Vencimiento: fmtFecha(c.vencimiento),
      Estado: c.estado,
      Cuenta: c.cuenta || "—",
    }));
    const ws = XLSX.utils.json_to_sheet(sanitizeRecords(rows));
    ws["!cols"] = [12, 10, 20, 25, 14, 8, 12, 12, 12, 20].map(w => ({ wch: w }));
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "Cartera Cheques");
    XLSX.writeFile(wb, `cartera-cheques-${hoy()}.xlsx`);
  };

  if (!can("TES_REP_LIBRO_BANCO_VER")) return null;

  return (
    <Box>
      <Tabs value={subTab} onChange={(_, v) => setSubTab(v)} sx={{ mb: 3 }}>
        <Tab label="Extracto de Cuenta" />
        <Tab label="Cartera de Cheques" />
      </Tabs>

      {/* ── Extracto ───────────────────────────────────────────────────────── */}
      {subTab === 0 && (
        <>
          <Paper sx={{ p: 2, mb: 3, display: "flex", gap: 2, flexWrap: "wrap", alignItems: "flex-end" }}>
            <FormControl size="small" sx={{ minWidth: 220 }} required>
              <InputLabel>Cuenta *</InputLabel>
              <Select label="Cuenta *" value={exFilters.cuenta_id}
                onChange={e => setExFilters(f => ({ ...f, cuenta_id: e.target.value }))}>
                <MenuItem value="">Seleccionar cuenta</MenuItem>
                {/* Incluye las cerradas, marcadas: sacar el extracto histórico
                    de una cuenta que se dio de baja es un caso legítimo. */}
                {cuentas.map(c => (
                  <MenuItem key={c.id} value={c.id}>
                    {c.nombre}{c.activo === false ? " (inactiva)" : ""}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
            <TextField label="Desde" type="date" size="small" value={exFilters.fecha_desde}
              onChange={e => setExFilters(f => ({ ...f, fecha_desde: e.target.value }))}
              InputLabelProps={{ shrink: true }} sx={{ width: 145 }} />
            <TextField label="Hasta" type="date" size="small" value={exFilters.fecha_hasta}
              onChange={e => setExFilters(f => ({ ...f, fecha_hasta: e.target.value }))}
              InputLabelProps={{ shrink: true }} sx={{ width: 145 }} />
            <Button variant="contained" onClick={() => { setExApplied({ ...exFilters }); setExSearch(""); }}
              disabled={!exFilters.cuenta_id}
              sx={{ background: "#f88533", "&:hover": { background: "#e07320" } }}>
              Buscar
            </Button>
            <Button variant="outlined" startIcon={<Icon icon="lucide:download" />}
              onClick={exportarExtracto} disabled={!extracto}>
              Excel
            </Button>
          </Paper>

          {!exApplied?.cuenta_id ? (
            <Box sx={{ textAlign: "center", py: 8, opacity: 0.4 }}>
              <Icon icon="lucide:file-text" style={{ fontSize: 48 }} />
              <Typography sx={{ mt: 1 }}>Seleccioná una cuenta y un período para ver el extracto</Typography>
            </Box>
          ) : loadingEx ? (
            <Box sx={{ display: "flex", justifyContent: "center", p: 6 }}><CircularProgress /></Box>
          ) : extracto ? (
            <>
              {/* KPIs */}
              <Box sx={{ display: "flex", gap: 2, flexWrap: "wrap", mb: 3 }}>
                <SaldoCard>
                  <SaldoLabel>Saldo anterior al período</SaldoLabel>
                  <SaldoVal>{fmtGs(extracto.saldoAnterior, extracto.cuenta?.moneda)}</SaldoVal>
                </SaldoCard>
                <SaldoCard $highlight>
                  <SaldoLabel>Saldo final</SaldoLabel>
                  <SaldoVal $color={extracto.saldoFinal >= 0 ? "#22c55e" : "#ef4444"}>
                    {fmtGs(extracto.saldoFinal, extracto.cuenta?.moneda)}
                  </SaldoVal>
                </SaldoCard>
                <SaldoCard>
                  <SaldoLabel>Movimientos</SaldoLabel>
                  <SaldoVal>{extracto.lineas?.length || 0}</SaldoVal>
                </SaldoCard>
              </Box>

              <Paper sx={{ overflow: "hidden" }}>
                {/* Buscador */}
                <Box sx={{ px: 2, py: 1.5, borderBottom: "1px solid", borderColor: "divider" }}>
                  <TextField
                    size="small" placeholder="Buscar por descripción o categoría…"
                    value={exSearch} onChange={e => setExSearch(e.target.value)}
                    InputProps={{ startAdornment: <Icon icon="lucide:search" style={{ marginRight: 6, opacity: 0.5 }} /> }}
                    sx={{ width: 340 }}
                  />
                  {exSearch && (
                    <Typography component="span" variant="caption" sx={{ ml: 2, opacity: 0.5 }}>
                      {lineasFiltradas.length} de {extracto.lineas?.length}
                    </Typography>
                  )}
                </Box>
                <Box sx={{ overflowX: "auto" }}>
                  <ResizableTable>
                    <colgroup>
                      <col style={{ width: 90 }} />
                      <col style={{ width: 220 }} />
                      <col style={{ width: 160 }} />
                      <col style={{ width: 130 }} />
                      <col style={{ width: 130 }} />
                      <col style={{ width: 130 }} />
                    </colgroup>
                    <thead>
                      <tr>
                        <Rth>Fecha</Rth>
                        <Rth>Descripción</Rth>
                        <Rth>Categorías</Rth>
                        <Rth style={{ textAlign: "right" }}>Ingreso</Rth>
                        <Rth style={{ textAlign: "right" }}>Egreso</Rth>
                        <Rth style={{ textAlign: "right" }}>Saldo</Rth>
                      </tr>
                    </thead>
                    <tbody>
                      {lineasFiltradas.map((l, i) => (
                        <Rtr key={i}>
                          <Rtd style={{ whiteSpace: "nowrap" }}>{fmtFecha(l.fecha)}</Rtd>
                          <Rtd style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                            {l.descripcion || "—"}
                          </Rtd>
                          <Rtd style={{ fontSize: 11, opacity: 0.6 }}>
                            {(l.categorias || []).join(", ") || "—"}
                          </Rtd>
                          <Rtd style={{ textAlign: "right", color: "#22c55e", fontWeight: 700 }}>
                            {l.ingreso ? fmtGs(l.ingreso, extracto.cuenta?.moneda) : "—"}
                          </Rtd>
                          <Rtd style={{ textAlign: "right", color: "#ef4444", fontWeight: 700 }}>
                            {l.egreso ? fmtGs(l.egreso, extracto.cuenta?.moneda) : "—"}
                          </Rtd>
                          <Rtd style={{ textAlign: "right", fontWeight: 700, color: l.saldo >= 0 ? "inherit" : "#ef4444" }}>
                            {fmtGs(l.saldo, extracto.cuenta?.moneda)}
                          </Rtd>
                        </Rtr>
                      ))}
                      {lineasFiltradas.length === 0 && (
                        <tr><Rtd colSpan={6} style={{ textAlign: "center", opacity: 0.4, padding: "24px 0" }}>Sin resultados</Rtd></tr>
                      )}
                    </tbody>
                  </ResizableTable>
                </Box>
              </Paper>
            </>
          ) : null}
        </>
      )}

      {/* ── Cartera de cheques ──────────────────────────────────────────────── */}
      {subTab === 1 && (
        <>
          <Paper sx={{ p: 2, mb: 3, display: "flex", gap: 2, flexWrap: "wrap", alignItems: "flex-end" }}>
            <FormControl size="small" sx={{ minWidth: 150 }}>
              <InputLabel>Tipo</InputLabel>
              <Select label="Tipo" value={chFilters.tipo_cheque}
                onChange={e => setChFilters(f => ({ ...f, tipo_cheque: e.target.value }))}>
                <MenuItem value="">Todos</MenuItem>
                <MenuItem value="RECIBIDO">Recibidos</MenuItem>
                <MenuItem value="EMITIDO">Emitidos</MenuItem>
              </Select>
            </FormControl>
            <FormControl size="small" sx={{ minWidth: 150 }}>
              <InputLabel>Estado</InputLabel>
              <Select label="Estado" value={chFilters.estado}
                onChange={e => setChFilters(f => ({ ...f, estado: e.target.value }))}>
                <MenuItem value="">Todos</MenuItem>
                <MenuItem value="EN_CARTERA">En Cartera</MenuItem>
                <MenuItem value="DEPOSITADO">Depositado</MenuItem>
                <MenuItem value="DEBITADO">Debitado</MenuItem>
                <MenuItem value="RECHAZADO">Rechazado</MenuItem>
                <MenuItem value="DEVUELTO">Devuelto</MenuItem>
                <MenuItem value="ANULADO">Anulado</MenuItem>
              </Select>
            </FormControl>
            <TextField label="Vence desde" type="date" size="small" value={chFilters.fecha_desde}
              onChange={e => setChFilters(f => ({ ...f, fecha_desde: e.target.value }))}
              InputLabelProps={{ shrink: true }} sx={{ width: 145 }} />
            <TextField label="Vence hasta" type="date" size="small" value={chFilters.fecha_hasta}
              onChange={e => setChFilters(f => ({ ...f, fecha_hasta: e.target.value }))}
              InputLabelProps={{ shrink: true }} sx={{ width: 145 }} />
            <Button variant="contained" onClick={() => { setChApplied({ ...chFilters }); setChSearch(""); }}
              sx={{ background: "#f88533", "&:hover": { background: "#e07320" } }}>
              Buscar
            </Button>
            <Button variant="outlined" startIcon={<Icon icon="lucide:download" />}
              onClick={exportarCartera} disabled={!cartera}>
              Excel
            </Button>
          </Paper>

          {loadingCh ? (
            <Box sx={{ display: "flex", justifyContent: "center", p: 6 }}><CircularProgress /></Box>
          ) : cartera ? (
            <>
              {/* KPIs */}
              <Box sx={{ display: "flex", gap: 2, flexWrap: "wrap", mb: 3 }}>
                <SaldoCard>
                  <SaldoLabel>En Cartera</SaldoLabel>
                  <SaldoVal $color="#3b82f6">{cartera.resumen?.enCartera || 0}</SaldoVal>
                </SaldoCard>
                <SaldoCard>
                  <SaldoLabel>Depositados</SaldoLabel>
                  <SaldoVal $color="#22c55e">{cartera.resumen?.depositados || 0}</SaldoVal>
                </SaldoCard>
                <SaldoCard $highlight>
                  <SaldoLabel>Vencen en 7 días</SaldoLabel>
                  <SaldoVal $color="#f59e0b">{cartera.resumen?.vencenEn7Dias || 0}</SaldoVal>
                </SaldoCard>
                <SaldoCard>
                  <SaldoLabel>Total en cartera</SaldoLabel>
                  <SaldoVal>{fmtGs(cartera.resumen?.totalCartera)}</SaldoVal>
                </SaldoCard>
              </Box>

              <Paper sx={{ overflow: "hidden" }}>
                {/* Buscador */}
                <Box sx={{ px: 2, py: 1.5, borderBottom: "1px solid", borderColor: "divider" }}>
                  <TextField
                    size="small" placeholder="Buscar por número, titular, banco o cuenta…"
                    value={chSearch} onChange={e => setChSearch(e.target.value)}
                    InputProps={{ startAdornment: <Icon icon="lucide:search" style={{ marginRight: 6, opacity: 0.5 }} /> }}
                    sx={{ width: 380 }}
                  />
                  {chSearch && (
                    <Typography component="span" variant="caption" sx={{ ml: 2, opacity: 0.5 }}>
                      {chequesFiltrados.length} de {cartera.cheques?.length}
                    </Typography>
                  )}
                </Box>
                <Box sx={{ overflowX: "auto" }}>
                  <ResizableTable>
                    <colgroup>
                      <col style={{ width: 120 }} />
                      <col style={{ width: 90 }} />
                      <col style={{ width: 140 }} />
                      <col style={{ width: 160 }} />
                      <col style={{ width: 90 }} />
                      <col style={{ width: 110 }} />
                      <col style={{ width: 110 }} />
                      <col style={{ width: 110 }} />
                      <col style={{ width: 110 }} />
                      <col style={{ width: 150 }} />
                      <col style={{ width: 120 }} />
                    </colgroup>
                    <thead>
                      <tr>
                        <Rth>Número</Rth>
                        <Rth>Tipo</Rth>
                        <Rth>Banco</Rth>
                        <Rth>Titular</Rth>
                        <Rth>Emisión</Rth>
                        <Rth>Vencimiento</Rth>
                        <Rth>Recepción</Rth>
                        <Rth>Estado</Rth>
                        <Rth>Cuenta</Rth>
                        <Rth style={{ textAlign: "right" }}>Monto</Rth>
                      </tr>
                    </thead>
                    <tbody>
                      {chequesFiltrados.map(c => (
                        <Rtr key={c.id}>
                          <Rtd style={{ fontFamily: "monospace", fontSize: 12 }}>{c.numero}</Rtd>
                          <Rtd>{c.tipo}</Rtd>
                          <Rtd>{c.banco || "—"}</Rtd>
                          <Rtd style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{c.titular || "—"}</Rtd>
                          <Rtd style={{ whiteSpace: "nowrap" }}>{fmtFecha(c.emision)}</Rtd>
                          <Rtd style={{ whiteSpace: "nowrap" }}>{fmtFecha(c.vencimiento)}</Rtd>
                          <Rtd style={{ whiteSpace: "nowrap" }}>{fmtFechaHoraSoloFecha(c.recepcion)}</Rtd>
                          <Rtd>
                            <span style={{
                              background: `${ESTADO_COLORS[c.estado] || "#6b7280"}22`,
                              color: ESTADO_COLORS[c.estado] || "#6b7280",
                              border: `1px solid ${ESTADO_COLORS[c.estado] || "#6b7280"}44`,
                              borderRadius: 4, padding: "2px 8px", fontSize: 11, fontWeight: 700,
                              whiteSpace: "nowrap",
                            }}>
                              {c.estado}
                            </span>
                          </Rtd>
                          <Rtd style={{ fontSize: 12, opacity: 0.7, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                            {c.cuenta || "—"}
                          </Rtd>
                          <Rtd style={{ textAlign: "right", fontWeight: 700 }}>
                            {fmtGs(c.monto, c.moneda)}
                          </Rtd>
                        </Rtr>
                      ))}
                      {chequesFiltrados.length === 0 && (
                        <tr><Rtd colSpan={9} style={{ textAlign: "center", opacity: 0.4, padding: "24px 0" }}>Sin resultados</Rtd></tr>
                      )}
                    </tbody>
                  </ResizableTable>
                </Box>
              </Paper>
            </>
          ) : (
            <Box sx={{ textAlign: "center", py: 8, opacity: 0.4 }}>
              <Icon icon="lucide:credit-card" style={{ fontSize: 48 }} />
              <Typography sx={{ mt: 1 }}>Aplicá filtros para ver la cartera de cheques</Typography>
            </Box>
          )}
        </>
      )}
    </Box>
  );
}

const SaldoCard = styled.div`
  background: ${p => p.$highlight ? (p.theme.bg2 || "#1e293b") : "transparent"};
  border: 1px solid ${p => p.theme.bg3 || "#334155"};
  border-radius: 12px;
  padding: 12px 18px;
  min-width: 140px;
  flex: 1;
`;
const SaldoLabel = styled.div`font-size: 11px; opacity: 0.6; margin-bottom: 4px;`;
const SaldoVal = styled.div`
  font-size: 18px;
  font-weight: 700;
  color: ${p => p.$color || "inherit"};
`;

/* Tabla con columnas redimensionables */
const ResizableTable = styled.table`
  width: 100%;
  table-layout: fixed;
  border-collapse: collapse;
  font-size: 13px;
`;
const Rth = styled.th`
  padding: 8px 12px;
  text-align: left;
  font-weight: 600;
  font-size: 12px;
  border-bottom: 1px solid ${p => p.theme.bg3 || "#334155"};
  background: ${p => p.theme.bg2 || "#1e293b"};
  resize: horizontal;
  overflow: auto;
  white-space: nowrap;
  position: relative;
  user-select: none;
  &::after {
    content: "";
    position: absolute;
    right: 0;
    top: 20%;
    height: 60%;
    width: 3px;
    border-radius: 2px;
    background: ${p => p.theme.bg3 || "#475569"};
    cursor: col-resize;
  }
`;
const Rtr = styled.tr`
  &:hover td { background: ${p => p.theme.bg2 || "#1e293b"}; }
`;
const Rtd = styled.td`
  padding: 7px 12px;
  border-bottom: 1px solid ${p => p.theme.bg3 || "#1e293b"};
  vertical-align: middle;
  overflow: hidden;
  text-overflow: ellipsis;
`;
