import { Icon } from "@iconify/react";
import {
  Box,
  Button,
  Card,
  CardContent,
  Chip,
  FormControl,
  InputAdornment,
  InputLabel,
  MenuItem,
  Pagination,
  Paper,
  Select,
  Skeleton,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  Typography,
  useMediaQuery,
  useTheme,
} from "@mui/material";
import { useQuery } from "@tanstack/react-query";
import { useCallback, useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import { toast } from "sonner";
import * as XLSX from "xlsx";
import api from "../api/api.config";
import { AccesoRestringido } from "../components/common/AccesoRestringido";
import { usePermission } from "../hooks/usePermission";
import { sanitizeRows } from "../components/_standards";
import { hoyISO } from "../utils/fecha";

// ==================== API ====================

const getFacturas = async (params) => {
  const query = new URLSearchParams();
  query.set("page", String(params.page || 1));
  query.set("limit", String(params.limit || 20));
  if (params.fecha_desde) query.set("fecha_desde", params.fecha_desde);
  if (params.fecha_hasta) query.set("fecha_hasta", params.fecha_hasta);
  if (params.estado) query.set("estado", params.estado);
  if (params.search) query.set("search", params.search);
  const res = await api.get(`/facturas?${query.toString()}`);
  return res.data;
};

// Resumen agregado sobre TODO el filtro (no la página): totales, IVA y conteos.
const getResumenVentas = async (params = {}) => {
  const q = new URLSearchParams();
  if (params.fecha_desde) q.set("fecha_desde", params.fecha_desde);
  if (params.fecha_hasta) q.set("fecha_hasta", params.fecha_hasta);
  if (params.estado) q.set("estado", params.estado);
  if (params.search) q.set("search", params.search);
  const res = await api.get(`/facturas/resumen?${q.toString()}`);
  return res.data;
};

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

const formatMoney = (amount, currencyCode = "PYG") => {
  const currency = currencyCode || "PYG";
  return new Intl.NumberFormat("es-PY", {
    style: "currency",
    currency,
    minimumFractionDigits: currency === "PYG" ? 0 : 2,
  }).format(amount || 0);
};

const formatFecha = (fecha) => {
  if (!fecha) return "-";
  const d = new Date(fecha);
  if (isNaN(d.getTime())) return "-";
  return `${String(d.getDate()).padStart(2, "0")}/${String(d.getMonth() + 1).padStart(2, "0")}/${d.getFullYear()} ${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
};

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

const getMontoFactura = (f) => f.factura_subtotales?.[0]?.dtotope || f.total_factura || 0;
const getMonedaFactura = (f) => f.moneda?.codigo || "PYG";
const getClienteNombre = (f) => f.clientes?.personas?.razon_social || f.clientes?.nombre || "Sin nombre";
// Documento del cliente: RUC con dígito verificador si es contribuyente; si no,
// el nro. de documento (cédula, pasaporte…), que es lo que tienen los particulares.
const getClienteRuc = (f) => {
  const p = f.clientes?.personas;
  if (p?.ruc) return p.dv ? `${p.ruc}-${p.dv}` : p.ruc;
  // "0" es el documento del cliente genérico (consumidor final / sin nombre).
  const doc = p?.nro_documento;
  return doc && doc !== "0" ? doc : "";
};
// Número completo del comprobante: establecimiento-punto de expedición-número
// (001-001-0000002). Sólo el correlativo se repite entre sucursales y puntos.
const getNumeroFactura = (f) => {
  if (!f.dnumdoc) return f.numero_factura || "-";
  return f.dest && f.dpunexp ? `${f.dest}-${f.dpunexp}-${f.dnumdoc}` : f.dnumdoc;
};

const getEstadoColor = (estado) => {
  switch (estado?.toLowerCase()) {
    case "aprobado":
    case "pagada":
      return "success";
    case "pendiente":
    case "enviado":
      return "warning";
    case "rechazado":
    case "anulado":
    case "anulada":
      return "error";
    default:
      return "default";
  }
};

const getCondicionLabel = (f) => {
  if (f.condicion_operacion?.descripcion) return f.condicion_operacion.descripcion;
  if (f.condicion_venta === 1 || f.icondope === 1) return "Contado";
  return "Crédito";
};

// ==================== EXCEL EXPORT ====================
// XLSX con celdas numéricas reales (Monto / IVA) para que la planilla sea operable.

// Formato legible aaaa-mm-dd hh:mm:ss (sin la "T" ni la "Z" del ISO crudo).
// Se toman las partes del string tal cual se guardan (mismo criterio que la UI),
// sin convertir zona horaria.
const fmtFechaExport = (iso) => {
  if (!iso) return "";
  const [fecha, hora] = String(iso).split("T");
  if (!fecha) return String(iso);
  const hhmmss = hora ? hora.substring(0, 8) : "00:00:00";
  return `${fecha} ${hhmmss}`;
};

// Bloque de totales al pie de la hoja. Sale del mismo resumen que los KPIs de la
// pantalla (ventas válidas del filtro), no de sumar las filas: con "Todos" las
// filas incluyen anuladas y rechazadas, y el total no coincidiría con la pantalla.
// Columnas: etiqueta (0), moneda (5), monto (6), IVA 10% (7), IVA 5% (8).
const filasTotales = (resumen) => {
  if (!resumen) return [];
  const fila = (label, moneda = "", monto = "", iva10 = "", iva5 = "") => [label, "", "", "", "", moneda, monto, iva10, iva5, ""];
  const porMoneda = (label, montos) => {
    const entradas = Object.entries(montos || {});
    return entradas.length === 0 ? [fila(label, "PYG", 0)] : entradas.map(([moneda, total]) => fila(label, moneda, Number(total) || 0));
  };
  return [
    [],
    ["TOTALES (ventas válidas del filtro)"],
    ...porMoneda("Total ventas", resumen.ventasPorMoneda),
    ...porMoneda(`Contado (${resumen.contado.cantidad} facturas)`, resumen.contado.porMoneda),
    ...porMoneda(`Crédito (${resumen.credito.cantidad} facturas)`, resumen.credito.porMoneda),
    fila("IVA", "", "", resumen.totalIVA10, resumen.totalIVA5),
    fila(`Facturas: ${resumen.cantFacturas} · Anuladas: ${resumen.cantAnuladas}`),
  ];
};

const exportExcel = (facturas, resumen) => {
  if (!facturas?.length) return;
  const num = (v) => (v === null || v === undefined || v === "" ? 0 : Number(v) || 0);
  const headers = ["Fecha", "Número", "Cliente", "RUC / CI", "Condición", "Moneda", "Monto", "IVA 10%", "IVA 5%", "Estado"];
  const rows = facturas.map((f) => {
    const sub = f.factura_subtotales?.[0] || {};
    return [
      fmtFechaExport(f.dfeemide || f.fecha_factura || ""),
      getNumeroFactura(f),
      getClienteNombre(f),
      getClienteRuc(f),
      getCondicionLabel(f),
      getMonedaFactura(f),
      num(getMontoFactura(f)),
      num(sub.diva10),
      num(sub.diva5),
      f.estado || "",
    ];
  });

  const totales = filasTotales(resumen);
  const ws = XLSX.utils.aoa_to_sheet(sanitizeRows([headers, ...rows, ...totales]));
  // Formato de miles en las columnas numéricas: Monto (6), IVA 10% (7), IVA 5% (8).
  const range = XLSX.utils.decode_range(ws["!ref"]);
  for (let R = 1; R <= range.e.r; R++) {
    for (const C of [6, 7, 8]) {
      const cell = ws[XLSX.utils.encode_cell({ r: R, c: C })];
      if (cell && typeof cell.v === "number") {
        cell.t = "n";
        cell.z = "#,##0";
      }
    }
  }
  ws["!cols"] = [16, 18, 32, 14, 12, 8, 16, 14, 14, 12].map((wch) => ({ wch }));

  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, "Resumen de Ventas");
  XLSX.writeFile(wb, `resumen_ventas_${getHoy()}.xlsx`);
  toast.success("Reporte exportado correctamente");
};

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

export function ReporteVentas() {
  const navigate = useNavigate();
  const muiTheme = useTheme();
  const isMobile = useMediaQuery(muiTheme.breakpoints.down("md"));
  const { canRead } = usePermission("REPORTES");

  const [search, setSearch] = useState("");
  const [searchDebounced, setSearchDebounced] = useState("");
  const [fechaDesde, setFechaDesde] = useState(getInicioMes());
  const [fechaHasta, setFechaHasta] = useState(getHoy());
  // Por defecto mostramos solo las APROBADAS (sin anular) para que la lista y la
  // exportación coincidan con el "Total Ventas" de los KPIs (ventas válidas). El
  // usuario puede cambiar a "Todos" u otro estado; el export respeta lo elegido.
  const [estado, setEstado] = useState("aprobado");
  const [page, setPage] = useState(1);
  const limit = 20;

  const handleSearchChange = useCallback((e) => {
    setSearch(e.target.value);
    clearTimeout(window._ventasSearchTimer);
    window._ventasSearchTimer = setTimeout(() => {
      setSearchDebounced(e.target.value);
      setPage(1);
    }, 400);
  }, []);

  const { data: facturasData, isLoading } = useQuery({
    queryKey: ["reporte-ventas", fechaDesde, fechaHasta, estado, searchDebounced, page],
    queryFn: () =>
      getFacturas({
        page,
        limit,
        fecha_desde: fechaDesde || undefined,
        fecha_hasta: fechaHasta || undefined,
        estado: estado || undefined,
        search: searchDebounced || undefined,
      }),
  });

  const facturas = useMemo(() => facturasData?.data || [], [facturasData]);
  const totalItems = facturasData?.total || 0;
  const totalPages = facturasData?.lastPage || 1;

  // Resumen agregado sobre TODO el filtro (backend), no la página visible.
  const { data: resumenData } = useQuery({
    queryKey: ["reporte-ventas-resumen", fechaDesde, fechaHasta, estado, searchDebounced],
    queryFn: () =>
      getResumenVentas({
        fecha_desde: fechaDesde || undefined,
        fecha_hasta: fechaHasta || undefined,
        estado: estado || undefined,
        search: searchDebounced || undefined,
      }),
  });

  // KPIs desde el resumen filtro-wide (ver ui-standards "KPIs reflejan el FILTRO, no la página").
  const resumen = useMemo(
    () => ({
      ventasPorMoneda: resumenData?.ventasPorMoneda || {},
      contado: resumenData?.ventasPorCondicion?.contado || { cantidad: 0, porMoneda: {} },
      credito: resumenData?.ventasPorCondicion?.credito || { cantidad: 0, porMoneda: {} },
      totalIVA10: Number(resumenData?.totalIva10 || 0),
      totalIVA5: Number(resumenData?.totalIva5 || 0),
      cantFacturas: Number(resumenData?.facturas || 0),
      cantAnuladas: Number(resumenData?.anuladas || 0),
    }),
    [resumenData],
  );

  const handleExport = async () => {
    try {
      // El backend capa el límite a 100 por página, así que paginamos y juntamos
      // TODOS los registros del filtro (no solo la primera página).
      const LIMIT = 100;
      const baseParams = {
        fecha_desde: fechaDesde || undefined,
        fecha_hasta: fechaHasta || undefined,
        estado: estado || undefined,
        search: searchDebounced || undefined,
      };
      let paginaActual = 1;
      let ultimaPagina = 1;
      let todas = [];
      do {
        const resp = await getFacturas({ ...baseParams, page: paginaActual, limit: LIMIT });
        todas = todas.concat(resp?.data || []);
        ultimaPagina = resp?.lastPage || 1;
        paginaActual += 1;
      } while (paginaActual <= ultimaPagina);
      exportExcel(todas, resumenData ? resumen : null);
    } catch {
      toast.error("Error al exportar");
    }
  };

  if (!canRead) return <AccesoRestringido mensaje="No tienes permisos para ver reportes." />;

  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:bar-chart-3" width={22} />
              <Typography variant="h6" fontWeight={700}>
                Resumen de Ventas
              </Typography>
            </Box>
            <Typography variant="caption" color="text.secondary">
              Facturación por período con desglose de montos e IVA
            </Typography>
          </Box>
        </Box>
        <Button variant="outlined" size="small" startIcon={<Icon icon="lucide:download" width={16} />} onClick={handleExport}>
          Exportar Excel
        </Button>
      </Box>

      <Typography variant="caption" color="text.secondary" sx={{ mb: 2, display: "block" }}>
        <span style={{ cursor: "pointer" }} onClick={() => navigate("/reportes")}>
          Reportes
        </span>
        {" > "}Resumen de Ventas
      </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"
            placeholder="Buscar por nro. factura o cliente..."
            value={search}
            onChange={handleSearchChange}
            sx={{ minWidth: 250, flex: { xs: "1 1 100%", sm: "0 1 auto" } }}
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <Icon icon="lucide:search" width={16} />
                </InputAdornment>
              ),
            }}
          />
          <FormControl size="small" sx={{ minWidth: 140 }}>
            <InputLabel>Estado</InputLabel>
            <Select
              value={estado}
              label="Estado"
              onChange={(e) => {
                setEstado(e.target.value);
                setPage(1);
              }}
            >
              <MenuItem value="">Todos</MenuItem>
              <MenuItem value="aprobado">Aprobado</MenuItem>
              <MenuItem value="pendiente">Pendiente</MenuItem>
              <MenuItem value="rechazado">Rechazado</MenuItem>
              <MenuItem value="anulada">Anulado</MenuItem>
            </Select>
          </FormControl>
          <TextField
            size="small"
            type="date"
            label="Desde"
            value={fechaDesde}
            onChange={(e) => {
              setFechaDesde(e.target.value);
              setPage(1);
            }}
            InputLabelProps={{ shrink: true }}
            sx={{ minWidth: 145 }}
          />
          <TextField
            size="small"
            type="date"
            label="Hasta"
            value={fechaHasta}
            onChange={(e) => {
              setFechaHasta(e.target.value);
              setPage(1);
            }}
            InputLabelProps={{ shrink: true }}
            sx={{ minWidth: 145 }}
          />
        </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:trending-up" width={20} style={{ opacity: 0.6 }} />
            <Box>
              <Typography variant="caption" color="text.secondary">
                Total Ventas
              </Typography>
              {Object.entries(resumen.ventasPorMoneda).length === 0 ? (
                <Typography variant="h6" fontWeight={700} color="success.main">
                  {formatMoney(0)}
                </Typography>
              ) : (
                Object.entries(resumen.ventasPorMoneda).map(([moneda, total]) => (
                  <Typography key={moneda} variant="h6" fontWeight={700} color="success.main">
                    {formatMoney(total, moneda)}
                  </Typography>
                ))
              )}
              {[
                { key: "contado", label: "Contado", color: "text.primary" },
                { key: "credito", label: "Crédito", color: "warning.main" },
              ].map(({ key, label, color }) => {
                const grupo = resumen[key];
                const montos = Object.entries(grupo.porMoneda);
                return (
                  <Typography key={key} variant="body2" color="text.secondary" sx={{ lineHeight: 1.5 }}>
                    {label}:{" "}
                    <Box component="span" sx={{ fontWeight: 600, color }}>
                      {montos.length === 0 ? formatMoney(0) : montos.map(([moneda, total]) => formatMoney(total, moneda)).join(" + ")}
                    </Box>{" "}
                    ({grupo.cantidad})
                  </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">
                IVA Total
              </Typography>
              <Typography variant="body2" fontWeight={600} color="warning.main">
                10%: {formatMoney(resumen.totalIVA10)}
              </Typography>
              <Typography variant="body2" fontWeight={600} color="warning.main">
                5%: {formatMoney(resumen.totalIVA5)}
              </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:file-text" width={20} style={{ opacity: 0.6 }} />
            <Box>
              <Typography variant="caption" color="text.secondary">
                Facturas
              </Typography>
              <Typography variant="h6" fontWeight={700} color="primary.main">
                {resumen.cantFacturas}
              </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:file-x" width={20} style={{ opacity: 0.6 }} />
            <Box>
              <Typography variant="caption" color="text.secondary">
                Anuladas
              </Typography>
              <Typography variant="h6" fontWeight={700} color="error.main">
                {resumen.cantAnuladas}
              </Typography>
            </Box>
          </CardContent>
        </Card>
      </Box>

      {/* ── Tabla ── */}
      {isLoading ? (
        <Box sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
          {[...Array(10)].map((_, i) => (
            <Skeleton key={i} variant="rounded" height={44} />
          ))}
        </Box>
      ) : facturas.length === 0 ? (
        <Paper variant="outlined" sx={{ p: 6, textAlign: "center", borderRadius: 2 }}>
          <Icon icon="lucide:inbox" width={48} style={{ opacity: 0.3, marginBottom: 12 }} />
          <Typography color="text.secondary">No hay facturas para el período seleccionado</Typography>
        </Paper>
      ) : isMobile ? (
        <Box sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
          {facturas.map((f) => (
            <Card key={f.id} variant="outlined" sx={{ borderRadius: 2 }}>
              <CardContent sx={{ p: "12px !important" }}>
                <Box sx={{ display: "flex", justifyContent: "space-between", mb: 0.5 }}>
                  <Typography variant="body2" fontWeight={600}>
                    {getNumeroFactura(f)}
                  </Typography>
                  <Chip label={f.estado || "PENDIENTE"} color={getEstadoColor(f.estado)} size="small" sx={{ fontSize: "0.68rem", height: 20 }} />
                </Box>
                <Typography variant="caption" color="text.secondary">
                  {getClienteNombre(f)}
                  {getClienteRuc(f) ? ` • ${getClienteRuc(f)}` : ""}
                </Typography>
                <Box sx={{ display: "flex", justifyContent: "space-between", mt: 1 }}>
                  <Typography variant="caption" color="text.secondary">
                    {formatFecha(f.dfeemide || f.fecha_factura || f.created_at)}
                  </Typography>
                  <Typography variant="body2" fontWeight={700} color="success.main">
                    {formatMoney(getMontoFactura(f), getMonedaFactura(f))}
                  </Typography>
                </Box>
              </CardContent>
            </Card>
          ))}
        </Box>
      ) : (
        <TableContainer component={Paper} variant="outlined" sx={{ borderRadius: 2 }}>
          <Table size="small">
            <TableHead>
              <TableRow>
                <TableCell sx={{ fontWeight: 600 }}>Fecha</TableCell>
                <TableCell sx={{ fontWeight: 600 }}>Número</TableCell>
                <TableCell sx={{ fontWeight: 600 }}>Cliente</TableCell>
                <TableCell sx={{ fontWeight: 600 }}>RUC / CI</TableCell>
                <TableCell sx={{ fontWeight: 600 }}>Condición</TableCell>
                <TableCell sx={{ fontWeight: 600 }}>Moneda</TableCell>
                <TableCell sx={{ fontWeight: 600 }} align="right">
                  Monto
                </TableCell>
                <TableCell sx={{ fontWeight: 600 }} align="right">
                  IVA
                </TableCell>
                <TableCell sx={{ fontWeight: 600 }}>Estado</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {facturas.map((f) => {
                const sub = f.factura_subtotales?.[0] || {};
                const ivaTotal = (Number(sub.diva10) || 0) + (Number(sub.diva5) || 0);
                return (
                  <TableRow key={f.id} hover sx={{ "&:last-child td": { borderBottom: 0 } }}>
                    <TableCell sx={{ whiteSpace: "nowrap" }}>{formatFecha(f.dfeemide || f.fecha_factura || f.created_at)}</TableCell>
                    <TableCell sx={{ whiteSpace: "nowrap" }}>
                      <Typography variant="body2" fontWeight={600}>
                        {getNumeroFactura(f)}
                      </Typography>
                    </TableCell>
                    <TableCell>
                      <Typography variant="body2">{getClienteNombre(f)}</Typography>
                    </TableCell>
                    <TableCell>
                      <Typography variant="caption" color="text.secondary">
                        {getClienteRuc(f) || "-"}
                      </Typography>
                    </TableCell>
                    <TableCell>
                      <Chip label={getCondicionLabel(f)} size="small" variant="outlined" color={getCondicionLabel(f) === "Contado" ? "default" : "warning"} />
                    </TableCell>
                    <TableCell>
                      <Chip label={getMonedaFactura(f)} size="small" variant="outlined" sx={{ fontSize: "0.72rem" }} />
                    </TableCell>
                    <TableCell align="right">
                      <Typography
                        variant="body2"
                        fontWeight={700}
                        color={f.estado === "Anulada" ? "text.disabled" : "success.main"}
                        sx={{ textDecoration: f.estado === "Anulada" ? "line-through" : "none" }}
                      >
                        {formatMoney(getMontoFactura(f), getMonedaFactura(f))}
                      </Typography>
                    </TableCell>
                    <TableCell align="right">
                      <Typography variant="body2" color="text.secondary">
                        {formatMoney(ivaTotal, getMonedaFactura(f))}
                      </Typography>
                    </TableCell>
                    <TableCell>
                      <Chip label={f.estado || "PENDIENTE"} size="small" color={getEstadoColor(f.estado)} />
                    </TableCell>
                  </TableRow>
                );
              })}
            </TableBody>
          </Table>
        </TableContainer>
      )}

      {/* ── Paginación ── */}
      {totalItems > 0 && (
        <Box
          sx={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            mt: 2,
            flexWrap: "wrap",
            gap: 1,
          }}
        >
          <Typography variant="caption" color="text.secondary">
            Mostrando {(page - 1) * limit + 1}-{Math.min(page * limit, totalItems)} de {totalItems}
          </Typography>
          <Pagination count={totalPages} page={page} onChange={(_, p) => setPage(p)} size="small" color="primary" />
        </Box>
      )}
    </Box>
  );
}
