import { Icon } from "@iconify/react";
import {
  Box,
  Button,
  Card,
  CardContent,
  Chip,
  CircularProgress,
  Container,
  IconButton,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { useEffect, useMemo, useState } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import { toast } from "sonner";
import {
  getReporteInteresesDetalle,
  getReporteInteresesResumen,
} from "../api/cobros.service";
import { EmptyState } from "../components/_standards";
import { usePermission } from "../hooks/usePermission";
import { formatMoney } from "../utils/formatMoney";
import { fmtFechaCalendario, hoyISO } from "../utils/fecha";

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

export function ReporteInteresesCobrados() {
  const navigate = useNavigate();
  const { can: canCobranzas } = usePermission("COBRANZAS");
  const canVer = canCobranzas("COB_INT_VER");
  const canVerRecibo = canCobranzas("COB_REC_RECIBO_VER");

  const [searchParams] = useSearchParams();
  const [fechaDesde, setFechaDesde] = useState(
    searchParams.get("fecha_desde") || primerDiaMes(),
  );
  const [fechaHasta, setFechaHasta] = useState(
    searchParams.get("fecha_hasta") || hoyStr(),
  );

  const [resumen, setResumen] = useState(null);
  const [detalle, setDetalle] = useState(null);
  const [page, setPage] = useState(1);
  const pageSize = 20;
  const [loading, setLoading] = useState(false);

  const cargar = async () => {
    if (!canVer) return;
    setLoading(true);
    try {
      const [res, det] = await Promise.all([
        getReporteInteresesResumen({ fecha_desde: fechaDesde, fecha_hasta: fechaHasta }),
        getReporteInteresesDetalle({
          fecha_desde: fechaDesde,
          fecha_hasta: fechaHasta,
          page,
          pageSize,
        }),
      ]);
      setResumen(res);
      setDetalle(det);
    } catch (e) {
      toast.error(e?.response?.data?.message || "Error al cargar el reporte");
    } finally {
      setLoading(false);
    }
  };

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

  const kpis = useMemo(() => {
    if (!resumen) return [];
    const t = resumen.totales;
    return [
      { label: "Cobrado neto", value: formatMoney(t.monto_cobrado), icon: "lucide:banknote", color: "success.main" },
      { label: "Interés bruto", value: formatMoney(t.monto_bruto), icon: "lucide:calculator", color: "text.primary" },
      { label: "Exonerado", value: formatMoney(t.monto_exonerado), icon: "lucide:shield-off", color: "warning.main", extra: `${t.tasa_exoneracion}% del bruto` },
      { label: "IVA cobrado", value: formatMoney(t.monto_iva), icon: "lucide:receipt", color: "text.primary" },
      { label: "Recibos", value: t.cantidad_recibos, icon: "lucide:files", color: "text.primary", extra: `${t.cantidad_cuotas} cuotas` },
    ];
  }, [resumen]);

  if (!canVer) {
    return (
      <Container maxWidth="xl" sx={{ py: 3 }}>
        <Typography variant="body2" color="text.secondary">
          No tenés permisos para ver el reporte de intereses cobrados.
        </Typography>
      </Container>
    );
  }

  return (
    <Container maxWidth="xl" sx={{ py: 3 }}>
      <Stack direction="row" alignItems="center" spacing={1.5} mb={2}>
        <Tooltip title="Volver a Reportes">
          <IconButton onClick={() => navigate("/reportes")} size="small">
            <Icon icon="lucide:arrow-left" width={20} />
          </IconButton>
        </Tooltip>
        <Box>
          <Typography variant="h5" fontWeight={700}>
            Intereses Moratorios Cobrados
          </Typography>
          <Typography variant="body2" color="text.secondary">
            Ranking por cliente y cobrador. Clic en una fila del detalle para abrir el recibo asociado.
          </Typography>
        </Box>
      </Stack>

      {/* Filtros */}
      <Card sx={{ mb: 2 }}>
        <CardContent>
          <Stack direction={{ xs: "column", sm: "row" }} spacing={2} alignItems="center">
            <TextField
              type="date"
              label="Desde"
              value={fechaDesde}
              onChange={(e) => setFechaDesde(e.target.value)}
              InputLabelProps={{ shrink: true }}
              size="small"
            />
            <TextField
              type="date"
              label="Hasta"
              value={fechaHasta}
              onChange={(e) => setFechaHasta(e.target.value)}
              InputLabelProps={{ shrink: true }}
              size="small"
            />
            <Button
              variant="contained"
              onClick={() => {
                setPage(1);
                cargar();
              }}
              startIcon={<Icon icon="lucide:search" />}
              disabled={loading}
            >
              Aplicar
            </Button>
            {loading && <CircularProgress size={20} />}
          </Stack>
        </CardContent>
      </Card>

      {/* KPIs */}
      {resumen && (
        <Stack
          direction={{ xs: "column", sm: "row" }}
          spacing={2}
          mb={2}
          sx={{ width: "100%" }}
        >
          {kpis.map((k) => (
            <Card key={k.label} sx={{ flex: 1, minWidth: 0 }}>
              <CardContent>
                <Stack direction="row" spacing={1} alignItems="center" mb={0.5}>
                  <Icon icon={k.icon} width={18} />
                  <Typography variant="caption" color="text.secondary" noWrap>
                    {k.label}
                  </Typography>
                </Stack>
                <Typography variant="h6" fontWeight={700} sx={{ color: k.color }} noWrap>
                  {k.value}
                </Typography>
                {k.extra && (
                  <Typography variant="caption" color="text.secondary" noWrap>
                    {k.extra}
                  </Typography>
                )}
              </CardContent>
            </Card>
          ))}
        </Stack>
      )}

      {/* Rankings */}
      {resumen && (
        <Stack direction={{ xs: "column", md: "row" }} spacing={2} mb={2} sx={{ width: "100%" }}>
          <Box sx={{ flex: 1, minWidth: 0 }}>
            <Card>
              <CardContent>
                <Typography variant="subtitle1" fontWeight={700} mb={1}>
                  Top clientes
                </Typography>
                {resumen.ranking_clientes.length === 0 ? (
                  <EmptyState icon="lucide:users" title="Sin datos en el período" description="" compact />
                ) : (
                  <TableContainer>
                    <Table size="small">
                      <TableHead>
                        <TableRow>
                          <TableCell>Cliente</TableCell>
                          <TableCell align="right">Cuotas</TableCell>
                          <TableCell align="right">Cobrado</TableCell>
                          <TableCell align="right">Exonerado</TableCell>
                        </TableRow>
                      </TableHead>
                      <TableBody>
                        {resumen.ranking_clientes.slice(0, 10).map((c) => (
                          <TableRow key={c.cliente_id} hover>
                            <TableCell>{c.cliente_nombre}</TableCell>
                            <TableCell align="right">{c.cantidad_cuotas}</TableCell>
                            <TableCell align="right">{formatMoney(c.monto_cobrado)}</TableCell>
                            <TableCell align="right">
                              <Typography variant="body2" color="warning.main">
                                {formatMoney(c.monto_exonerado)}
                              </Typography>
                            </TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </TableContainer>
                )}
              </CardContent>
            </Card>
          </Box>
          <Box sx={{ flex: 1, minWidth: 0 }}>
            <Card>
              <CardContent>
                <Typography variant="subtitle1" fontWeight={700} mb={1}>
                  Por cobrador
                </Typography>
                {resumen.ranking_cobradores.length === 0 ? (
                  <EmptyState icon="lucide:user-check" title="Sin datos en el período" description="" compact />
                ) : (
                  <TableContainer>
                    <Table size="small">
                      <TableHead>
                        <TableRow>
                          <TableCell>Cobrador</TableCell>
                          <TableCell align="right">Cuotas</TableCell>
                          <TableCell align="right">Cobrado</TableCell>
                          <TableCell align="right">Exonerado</TableCell>
                        </TableRow>
                      </TableHead>
                      <TableBody>
                        {resumen.ranking_cobradores.map((c) => (
                          <TableRow key={c.cobrador_id ?? "sin-cobrador"} hover>
                            <TableCell>{c.cobrador_nombre}</TableCell>
                            <TableCell align="right">{c.cantidad_cuotas}</TableCell>
                            <TableCell align="right">{formatMoney(c.monto_cobrado)}</TableCell>
                            <TableCell align="right">
                              <Typography variant="body2" color="warning.main">
                                {formatMoney(c.monto_exonerado)}
                              </Typography>
                            </TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </TableContainer>
                )}
              </CardContent>
            </Card>
          </Box>
        </Stack>
      )}

      {/* Detalle */}
      <Card>
        <CardContent>
          <Stack direction="row" justifyContent="space-between" alignItems="center" mb={1}>
            <Typography variant="subtitle1" fontWeight={700}>
              Detalle por cuota
            </Typography>
            {detalle && (
              <Typography variant="caption" color="text.secondary">
                {detalle.total} filas — página {detalle.page} de {detalle.totalPages || 1}
              </Typography>
            )}
          </Stack>
          {!detalle || detalle.data.length === 0 ? (
            <EmptyState
              icon="lucide:inbox"
              title="Sin intereses cobrados en el período"
              description="Ajustá las fechas o verificá que haya recibos con mora en este rango."
            />
          ) : (
            <>
              <TableContainer>
                <Table size="small">
                  <TableHead>
                    <TableRow>
                      <TableCell>Fecha</TableCell>
                      <TableCell>Recibo</TableCell>
                      <TableCell>Cliente</TableCell>
                      <TableCell>Cobrador</TableCell>
                      <TableCell>Factura · Cuota</TableCell>
                      <TableCell align="right">Días</TableCell>
                      <TableCell align="right">Bruto</TableCell>
                      <TableCell align="right">Exonerado</TableCell>
                      <TableCell align="right">Cobrado</TableCell>
                      <TableCell align="center">Emitido</TableCell>
                      <TableCell align="center">Acciones</TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {detalle.data.map((row) => (
                      <TableRow key={row.id} hover>
                        <TableCell>{fmtFechaCalendario(row.fecha)}</TableCell>
                        <TableCell>{row.recibo.numero}</TableCell>
                        <TableCell>{row.cliente.nombre}</TableCell>
                        <TableCell>{row.cobrador?.nombre || "—"}</TableCell>
                        <TableCell>
                          {row.factura} · cuota {row.nro_cuota ?? "—"}
                        </TableCell>
                        <TableCell align="right">{row.dias_mora}</TableCell>
                        <TableCell align="right">{formatMoney(row.monto_bruto)}</TableCell>
                        <TableCell align="right">
                          {row.monto_exonerado > 0 ? (
                            <Tooltip title={row.autorizacion_descuento_id ? "Con autorización de descuento" : "Exonerado"}>
                              <Typography variant="body2" color="warning.main">
                                {formatMoney(row.monto_exonerado)}
                              </Typography>
                            </Tooltip>
                          ) : (
                            "—"
                          )}
                        </TableCell>
                        <TableCell align="right">
                          <Typography variant="body2" fontWeight={600}>
                            {formatMoney(row.monto_cobrado)}
                          </Typography>
                        </TableCell>
                        <TableCell align="center">
                          {row.tipo_comprobante === "NINGUNO" ? (
                            <Chip size="small" label="Sin comp." variant="outlined" />
                          ) : row.emitido ? (
                            <Chip size="small" color="success" label={row.tipo_comprobante} />
                          ) : (
                            <Chip size="small" color="warning" label="Pendiente" />
                          )}
                        </TableCell>
                        <TableCell align="center">
                          {canVerRecibo && (
                            <Tooltip title="Ver recibo (fuente de verdad para reclamos del cliente)">
                              <IconButton
                                size="small"
                                onClick={() => navigate(`/cobranzas/recibos?recibo=${row.recibo.id}`)}
                              >
                                <Icon icon="lucide:external-link" width={16} />
                              </IconButton>
                            </Tooltip>
                          )}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </TableContainer>

              <Stack direction="row" justifyContent="flex-end" spacing={1} mt={2}>
                <Button
                  size="small"
                  disabled={page <= 1 || loading}
                  onClick={() => setPage((p) => p - 1)}
                >
                  Anterior
                </Button>
                <Button
                  size="small"
                  disabled={!detalle.totalPages || page >= detalle.totalPages || loading}
                  onClick={() => setPage((p) => p + 1)}
                >
                  Siguiente
                </Button>
              </Stack>
            </>
          )}
        </CardContent>
      </Card>
    </Container>
  );
}

export default ReporteInteresesCobrados;
