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 { useNavigate } from "react-router-dom";
import styled from "styled-components";
import { useTesReporteCashFlowRealQuery, useTesReporteCashFlowProyectadoQuery, useTesCuentasQuery } from "../tanstack/TesoreriaStack";
import { usePermission } from "../hooks/usePermission";
import { AccesoRestringido } from "../components/common/AccesoRestringido";
import { sanitizeRecords } from "../components/_standards";
import { hoyISO } from "../utils/fecha";

const hoy = () => hoyISO();
const primerDiaMes = () => {
  const d = new Date();
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-01`;
};
const fmtGs = (v) => `Gs. ${Number(v || 0).toLocaleString("es-PY", { maximumFractionDigits: 0 })}`;
const fmtFecha = (val) => {
  if (!val) return "—";
  const m = String(val).match(/^(\d{4})-(\d{2})-(\d{2})/);
  return m ? `${m[3]}/${m[2]}/${m[1]}` : val;
};

export function ReporteFlujoCaja() {
  const navigate = useNavigate();
  const { can } = usePermission("FINANZAS");
  const [tab, setTab] = useState(0); // 0=real, 1=proyectado
  const [filters, setFilters] = useState({ fecha_desde: primerDiaMes(), fecha_hasta: hoy(), cuenta_id: "" });
  const [applied, setApplied] = useState({ ...filters });

  const { data: cuentasData } = useTesCuentasQuery();
  const cuentas = Array.isArray(cuentasData) ? cuentasData : cuentasData?.data || [];

  const params = useMemo(
    () => ({
      fecha_desde: applied.fecha_desde,
      fecha_hasta: applied.fecha_hasta,
      ...(applied.cuenta_id ? { cuenta_id: applied.cuenta_id } : {}),
    }),
    [applied],
  );

  const { data: real, isLoading: loadingReal } = useTesReporteCashFlowRealQuery(params);
  const { data: proyectado, isLoading: loadingProy } = useTesReporteCashFlowProyectadoQuery(params, tab === 1);

  const data = tab === 0 ? real : proyectado;
  const isLoading = tab === 0 ? loadingReal : loadingProy;

  if (!can("TES_REP_FLUJO_CAJA_VER")) return <AccesoRestringido modulo="TESORERIA" />;

  const handleBuscar = () => setApplied({ ...filters });

  const exportarExcel = () => {
    if (!data) return;
    const wb = XLSX.utils.book_new();

    // Hoja resumen
    const resumenRows = [
      { Concepto: "Ingresos", Monto: data.totalIngresos },
      { Concepto: "Egresos", Monto: data.totalEgresos },
      { Concepto: "Resultado", Monto: data.resultado },
      ...(tab === 1
        ? [
            { Concepto: "Cobros Proyectados (CxC)", Monto: data.cobrosProyectados || 0 },
            { Concepto: "Pagos Proyectados (CxP)", Monto: data.pagosProyectados || 0 },
            { Concepto: "Resultado Proyectado", Monto: data.resultadoProyectado || 0 },
          ]
        : []),
    ];
    XLSX.utils.book_append_sheet(wb, XLSX.utils.json_to_sheet(sanitizeRecords(resumenRows)), "Resumen");

    // Hoja por categoría
    const catRows = (data.porCategoria || []).map((c) => ({ Categoría: c.nombre, Tipo: c.tipo, Total: c.total, Cant: c.cantidad }));
    XLSX.utils.book_append_sheet(wb, XLSX.utils.json_to_sheet(sanitizeRecords(catRows)), "Por Categoría");

    // Hoja movimientos
    const movRows = (data.movimientos || []).map((m) => ({
      Fecha: fmtFecha(m.fecha),
      Cuenta: m.cuenta,
      Tipo: m.tipo,
      Monto: m.monto,
      Descripción: m.descripcion,
      Categorías: (m.categorias || []).join(", "),
    }));
    XLSX.utils.book_append_sheet(wb, XLSX.utils.json_to_sheet(sanitizeRecords(movRows)), "Movimientos");

    XLSX.writeFile(wb, `flujo-caja-${applied.fecha_desde}-${applied.fecha_hasta}.xlsx`);
  };

  const maxCat = Math.max(...(data?.porCategoria || []).map((c) => c.total), 1);

  return (
    <Container>
      <Header>
        <Button startIcon={<Icon icon="lucide:arrow-left" />} onClick={() => navigate("/reportes")} size="small">
          Volver
        </Button>
        <TitleRow>
          <Icon icon="lucide:trending-up" style={{ fontSize: 28, color: "#f88533" }} />
          <div>
            <Typography variant="h5" fontWeight={700}>
              Flujo de Caja
            </Typography>
            <Typography variant="body2" color="text.secondary">
              Ingresos y egresos reales y proyectados
            </Typography>
          </div>
        </TitleRow>
        <Button variant="outlined" startIcon={<Icon icon="lucide:download" />} onClick={exportarExcel} disabled={!data}>
          Excel
        </Button>
      </Header>

      {/* Filtros */}
      <Paper sx={{ p: 2, mb: 3, display: "flex", gap: 2, flexWrap: "wrap", alignItems: "flex-end" }}>
        <TextField
          label="Desde"
          type="date"
          size="small"
          value={filters.fecha_desde}
          onChange={(e) => setFilters((f) => ({ ...f, fecha_desde: e.target.value }))}
          InputLabelProps={{ shrink: true }}
          sx={{ width: 145 }}
        />
        <TextField
          label="Hasta"
          type="date"
          size="small"
          value={filters.fecha_hasta}
          onChange={(e) => setFilters((f) => ({ ...f, fecha_hasta: e.target.value }))}
          InputLabelProps={{ shrink: true }}
          sx={{ width: 145 }}
        />
        <FormControl size="small" sx={{ minWidth: 180 }}>
          <InputLabel>Cuenta (opcional)</InputLabel>
          <Select label="Cuenta (opcional)" value={filters.cuenta_id} onChange={(e) => setFilters((f) => ({ ...f, cuenta_id: e.target.value }))}>
            <MenuItem value="">Todas las cuentas</MenuItem>
            {cuentas.map((c) => (
              <MenuItem key={c.id} value={c.id}>
                {c.nombre}
              </MenuItem>
            ))}
          </Select>
        </FormControl>
        <Button variant="contained" onClick={handleBuscar} sx={{ background: "#f88533", "&:hover": { background: "#e07320" } }}>
          Buscar
        </Button>
      </Paper>

      {/* Toggle real / proyectado */}
      <Tabs value={tab} onChange={(_, v) => setTab(v)} sx={{ mb: 2 }}>
        <Tab label="Flujo Real" />
        <Tab label="Flujo Proyectado (incl. CxC / CxP)" />
      </Tabs>

      {isLoading ? (
        <Box sx={{ display: "flex", justifyContent: "center", p: 6 }}>
          <CircularProgress />
        </Box>
      ) : !data ? null : (
        <>
          {/* KPIs */}
          <KpiGrid>
            <KpiCard $color="#22c55e">
              <KpiLabel>Ingresos</KpiLabel>
              <KpiVal>{fmtGs(data.totalIngresos)}</KpiVal>
            </KpiCard>
            <KpiCard $color="#ef4444">
              <KpiLabel>Egresos</KpiLabel>
              <KpiVal>{fmtGs(data.totalEgresos)}</KpiVal>
            </KpiCard>
            <KpiCard $color={data.resultado >= 0 ? "#3b82f6" : "#f59e0b"}>
              <KpiLabel>Resultado</KpiLabel>
              <KpiVal>{fmtGs(data.resultado)}</KpiVal>
            </KpiCard>
            {tab === 1 && (
              <>
                <KpiCard $color="#0891b2">
                  <KpiLabel>Cobros Proyectados (CxC)</KpiLabel>
                  <KpiVal>{fmtGs(data.cobrosProyectados)}</KpiVal>
                </KpiCard>
                <KpiCard $color="#9d174d">
                  <KpiLabel>Pagos Proyectados (CxP)</KpiLabel>
                  <KpiVal>{fmtGs(data.pagosProyectados)}</KpiVal>
                </KpiCard>
                <KpiCard $color={data.resultadoProyectado >= 0 ? "#3b82f6" : "#f59e0b"}>
                  <KpiLabel>Resultado Proyectado</KpiLabel>
                  <KpiVal>{fmtGs(data.resultadoProyectado)}</KpiVal>
                </KpiCard>
              </>
            )}
          </KpiGrid>

          {/* Por categoría */}
          {data.porCategoria?.length > 0 && (
            <Paper sx={{ p: 2, mb: 3 }}>
              <Typography variant="subtitle1" fontWeight={700} sx={{ mb: 2 }}>
                Por Categoría
              </Typography>
              {data.porCategoria.map((cat) => (
                <CatRow key={cat.nombre}>
                  <CatName>{cat.nombre}</CatName>
                  <CatBar>
                    <CatFill $pct={(cat.total / maxCat) * 100} $tipo={cat.tipo} />
                  </CatBar>
                  <CatMonto $tipo={cat.tipo}>{fmtGs(cat.total)}</CatMonto>
                  <CatCant>{cat.cantidad} mov.</CatCant>
                </CatRow>
              ))}
            </Paper>
          )}

          {/* Detalle movimientos */}
          {data.movimientos?.length > 0 && (
            <Paper sx={{ overflow: "hidden" }}>
              <Box sx={{ px: 2, py: 1.5, borderBottom: "1px solid", borderColor: "divider" }}>
                <Typography variant="subtitle1" fontWeight={700}>
                  Movimientos ({data.movimientos.length})
                </Typography>
              </Box>
              <Box sx={{ overflowX: "auto" }}>
                <Table size="small">
                  <TableHead>
                    <TableRow>
                      <TableCell>Fecha</TableCell>
                      <TableCell>Cuenta</TableCell>
                      <TableCell>Tipo</TableCell>
                      <TableCell>Descripción</TableCell>
                      <TableCell>Categorías</TableCell>
                      <TableCell align="right">Monto</TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {data.movimientos.map((m) => (
                      <TableRow key={m.id} hover>
                        <TableCell sx={{ whiteSpace: "nowrap" }}>{fmtFecha(m.fecha)}</TableCell>
                        <TableCell>{m.cuenta}</TableCell>
                        <TableCell>
                          <span style={{ color: m.tipo === "INGRESO" ? "#22c55e" : "#ef4444", fontWeight: 700, fontSize: 11 }}>{m.tipo}</span>
                        </TableCell>
                        <TableCell sx={{ maxWidth: 200, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{m.descripcion || "—"}</TableCell>
                        <TableCell sx={{ fontSize: 11, color: "text.secondary" }}>{(m.categorias || []).join(", ") || "—"}</TableCell>
                        <TableCell align="right" sx={{ color: m.tipo === "INGRESO" ? "#22c55e" : "#ef4444", fontWeight: 700 }}>
                          {fmtGs(m.monto)}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </Box>
            </Paper>
          )}

          {/* CxC proyectados */}
          {tab === 1 && data.detalleCobros?.length > 0 && (
            <Paper sx={{ mt: 3, overflow: "hidden" }}>
              <Box sx={{ px: 2, py: 1.5, borderBottom: "1px solid", borderColor: "divider" }}>
                <Typography variant="subtitle1" fontWeight={700} color="#0891b2">
                  Cobros esperados (CxC vencen en el período)
                </Typography>
              </Box>
              <Table size="small">
                <TableHead>
                  <TableRow>
                    <TableCell>Cliente</TableCell>
                    <TableCell>Vencimiento</TableCell>
                    <TableCell align="right">Monto</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {data.detalleCobros.map((c, i) => (
                    <TableRow key={i} hover>
                      <TableCell>{c.cliente}</TableCell>
                      <TableCell>{fmtFecha(c.vencimiento)}</TableCell>
                      <TableCell align="right" sx={{ color: "#0891b2", fontWeight: 700 }}>
                        {fmtGs(c.monto)}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </Paper>
          )}
        </>
      )}
    </Container>
  );
}

const Container = styled.div`
  max-width: 1100px;
  margin: 60px auto 0;
  padding: 24px 16px 40px;
`;
const Header = styled.div`
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 24px;
  flex-wrap: wrap;
`;
const TitleRow = styled.div`
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
`;
const KpiGrid = styled.div`
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
  margin-bottom: 24px;
`;
const KpiCard = styled.div`
  background: ${(p) => p.$color}18;
  border: 1px solid ${(p) => p.$color}44;
  border-radius: 12px;
  padding: 16px 20px;
  min-width: 160px;
  flex: 1;
`;
const KpiLabel = styled.div`
  font-size: 12px;
  opacity: 0.7;
  margin-bottom: 6px;
`;
const KpiVal = styled.div`
  font-size: 20px;
  font-weight: 700;
`;
const CatRow = styled.div`
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 10px;
`;
const CatName = styled.div`
  font-size: 13px;
  min-width: 160px;
  flex-shrink: 0;
`;
const CatBar = styled.div`
  flex: 1;
  height: 10px;
  background: ${(p) => p.theme.bg3 || "#334155"};
  border-radius: 5px;
  overflow: hidden;
`;
const CatFill = styled.div`
  height: 100%;
  width: ${(p) => p.$pct}%;
  background: ${(p) => (p.$tipo === "INGRESO" ? "#22c55e" : "#ef4444")};
  border-radius: 5px;
  transition: width 0.4s;
`;
const CatMonto = styled.div`
  font-size: 13px;
  font-weight: 700;
  min-width: 110px;
  text-align: right;
  color: ${(p) => (p.$tipo === "INGRESO" ? "#22c55e" : "#ef4444")};
`;
const CatCant = styled.div`
  font-size: 11px;
  opacity: 0.5;
  min-width: 50px;
  text-align: right;
`;
