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 { getReporteProductividadGestiones } from "../../api/cobranzas.service";
import { AccesoRestringido } from "../../components/common/AccesoRestringido";
import {
  COB_GESTION_RESULTADO_META,
  COB_GESTION_TIPO_META,
} from "../../components/_standards/enums/estados";
import { usePermission } from "../../hooks/usePermission";
import { sanitizeRows } from "../../components/_standards";
import { hoyISO } from "../../utils/fecha";

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 >= 60) return "success";
  if (pct >= 30) return "warning";
  return "error";
};

const TIPOS = Object.keys(COB_GESTION_TIPO_META);
const RESULTADOS = Object.keys(COB_GESTION_RESULTADO_META);

function exportarExcel(rows, periodo) {
  const wb = XLSX.utils.book_new();
  const header = [
    "Cobrador",
    "Total",
    "Efectivas",
    "Tasa efect. (%)",
    ...TIPOS.map((t) => `Tipo: ${COB_GESTION_TIPO_META[t].label}`),
    ...RESULTADOS.map((r) => `Res: ${COB_GESTION_RESULTADO_META[r].label}`),
  ];
  const data = [header];
  for (const r of rows) {
    data.push([
      r.cobrador,
      r.total,
      r.efectivas,
      Number(r.tasa_efectividad || 0).toFixed(1),
      ...TIPOS.map((t) => r.por_tipo?.[t] ?? 0),
      ...RESULTADOS.map((rs) => r.por_resultado?.[rs] ?? 0),
    ]);
  }
  XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(sanitizeRows(data)), "Productividad");
  XLSX.writeFile(wb, `productividad-cobradores-${periodo.desde}-${periodo.hasta}.xlsx`);
  toast.success("Reporte exportado correctamente");
}

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

  const [desde, setDesde] = useState(getInicioMes());
  const [hasta, setHasta] = useState(getHoy());
  const [rows, setRows] = useState([]);
  const [loading, setLoading] = useState(false);

  const cargar = async () => {
    if (!desde || !hasta) {
      toast.warning("Seleccioná desde y hasta");
      return;
    }
    setLoading(true);
    try {
      const data = await getReporteProductividadGestiones({ desde, hasta });
      setRows(Array.isArray(data) ? data : []);
    } 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 totalGestiones = rows.reduce((s, r) => s + (r.total || 0), 0);
  const totalEfectivas = rows.reduce((s, r) => s + (r.efectivas || 0), 0);
  const tasaGlobal = totalGestiones > 0 ? (totalEfectivas / totalGestiones) * 100 : 0;
  const totalCobradores = rows.length;

  return (
    <Box sx={{ maxWidth: 1500, 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="mdi:clipboard-check-multiple-outline" width={22} />
              <Typography variant="h6" fontWeight={700}>
                Productividad de Cobradores
              </Typography>
            </Box>
            <Typography variant="caption" color="text.secondary">
              Gestiones realizadas por cobrador, distribución por tipo/resultado y tasa de efectividad
            </Typography>
          </Box>
        </Box>
        <Button
          variant="outlined"
          size="small"
          startIcon={<Icon icon="lucide:download" width={16} />}
          onClick={() => rows.length && exportarExcel(rows, { desde, hasta })}
          disabled={!rows.length || loading}
        >
          Exportar
        </Button>
      </Box>

      <Typography variant="caption" color="text.secondary" sx={{ mb: 2, display: "block" }}>
        <span style={{ cursor: "pointer" }} onClick={() => navigate("/reportes")}>
          Reportes
        </span>
        {" > "}Productividad de Cobradores
      </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={desde}
            onChange={(e) => setDesde(e.target.value)}
            InputLabelProps={{ shrink: true }}
            sx={{ minWidth: 145 }}
          />
          <TextField
            size="small"
            type="date"
            label="Hasta"
            value={hasta}
            onChange={(e) => setHasta(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(4, 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:users" width={20} style={{ opacity: 0.6 }} />
            <Box>
              <Typography variant="caption" color="text.secondary">Cobradores activos</Typography>
              <Typography variant="h6" fontWeight={700} color="primary.main">
                {fmtNum(totalCobradores)}
              </Typography>
            </Box>
          </CardContent>
        </Card>
        <Card variant="outlined" sx={{ borderRadius: 2 }}>
          <CardContent sx={{ p: "14px !important", display: "flex", alignItems: "center", gap: 1.5 }}>
            <Icon icon="mdi:clipboard-text-outline" width={20} style={{ opacity: 0.6 }} />
            <Box>
              <Typography variant="caption" color="text.secondary">Total gestiones</Typography>
              <Typography variant="h6" fontWeight={700}>
                {fmtNum(totalGestiones)}
              </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">Efectivas</Typography>
              <Typography variant="h6" fontWeight={700} color="success.main">
                {fmtNum(totalEfectivas)}
              </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 efectividad</Typography>
              <Typography variant="h6" fontWeight={700} color={`${tasaColor(tasaGlobal)}.main`}>
                {fmtPct(tasaGlobal)}
              </Typography>
            </Box>
          </CardContent>
        </Card>
      </Box>

      {/* Tabla */}
      <Typography variant="subtitle2" sx={{ mb: 1, display: "flex", alignItems: "center", gap: 0.75 }}>
        <Icon icon="lucide:bar-chart-2" width={16} />
        Detalle 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>
      ) : rows.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 gestiones 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">Efectivas</TableCell>
                <TableCell sx={{ fontWeight: 600 }} align="center">Tasa</TableCell>
                {TIPOS.map((t) => (
                  <TableCell key={t} sx={{ fontWeight: 600 }} align="right">
                    {COB_GESTION_TIPO_META[t].label}
                  </TableCell>
                ))}
              </TableRow>
            </TableHead>
            <TableBody>
              {rows.map((r) => (
                <TableRow key={r.cobrador_id} hover sx={{ "&:last-child td": { borderBottom: 0 } }}>
                  <TableCell>
                    <Typography variant="body2" fontWeight={600}>
                      {r.cobrador || "— Sin nombre"}
                    </Typography>
                  </TableCell>
                  <TableCell align="right">{fmtNum(r.total)}</TableCell>
                  <TableCell align="right">
                    <Typography variant="body2" color="success.main" fontWeight={600}>
                      {fmtNum(r.efectivas)}
                    </Typography>
                  </TableCell>
                  <TableCell align="center">
                    <Chip
                      size="small"
                      label={fmtPct(r.tasa_efectividad)}
                      color={tasaColor(r.tasa_efectividad)}
                      sx={{ fontWeight: 700 }}
                    />
                  </TableCell>
                  {TIPOS.map((t) => (
                    <TableCell key={t} align="right">
                      {fmtNum(r.por_tipo?.[t] ?? 0)}
                    </TableCell>
                  ))}
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>
      )}
    </Box>
  );
}
