import { Icon } from "@iconify/react";
import {
  Box,
  Button,
  Card,
  CardContent,
  Chip,
  Paper,
  Skeleton,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  Typography,
} from "@mui/material";
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { toast } from "sonner";
import * as XLSX from "xlsx";
import {
  getPromesasDashboardCashflow,
  getReporteCumplimientoPromesas,
} from "../../api/cobranzas.service";
import { AccesoRestringido } from "../../components/common/AccesoRestringido";
import { usePermission } from "../../hooks/usePermission";
import { fmtFechaCalendario, hoyISO } from "../../utils/fecha";
import { sanitizeRows } from "../../components/_standards";

// ==================== HELPERS ====================

const fmtGs = (n) =>
  `Gs. ${Number(n || 0).toLocaleString("es-PY", { maximumFractionDigits: 0 })}`;
const fmtNum = (n) =>
  Number(n || 0).toLocaleString("es-PY", { maximumFractionDigits: 0 });
const fmtPct = (n) => `${Number(n || 0).toFixed(1)}%`;

const getHoy = () => hoyISO();
const getInicioMes = () => {
  const d = new Date();
  d.setDate(1);
  return d.toISOString().split("T")[0];
};

const tasaColor = (pct) => {
  if (pct >= 80) return "success";
  if (pct >= 50) return "warning";
  return "error";
};

// ==================== EXPORT ====================

function exportarExcel(porCobrador, proyeccion, periodo) {
  const wb = XLSX.utils.book_new();

  const rowsCob = [
    ["Cobrador", "Total", "Cumplidas", "Parciales", "Incumplidas", "Pendientes", "Tasa cumpl. (%)", "Gs. cumplido"],
  ];
  for (const r of porCobrador) {
    rowsCob.push([
      r.cobrador_nombre,
      r.total,
      r.cumplidas,
      r.cumplidas_parciales,
      r.incumplidas,
      r.pendientes,
      Number(r.tasa_cumplimiento || 0).toFixed(1),
      r.monto_cumplido,
    ]);
  }
  XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(sanitizeRows(rowsCob)), "Cobradores");

  const rowsProy = [["Fecha", "Monto Gs."]];
  for (const p of proyeccion) rowsProy.push([p.fecha, p.monto]);
  XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(sanitizeRows(rowsProy)), "Cashflow");

  XLSX.writeFile(wb, `reporte-promesas-${periodo.desde}-${periodo.hasta}.xlsx`);
  toast.success("Reporte exportado correctamente");
}

// ==================== COMPONENT ====================

export default function PromesasReportePage() {
  const navigate = useNavigate();
  const { can } = usePermission("COBRANZAS");
  const canRead = can("COB_PRM_REPORTE_CUMPLIMIENTO");

  const [fechaDesde, setFechaDesde] = useState(getInicioMes());
  const [fechaHasta, setFechaHasta] = useState(getHoy());
  const [reporte, setReporte] = useState(null);
  const [cashflow, setCashflow] = useState(null);
  const [loading, setLoading] = useState(false);

  const cargar = async () => {
    setLoading(true);
    try {
      const [rep, cf] = await Promise.all([
        getReporteCumplimientoPromesas({
          fecha_desde: fechaDesde || undefined,
          fecha_hasta: fechaHasta || undefined,
        }),
        getPromesasDashboardCashflow(),
      ]);
      setReporte(rep);
      setCashflow(cf);
    } catch (e) {
      toast.error(e?.response?.data?.message || "Error cargando reporte");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (canRead) cargar();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  if (!canRead) return <AccesoRestringido modulo="COBRANZAS" />;

  const porCobrador = reporte?.por_cobrador || [];
  const totalPromesas = porCobrador.reduce((acc, r) => acc + (r.total || 0), 0);
  const totalCumplidas = porCobrador.reduce(
    (acc, r) => acc + (r.cumplidas || 0) + (r.cumplidas_parciales || 0),
    0,
  );
  const totalIncumplidas = porCobrador.reduce((acc, r) => acc + (r.incumplidas || 0), 0);
  const totalMontoCumplido = porCobrador.reduce(
    (acc, r) => acc + Number(r.monto_cumplido || 0),
    0,
  );
  const tasaGlobal = totalPromesas > 0 ? (totalCumplidas / totalPromesas) * 100 : 0;
  const proyeccion = cashflow?.proyeccion || [];

  return (
    <Box sx={{ maxWidth: 1400, mx: "auto", p: { xs: 2, md: 3 } }}>
      {/* ── Header ── */}
      <Box
        sx={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "flex-start",
          mb: 1,
          flexWrap: "wrap",
          gap: 1,
        }}
      >
        <Box sx={{ display: "flex", alignItems: "center", gap: 1.5 }}>
          <Button
            size="small"
            onClick={() => navigate("/reportes")}
            sx={{ minWidth: 32, p: 0.5 }}
          >
            <Icon icon="lucide:arrow-left" width={20} />
          </Button>
          <Box>
            <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
              <Icon icon="lucide:handshake" width={22} />
              <Typography variant="h6" fontWeight={700}>
                Cumplimiento de Promesas
              </Typography>
            </Box>
            <Typography variant="caption" color="text.secondary">
              Tasa de cumplimiento por cobrador y cashflow proyectado de promesas pendientes
            </Typography>
          </Box>
        </Box>
        <Button
          variant="outlined"
          size="small"
          startIcon={<Icon icon="lucide:download" width={16} />}
          onClick={() =>
            reporte &&
            exportarExcel(porCobrador, proyeccion, { desde: fechaDesde, hasta: fechaHasta })
          }
          disabled={!reporte || loading}
        >
          Exportar
        </Button>
      </Box>

      <Typography variant="caption" color="text.secondary" sx={{ mb: 2, display: "block" }}>
        <span style={{ cursor: "pointer" }} onClick={() => navigate("/reportes")}>
          Reportes
        </span>
        {" > "}Cumplimiento de Promesas
      </Typography>

      {/* ── Filtros ── */}
      <Paper variant="outlined" sx={{ p: 2, mb: 2, borderRadius: 2 }}>
        <Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap", alignItems: "center" }}>
          <TextField
            size="small"
            type="date"
            label="Desde"
            value={fechaDesde}
            onChange={(e) => setFechaDesde(e.target.value)}
            InputLabelProps={{ shrink: true }}
            sx={{ minWidth: 145 }}
          />
          <TextField
            size="small"
            type="date"
            label="Hasta"
            value={fechaHasta}
            onChange={(e) => setFechaHasta(e.target.value)}
            InputLabelProps={{ shrink: true }}
            sx={{ minWidth: 145 }}
          />
          <Button
            variant="contained"
            size="small"
            startIcon={<Icon icon="lucide:search" width={16} />}
            onClick={cargar}
            disabled={loading}
          >
            Consultar
          </Button>
        </Box>
      </Paper>

      {/* ── KPIs ── */}
      <Box
        sx={{
          display: "grid",
          gridTemplateColumns: { xs: "repeat(2, 1fr)", md: "repeat(5, 1fr)" },
          gap: 2,
          mb: 2,
        }}
      >
        <Card variant="outlined" sx={{ borderRadius: 2 }}>
          <CardContent sx={{ p: "14px !important", display: "flex", alignItems: "center", gap: 1.5 }}>
            <Icon icon="lucide:handshake" width={20} style={{ opacity: 0.6 }} />
            <Box>
              <Typography variant="caption" color="text.secondary">Total promesas</Typography>
              <Typography variant="h6" fontWeight={700} color="primary.main">
                {fmtNum(totalPromesas)}
              </Typography>
            </Box>
          </CardContent>
        </Card>
        <Card variant="outlined" sx={{ borderRadius: 2 }}>
          <CardContent sx={{ p: "14px !important", display: "flex", alignItems: "center", gap: 1.5 }}>
            <Icon icon="lucide:check-circle-2" width={20} style={{ opacity: 0.6 }} />
            <Box>
              <Typography variant="caption" color="text.secondary">Cumplidas</Typography>
              <Typography variant="h6" fontWeight={700} color="success.main">
                {fmtNum(totalCumplidas)}
              </Typography>
            </Box>
          </CardContent>
        </Card>
        <Card variant="outlined" sx={{ borderRadius: 2 }}>
          <CardContent sx={{ p: "14px !important", display: "flex", alignItems: "center", gap: 1.5 }}>
            <Icon icon="lucide:x-octagon" width={20} style={{ opacity: 0.6 }} />
            <Box>
              <Typography variant="caption" color="text.secondary">Incumplidas</Typography>
              <Typography variant="h6" fontWeight={700} color="error.main">
                {fmtNum(totalIncumplidas)}
              </Typography>
            </Box>
          </CardContent>
        </Card>
        <Card variant="outlined" sx={{ borderRadius: 2 }}>
          <CardContent sx={{ p: "14px !important", display: "flex", alignItems: "center", gap: 1.5 }}>
            <Icon icon="lucide:percent" width={20} style={{ opacity: 0.6 }} />
            <Box>
              <Typography variant="caption" color="text.secondary">Tasa global</Typography>
              <Typography variant="h6" fontWeight={700} color="warning.main">
                {fmtPct(tasaGlobal)}
              </Typography>
            </Box>
          </CardContent>
        </Card>
        <Card variant="outlined" sx={{ borderRadius: 2 }}>
          <CardContent sx={{ p: "14px !important", display: "flex", alignItems: "center", gap: 1.5 }}>
            <Icon icon="lucide:banknote" width={20} style={{ opacity: 0.6 }} />
            <Box>
              <Typography variant="caption" color="text.secondary">Monto cumplido</Typography>
              <Typography variant="body1" fontWeight={700} color="success.main">
                {fmtGs(totalMontoCumplido)}
              </Typography>
            </Box>
          </CardContent>
        </Card>
      </Box>

      {/* ── Cumplimiento por cobrador ── */}
      <Typography variant="subtitle2" sx={{ mb: 1, display: "flex", alignItems: "center", gap: 0.75 }}>
        <Icon icon="lucide:users" width={16} />
        Cumplimiento por cobrador
      </Typography>
      {loading ? (
        <Box sx={{ display: "flex", flexDirection: "column", gap: 1, mb: 2 }}>
          {[...Array(5)].map((_, i) => (
            <Skeleton key={i} variant="rounded" height={44} />
          ))}
        </Box>
      ) : porCobrador.length === 0 ? (
        <Paper variant="outlined" sx={{ p: 6, textAlign: "center", borderRadius: 2, mb: 2 }}>
          <Icon icon="lucide:inbox" width={48} style={{ opacity: 0.3, marginBottom: 12 }} />
          <Typography color="text.secondary">Sin promesas en el rango seleccionado</Typography>
        </Paper>
      ) : (
        <TableContainer component={Paper} variant="outlined" sx={{ borderRadius: 2, mb: 3 }}>
          <Table size="small">
            <TableHead>
              <TableRow>
                <TableCell sx={{ fontWeight: 600 }}>Cobrador</TableCell>
                <TableCell sx={{ fontWeight: 600 }} align="right">Total</TableCell>
                <TableCell sx={{ fontWeight: 600 }} align="right">Cumpl.</TableCell>
                <TableCell sx={{ fontWeight: 600 }} align="right">Parc.</TableCell>
                <TableCell sx={{ fontWeight: 600 }} align="right">Incumpl.</TableCell>
                <TableCell sx={{ fontWeight: 600 }} align="right">Pend.</TableCell>
                <TableCell sx={{ fontWeight: 600 }} align="right">Tasa</TableCell>
                <TableCell sx={{ fontWeight: 600 }} align="right">Gs. cumplido</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {porCobrador.map((r) => (
                <TableRow key={r.cobrador_id ?? "sin"} hover sx={{ "&:last-child td": { borderBottom: 0 } }}>
                  <TableCell>
                    <Typography variant="body2" fontWeight={600}>
                      {r.cobrador_nombre || "— Sin cobrador"}
                    </Typography>
                  </TableCell>
                  <TableCell align="right">{fmtNum(r.total)}</TableCell>
                  <TableCell align="right">
                    <Typography variant="body2" color="success.main" fontWeight={600}>
                      {fmtNum(r.cumplidas)}
                    </Typography>
                  </TableCell>
                  <TableCell align="right">{fmtNum(r.cumplidas_parciales)}</TableCell>
                  <TableCell align="right">
                    <Typography variant="body2" color="error.main" fontWeight={600}>
                      {fmtNum(r.incumplidas)}
                    </Typography>
                  </TableCell>
                  <TableCell align="right">{fmtNum(r.pendientes)}</TableCell>
                  <TableCell align="right">
                    <Chip
                      label={fmtPct(r.tasa_cumplimiento)}
                      size="small"
                      color={tasaColor(Number(r.tasa_cumplimiento || 0))}
                      sx={{ fontWeight: 600 }}
                    />
                  </TableCell>
                  <TableCell align="right">
                    <Typography variant="body2" fontWeight={700} color="success.main">
                      {fmtGs(r.monto_cumplido)}
                    </Typography>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>
      )}

      {/* ── Cashflow proyectado ── */}
      <Typography variant="subtitle2" sx={{ mb: 1, display: "flex", alignItems: "center", gap: 0.75 }}>
        <Icon icon="lucide:trending-up" width={16} />
        Cashflow proyectado de promesas pendientes
      </Typography>
      <Paper variant="outlined" sx={{ p: 2, mb: 2, borderRadius: 2 }}>
        <Box sx={{ display: "flex", flexWrap: "wrap", gap: 3, alignItems: "baseline" }}>
          <Box>
            <Typography variant="caption" color="text.secondary">Total pendiente</Typography>
            <Typography variant="h6" fontWeight={700}>
              {fmtGs(cashflow?.total_pendiente)}
            </Typography>
          </Box>
          <Typography variant="body2" color="text.secondary">
            {cashflow?.total_promesas ?? 0} promesa(s) pendiente(s)
          </Typography>
        </Box>
      </Paper>

      {loading ? (
        <Box sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
          {[...Array(4)].map((_, i) => (
            <Skeleton key={i} variant="rounded" height={36} />
          ))}
        </Box>
      ) : proyeccion.length === 0 ? (
        <Paper variant="outlined" sx={{ p: 4, textAlign: "center", borderRadius: 2 }}>
          <Typography color="text.secondary">No hay promesas pendientes futuras</Typography>
        </Paper>
      ) : (
        <TableContainer component={Paper} variant="outlined" sx={{ borderRadius: 2 }}>
          <Table size="small">
            <TableHead>
              <TableRow>
                <TableCell sx={{ fontWeight: 600 }}>Fecha prometida</TableCell>
                <TableCell sx={{ fontWeight: 600 }} align="right">Monto Gs.</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {proyeccion.map((r) => (
                <TableRow key={r.fecha} hover sx={{ "&:last-child td": { borderBottom: 0 } }}>
                  <TableCell>{fmtFechaCalendario(r.fecha)}</TableCell>
                  <TableCell align="right">
                    <Typography variant="body2" fontWeight={700} color="success.main">
                      {fmtGs(r.monto)}
                    </Typography>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>
      )}
    </Box>
  );
}
