import {
    Add,
    Campaign,
    Close,
    Delete,
    Edit,
    FilterList,
    HelpOutline,
    Info,
    Percent,
    PowerSettingsNew,
    Search,
    Sell,
    Storefront,
} from "@mui/icons-material";
import {
    Alert,
    Autocomplete,
    Box,
    Button,
    Card,
    CardContent,
    Chip,
    CircularProgress,
    Collapse,
    Dialog,
    DialogActions,
    DialogContent,
    DialogTitle,
    Divider,
    FormControl,
    FormControlLabel,
    IconButton,
    InputAdornment,
    InputLabel,
    MenuItem,
    Pagination,
    Paper,
    Select,
    Skeleton,
    Switch,
    Table,
    TableBody,
    TableCell,
    TableContainer,
    TableHead,
    TableRow,
    TextField,
    Tooltip,
    Typography,
    useMediaQuery,
    useTheme,
} from "@mui/material";
import { useQuery } from "@tanstack/react-query";
import { useCallback, useState } from "react";
import { toast } from "sonner";
import { getCategorias } from "../../api/categorias.service";
import {
    buscarProductos as buscarProductosApi,
    getProducto,
} from "../../api/productos.service";
import { usePermission } from "../../hooks/usePermission";
import { useAuthStore } from "../../store/AuthStore";
import { useMarcasQuery } from "../../tanstack/MarcasStack";
import {
    useCreateOfertaMutation,
    useDeleteOfertaMutation,
    useOfertasQuery,
    useToggleOfertaMutation,
    useUpdateOfertaMutation,
} from "../../tanstack/OfertasStack";
import { useSucursalesQuery } from "../../tanstack/SucursalesStack";
import { getErrorApi } from "../../utils/errorUtils";
import { AccesoRestringido } from "../common/AccesoRestringido";

// ==================== CONSTANTES ====================

const TIPOS_OFERTA = [
  {
    value: "descuento_porcentaje",
    label: "Descuento por porcentaje",
    icon: <Percent sx={{ fontSize: 18 }} />,
    color: "#4caf50",
    ejemplo: "Ej: 20% OFF en lácteos",
    ayuda: "Aplica un % de descuento sobre el precio del producto",
  },
  {
    value: "descuento_monto",
    label: "Descuento por monto fijo",
    icon: <Sell sx={{ fontSize: 18 }} />,
    color: "#2196f3",
    ejemplo: "Ej: Gs. 5.000 de descuento",
    ayuda: "Resta un monto fijo del precio del producto",
  },
  {
    value: "precio_especial",
    label: "Precio especial",
    icon: <Storefront sx={{ fontSize: 18 }} />,
    color: "#ff9800",
    ejemplo: "Ej: Heladera a Gs. 500.000",
    ayuda: "Establece un precio fijo promocional para el producto",
  },
];

const APLICA_A_OPTIONS = [
  {
    value: "todos",
    label: "Todos los productos",
    ayuda: "La oferta se aplica a todo el catálogo",
  },
  {
    value: "categoria",
    label: "Categoría específica",
    ayuda: "Solo aplica a los productos de la categoría seleccionada",
  },
  {
    value: "marca",
    label: "Marca específica",
    ayuda: "Solo aplica a los productos de la marca seleccionada",
  },
  {
    value: "producto",
    label: "Producto específico",
    ayuda: "Solo aplica al producto seleccionado",
  },
];

const FORM_INITIAL = {
  nombre: "",
  descripcion: "",
  tipo: "descuento_porcentaje",
  valor: "",
  fecha_inicio: "",
  fecha_fin: "",
  prioridad: 0,
  acumulable_lista_precios: true,
  aplica_a: "todos",
  referencia_id: null,
  sucursal_ids: [],
};

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

function formatDate(dateStr) {
  if (!dateStr) return "-";
  return new Date(dateStr).toLocaleDateString("es-PY", {
    day: "2-digit",
    month: "short",
    year: "numeric",
  });
}

function formatDateInput(dateStr) {
  if (!dateStr) return "";
  const d = new Date(dateStr);
  return d.toISOString().slice(0, 16);
}

function getEstadoOferta(oferta) {
  if (!oferta.active) return { label: "Inactiva", color: "default" };
  const ahora = new Date();
  const inicio = new Date(oferta.fecha_inicio);
  const fin = new Date(oferta.fecha_fin);
  if (ahora < inicio) return { label: "Programada", color: "info" };
  if (ahora > fin) return { label: "Vencida", color: "warning" };
  return { label: "Activa", color: "success" };
}

function getTipoInfo(tipo) {
  return TIPOS_OFERTA.find((t) => t.value === tipo) || TIPOS_OFERTA[0];
}

function formatValor(tipo, valor) {
  const v = Number(valor);
  if (tipo === "descuento_porcentaje") return `${v}%`;
  return `Gs. ${v.toLocaleString("es-PY")}`;
}

function getAplicaLabel(oferta) {
  const ap = oferta.oferta_aplicacion;
  if (!ap || ap.length === 0) return "Sin definir";
  const inclusiones = ap.filter((a) => !a.excluir);
  if (inclusiones.length === 0) return "Sin definir";
  if (inclusiones.some((a) => a.aplica_a === "todos"))
    return "Todos los productos";
  const tipos = inclusiones.map((a) => {
    if (a.aplica_a === "categoria") return "Categoría";
    if (a.aplica_a === "marca") return "Marca";
    if (a.aplica_a === "producto") return "Producto";
    return a.aplica_a;
  });
  return tipos.join(", ");
}

// ==================== COMPONENTE PRINCIPAL ====================

export function OfertasTab() {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down("md"));
  const hasModule = useAuthStore((s) => s.hasModule);
  const hasEcommerce = hasModule("ECOMMERCE");
  const { can } = usePermission("INVENTARIO");
  const canCreate = can("INV_OFE_OFERTA_CREAR") || hasEcommerce;
  const canEdit = can("INV_OFE_OFERTA_EDITAR") || hasEcommerce;
  const canDelete = can("INV_OFE_OFERTA_ELIMINAR");

  // States
  const [formDialogOpen, setFormDialogOpen] = useState(false);
  const [formMode, setFormMode] = useState("create");
  const [selectedOferta, setSelectedOferta] = useState(null);
  const [formData, setFormData] = useState({ ...FORM_INITIAL });
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [ofertaToDelete, setOfertaToDelete] = useState(null);
  const [filtroEstado, setFiltroEstado] = useState("todas");
  const [filtroTipo, setFiltroTipo] = useState("");
  const [showHelp, setShowHelp] = useState(false);
  const [detalleDialogOpen, setDetalleDialogOpen] = useState(false);
  const [detalleOferta, setDetalleOferta] = useState(null);

  // Paginación y búsqueda
  const [page, setPage] = useState(1);
  const [limit] = useState(10);
  const [searchText, setSearchText] = useState("");
  const [searchDebounced, setSearchDebounced] = useState("");
  const [searchTimer, setSearchTimer] = useState(null);

  // Producto search states (para formulario)
  const [productosSearch, setProductosSearch] = useState([]);
  const [productoSearchLoading, setProductoSearchLoading] = useState(false);
  const [productoSearchTimer, setProductoSearchTimer] = useState(null);

  // Construir params para la query del listado
  const queryParams = {
    page,
    limit,
    ...(searchDebounced && { q: searchDebounced }),
    ...(filtroTipo && { tipo: filtroTipo }),
    ...(filtroEstado === "activas" && { active: "true" }),
    ...(filtroEstado === "inactivas" && { active: "false" }),
  };

  // Queries
  const {
    data: ofertasData,
    isLoading,
    error: ofertasError,
  } = useOfertasQuery(queryParams);
  const errorModulo = getErrorApi(ofertasError);
  const ofertas = ofertasData?.items || [];
  const totalOfertas = ofertasData?.total || 0;
  const lastPage = ofertasData?.lastPage || 1;

  const { data: marcas = [] } = useMarcasQuery();
  const { data: sucursalesData } = useSucursalesQuery();
  const sucursales = sucursalesData || [];

  // Categorías desde backend API
  const { data: categoriasData } = useQuery({
    queryKey: ["categorias-ofertas"],
    queryFn: () => getCategorias(1, 200),
    staleTime: 1000 * 60 * 5,
  });
  const categorias = Array.isArray(categoriasData?.data)
    ? categoriasData.data
    : Array.isArray(categoriasData?.items)
      ? categoriasData.items
      : Array.isArray(categoriasData)
        ? categoriasData
        : [];

  // Debounce para búsqueda en listado
  const handleSearchChange = (value) => {
    setSearchText(value);
    if (searchTimer) clearTimeout(searchTimer);
    const timer = setTimeout(() => {
      setSearchDebounced(value);
      setPage(1);
    }, 400);
    setSearchTimer(timer);
  };

  // Búsqueda de productos con debounce (para formulario)
  const handleProductoSearch = useCallback(
    (query) => {
      if (productoSearchTimer) clearTimeout(productoSearchTimer);
      if (!query || query.length < 2) {
        setProductosSearch([]);
        return;
      }
      setProductoSearchLoading(true);
      const timer = setTimeout(async () => {
        try {
          const results = await buscarProductosApi(query, 20);
          setProductosSearch(results || []);
        } catch {
          setProductosSearch([]);
        } finally {
          setProductoSearchLoading(false);
        }
      }, 350);
      setProductoSearchTimer(timer);
    },
    [productoSearchTimer],
  );

  // Mutations
  const createMutation = useCreateOfertaMutation();
  const updateMutation = useUpdateOfertaMutation();
  const toggleMutation = useToggleOfertaMutation();
  const deleteMutation = useDeleteOfertaMutation();

  // Filtrar ofertas del lado del cliente solo para estados calculados (programadas/vencidas)
  const ofertasFiltradas =
    filtroEstado === "programadas"
      ? ofertas.filter((o) => getEstadoOferta(o).label === "Programada")
      : filtroEstado === "vencidas"
        ? ofertas.filter((o) => getEstadoOferta(o).label === "Vencida")
        : ofertas;

  // ==================== HANDLERS ====================

  const handleOpenCreate = () => {
    setFormMode("create");
    setSelectedOferta(null);
    setFormData({ ...FORM_INITIAL });
    setFormDialogOpen(true);
  };

  const handleOpenEdit = async (oferta) => {
    setFormMode("edit");
    setSelectedOferta(oferta);
    const ap = oferta.oferta_aplicacion?.[0];
    setFormData({
      nombre: oferta.nombre || "",
      descripcion: oferta.descripcion || "",
      tipo: oferta.tipo,
      valor: Number(oferta.valor) || "",
      fecha_inicio: formatDateInput(oferta.fecha_inicio),
      fecha_fin: formatDateInput(oferta.fecha_fin),
      prioridad: oferta.prioridad || 0,
      acumulable_lista_precios: oferta.acumulable_lista_precios !== false,
      aplica_a: ap?.aplica_a || "todos",
      referencia_id: ap?.referencia_id || null,
      sucursal_ids: oferta.oferta_sucursales?.map((s) => s.sucursal_id) || [],
    });

    // Pre-cargar producto si aplica_a es "producto" para que el Autocomplete lo muestre
    if (ap?.aplica_a === "producto" && ap?.referencia_id) {
      try {
        const producto = await getProducto(ap.referencia_id);
        if (producto) {
          const prod = producto.data || producto;
          setProductosSearch((prev) => {
            const exists = prev.some((p) => p.id === prod.id);
            return exists ? prev : [prod, ...prev];
          });
        }
      } catch (error) {
        console.error("Error cargando producto de oferta:", error);
      }
    }

    setFormDialogOpen(true);
  };

  const handleCloseForm = () => {
    setFormDialogOpen(false);
    setSelectedOferta(null);
  };

  const handleSubmit = () => {
    // Validaciones
    if (!formData.nombre.trim()) {
      toast.error("El nombre es requerido");
      return;
    }
    if (!formData.tipo) {
      toast.error("Seleccione un tipo de oferta");
      return;
    }
    if (!formData.valor || Number(formData.valor) <= 0) {
      toast.error("El valor debe ser mayor a 0");
      return;
    }
    if (
      formData.tipo === "descuento_porcentaje" &&
      Number(formData.valor) > 100
    ) {
      toast.error("El porcentaje no puede ser mayor a 100%");
      return;
    }
    if (!formData.fecha_inicio || !formData.fecha_fin) {
      toast.error("Las fechas de inicio y fin son requeridas");
      return;
    }
    if (new Date(formData.fecha_fin) <= new Date(formData.fecha_inicio)) {
      toast.error("La fecha de fin debe ser posterior a la de inicio");
      return;
    }
    if (formData.aplica_a !== "todos" && !formData.referencia_id) {
      toast.error("Seleccione a qué aplica la oferta");
      return;
    }

    const payload = {
      nombre: formData.nombre.trim(),
      descripcion: formData.descripcion.trim() || undefined,
      tipo: formData.tipo,
      valor: Number(formData.valor),
      fecha_inicio: new Date(formData.fecha_inicio).toISOString(),
      fecha_fin: new Date(formData.fecha_fin).toISOString(),
      prioridad: Number(formData.prioridad) || 0,
      acumulable_lista_precios: formData.acumulable_lista_precios,
      aplicaciones: [
        {
          aplica_a: formData.aplica_a,
          referencia_id:
            formData.aplica_a !== "todos" ? formData.referencia_id : undefined,
        },
      ],
      sucursal_ids:
        formData.sucursal_ids.length > 0 ? formData.sucursal_ids : undefined,
    };

    if (formMode === "create") {
      createMutation.mutate(payload, { onSuccess: () => handleCloseForm() });
    } else {
      updateMutation.mutate(
        { id: selectedOferta.id, data: payload },
        { onSuccess: () => handleCloseForm() },
      );
    }
  };

  const handleOpenDelete = (oferta) => {
    setOfertaToDelete(oferta);
    setDeleteDialogOpen(true);
  };

  const handleCloseDelete = () => {
    setDeleteDialogOpen(false);
    setOfertaToDelete(null);
  };

  const handleConfirmDelete = () => {
    if (ofertaToDelete) {
      deleteMutation.mutate(ofertaToDelete.id, {
        onSuccess: () => handleCloseDelete(),
      });
    }
  };

  const handleOpenDetalle = (oferta) => {
    setDetalleOferta(oferta);
    setDetalleDialogOpen(true);
  };

  // ==================== RENDER ====================

  if (errorModulo) {
    return (
      <AccesoRestringido titulo="Módulo no disponible" mensaje={errorModulo} />
    );
  }

  return (
    <Box sx={{ p: { xs: 1, md: 2 }, height: "100%" }}>
      <Paper
        sx={{
          p: { xs: 1.5, md: 2 },
          height: "100%",
          display: "flex",
          flexDirection: "column",
        }}
      >
        {/* Header con ayuda */}
        <Box
          sx={{
            display: "flex",
            flexDirection: { xs: "column", sm: "row" },
            justifyContent: "space-between",
            alignItems: { xs: "stretch", sm: "center" },
            gap: 1,
            mb: 1.5,
          }}
        >
          <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
            <Campaign color="primary" />
            <Typography
              variant="h6"
              sx={{ fontSize: { xs: "1rem", md: "1.25rem" } }}
            >
              Ofertas y Promociones
            </Typography>
            <Tooltip title="Ver ayuda y ejemplos">
              <IconButton
                size="small"
                onClick={() => setShowHelp(!showHelp)}
                color={showHelp ? "primary" : "default"}
              >
                <HelpOutline sx={{ fontSize: 20 }} />
              </IconButton>
            </Tooltip>
          </Box>
          {canCreate && (
            <Button
              variant="contained"
              startIcon={<Add />}
              onClick={handleOpenCreate}
              size={isMobile ? "small" : "medium"}
              sx={{ textTransform: "none" }}
            >
              Nueva Oferta
            </Button>
          )}
        </Box>

        {/* Panel de ayuda colapsable */}
        <Collapse in={showHelp}>
          <Alert
            severity="info"
            sx={{ mb: 2, borderRadius: 2 }}
            icon={<Info />}
            onClose={() => setShowHelp(false)}
          >
            <Typography variant="subtitle2" gutterBottom>
              Tipos de ofertas disponibles:
            </Typography>
            <Box
              sx={{
                display: "grid",
                gridTemplateColumns: { xs: "1fr", sm: "1fr 1fr 1fr" },
                gap: 1,
                mt: 1,
              }}
            >
              {TIPOS_OFERTA.map((t) => (
                <Box
                  key={t.value}
                  sx={{
                    p: 1,
                    borderRadius: 1,
                    bgcolor: "rgba(0,0,0,0.04)",
                  }}
                >
                  <Box sx={{ display: "flex", alignItems: "center", gap: 0.5 }}>
                    <Box sx={{ color: t.color }}>{t.icon}</Box>
                    <Typography variant="body2" fontWeight={600}>
                      {t.label}
                    </Typography>
                  </Box>
                  <Typography
                    variant="caption"
                    color="text.secondary"
                    display="block"
                  >
                    {t.ayuda}
                  </Typography>
                  <Typography
                    variant="caption"
                    sx={{ fontStyle: "italic", color: t.color }}
                  >
                    {t.ejemplo}
                  </Typography>
                </Box>
              ))}
            </Box>
            <Typography
              variant="caption"
              color="text.secondary"
              sx={{ mt: 1 }}
              display="block"
            >
              Puedes aplicar ofertas a todos los productos, una categoría, una
              marca o un producto específico. Si no seleccionas sucursales, la
              oferta aplica en todas.
            </Typography>
          </Alert>
        </Collapse>

        {/* Buscador */}
        <TextField
          size="small"
          placeholder="Buscar por nombre o descripción..."
          value={searchText}
          onChange={(e) => handleSearchChange(e.target.value)}
          sx={{ mb: 1.5, maxWidth: { sm: 360 } }}
          InputProps={{
            startAdornment: (
              <InputAdornment position="start">
                <Search sx={{ fontSize: 20, color: "text.secondary" }} />
              </InputAdornment>
            ),
            ...(searchText && {
              endAdornment: (
                <InputAdornment position="end">
                  <IconButton
                    size="small"
                    onClick={() => handleSearchChange("")}
                  >
                    <Close sx={{ fontSize: 16 }} />
                  </IconButton>
                </InputAdornment>
              ),
            }),
          }}
        />

        {/* Filtros */}
        <Box
          sx={{
            display: "flex",
            flexDirection: { xs: "column", sm: "row" },
            gap: 1,
            mb: 2,
            alignItems: { xs: "stretch", sm: "center" },
          }}
        >
          <Box sx={{ display: "flex", alignItems: "center", gap: 0.5 }}>
            <FilterList sx={{ fontSize: 18, color: "text.secondary" }} />
            <Typography variant="body2" color="text.secondary">
              Filtros:
            </Typography>
          </Box>
          <Box sx={{ display: "flex", gap: 1, flexWrap: "wrap" }}>
            {[
              { key: "todas", label: "Todas" },
              { key: "activas", label: "Activas" },
              { key: "programadas", label: "Programadas" },
              { key: "vencidas", label: "Vencidas" },
              { key: "inactivas", label: "Inactivas" },
            ].map((f) => (
              <Chip
                key={f.key}
                label={f.label}
                size="small"
                variant={filtroEstado === f.key ? "filled" : "outlined"}
                color={filtroEstado === f.key ? "primary" : "default"}
                onClick={() => {
                  setFiltroEstado(f.key);
                  setPage(1);
                }}
                sx={{ cursor: "pointer" }}
              />
            ))}
          </Box>
          <FormControl size="small" sx={{ minWidth: 160 }}>
            <InputLabel>Tipo</InputLabel>
            <Select
              value={filtroTipo}
              label="Tipo"
              onChange={(e) => {
                setFiltroTipo(e.target.value);
                setPage(1);
              }}
            >
              <MenuItem value="">Todos los tipos</MenuItem>
              {TIPOS_OFERTA.map((t) => (
                <MenuItem key={t.value} value={t.value}>
                  {t.label}
                </MenuItem>
              ))}
            </Select>
          </FormControl>
        </Box>

        {/* Contador */}
        <Typography variant="body2" color="text.secondary" sx={{ mb: 1 }}>
          {totalOfertas} oferta{totalOfertas !== 1 ? "s" : ""}
          {filtroEstado !== "todas" || filtroTipo || searchDebounced
            ? " (filtradas)"
            : ""}
          {lastPage > 1 && ` — Página ${page} de ${lastPage}`}
        </Typography>

        {/* Content */}
        {isMobile ? (
          /* ===== MOBILE: Cards ===== */
          <Box sx={{ flex: 1, overflow: "auto" }}>
            {isLoading ? (
              <Box sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
                {[1, 2, 3].map((i) => (
                  <Skeleton key={i} variant="rounded" height={100} />
                ))}
              </Box>
            ) : ofertasFiltradas.length === 0 ? (
              <EmptyState onCreateClick={handleOpenCreate} />
            ) : (
              <Box sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}>
                {ofertasFiltradas.map((oferta) => {
                  const estado = getEstadoOferta(oferta);
                  const tipoInfo = getTipoInfo(oferta.tipo);
                  return (
                    <Card
                      key={oferta.id}
                      variant="outlined"
                      sx={{
                        borderRadius: 2,
                        opacity: oferta.active ? 1 : 0.6,
                        borderLeft: `4px solid ${tipoInfo.color}`,
                        cursor: "pointer",
                      }}
                      onClick={() => handleOpenDetalle(oferta)}
                    >
                      <CardContent sx={{ p: 1.5, "&:last-child": { pb: 1.5 } }}>
                        <Box
                          sx={{
                            display: "flex",
                            justifyContent: "space-between",
                            alignItems: "flex-start",
                          }}
                        >
                          <Box sx={{ flex: 1, minWidth: 0 }}>
                            <Typography variant="body2" fontWeight={600} noWrap>
                              {oferta.nombre}
                            </Typography>
                            <Box
                              sx={{
                                display: "flex",
                                flexWrap: "wrap",
                                gap: 0.5,
                                mt: 0.5,
                              }}
                            >
                              <Chip
                                label={formatValor(oferta.tipo, oferta.valor)}
                                size="small"
                                sx={{
                                  height: 22,
                                  fontSize: "0.7rem",
                                  fontWeight: 700,
                                  bgcolor: tipoInfo.color,
                                  color: "#fff",
                                }}
                              />
                              <Chip
                                label={estado.label}
                                size="small"
                                color={estado.color}
                                variant="outlined"
                                sx={{ height: 22, fontSize: "0.65rem" }}
                              />
                            </Box>
                            <Typography
                              variant="caption"
                              color="text.secondary"
                              display="block"
                              sx={{ mt: 0.5 }}
                            >
                              {formatDate(oferta.fecha_inicio)} →{" "}
                              {formatDate(oferta.fecha_fin)}
                            </Typography>
                          </Box>
                          <Box
                            sx={{ display: "flex", gap: 0.25 }}
                            onClick={(e) => e.stopPropagation()}
                          >
                            {canEdit && (
                              <IconButton
                                size="small"
                                onClick={() => handleOpenEdit(oferta)}
                                color="warning"
                              >
                                <Edit sx={{ fontSize: 18 }} />
                              </IconButton>
                            )}
                            {canDelete && (
                              <IconButton
                                size="small"
                                onClick={() => toggleMutation.mutate(oferta.id)}
                                color={oferta.active ? "error" : "success"}
                              >
                                <PowerSettingsNew sx={{ fontSize: 18 }} />
                              </IconButton>
                            )}
                          </Box>
                        </Box>
                      </CardContent>
                    </Card>
                  );
                })}
              </Box>
            )}
          </Box>
        ) : (
          /* ===== DESKTOP: Table ===== */
          <TableContainer sx={{ flex: 1 }}>
            <Table size="medium" stickyHeader>
              <TableHead>
                <TableRow>
                  <TableCell>Nombre</TableCell>
                  <TableCell>Tipo</TableCell>
                  <TableCell align="center">Valor</TableCell>
                  <TableCell>Aplica a</TableCell>
                  <TableCell>Vigencia</TableCell>
                  <TableCell align="center">Estado</TableCell>
                  <TableCell align="center">Usos</TableCell>
                  <TableCell align="right">Acciones</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {isLoading ? (
                  <TableRow>
                    <TableCell colSpan={8} align="center">
                      Cargando ofertas...
                    </TableCell>
                  </TableRow>
                ) : ofertasFiltradas.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={8} align="center">
                      <EmptyState onCreateClick={handleOpenCreate} />
                    </TableCell>
                  </TableRow>
                ) : (
                  ofertasFiltradas.map((oferta) => {
                    const estado = getEstadoOferta(oferta);
                    const tipoInfo = getTipoInfo(oferta.tipo);
                    return (
                      <TableRow
                        key={oferta.id}
                        hover
                        sx={{
                          opacity: oferta.active ? 1 : 0.6,
                          cursor: "pointer",
                          "&:hover": { bgcolor: "action.hover" },
                        }}
                        onClick={() => handleOpenDetalle(oferta)}
                      >
                        <TableCell>
                          <Box>
                            <Typography variant="body2" fontWeight={600}>
                              {oferta.nombre}
                            </Typography>
                            {oferta.descripcion && (
                              <Typography
                                variant="caption"
                                color="text.secondary"
                                noWrap
                                display="block"
                                sx={{ maxWidth: 200 }}
                              >
                                {oferta.descripcion}
                              </Typography>
                            )}
                          </Box>
                        </TableCell>
                        <TableCell>
                          <Chip
                            icon={tipoInfo.icon}
                            label={tipoInfo.label
                              .replace("Descuento por ", "")
                              .replace("Precio ", "P.")}
                            size="small"
                            variant="outlined"
                            sx={{
                              borderColor: tipoInfo.color,
                              color: tipoInfo.color,
                              fontSize: "0.75rem",
                            }}
                          />
                        </TableCell>
                        <TableCell align="center">
                          <Typography
                            variant="body2"
                            fontWeight={700}
                            sx={{ color: tipoInfo.color }}
                          >
                            {formatValor(oferta.tipo, oferta.valor)}
                          </Typography>
                        </TableCell>
                        <TableCell>
                          <Typography variant="body2">
                            {getAplicaLabel(oferta)}
                          </Typography>
                          {oferta.oferta_sucursales?.length > 0 && (
                            <Typography
                              variant="caption"
                              color="text.secondary"
                            >
                              {oferta.oferta_sucursales.length} sucursal(es)
                            </Typography>
                          )}
                        </TableCell>
                        <TableCell>
                          <Typography variant="caption" display="block">
                            {formatDate(oferta.fecha_inicio)}
                          </Typography>
                          <Typography variant="caption" color="text.secondary">
                            → {formatDate(oferta.fecha_fin)}
                          </Typography>
                        </TableCell>
                        <TableCell align="center">
                          <Chip
                            label={estado.label}
                            size="small"
                            color={estado.color}
                            variant="outlined"
                          />
                        </TableCell>
                        <TableCell align="center">
                          <Typography variant="body2">
                            {oferta._count?.oferta_usos || 0}
                          </Typography>
                        </TableCell>
                        <TableCell
                          align="right"
                          onClick={(e) => e.stopPropagation()}
                        >
                          <Box
                            sx={{
                              display: "flex",
                              gap: 0.5,
                              justifyContent: "flex-end",
                            }}
                          >
                            {canEdit && (
                              <Tooltip title="Editar">
                                <IconButton
                                  size="small"
                                  onClick={() => handleOpenEdit(oferta)}
                                  color="warning"
                                >
                                  <Edit fontSize="small" />
                                </IconButton>
                              </Tooltip>
                            )}
                            {canDelete && (
                              <Tooltip
                                title={oferta.active ? "Desactivar" : "Activar"}
                              >
                                <IconButton
                                  size="small"
                                  onClick={() =>
                                    toggleMutation.mutate(oferta.id)
                                  }
                                  color={oferta.active ? "error" : "success"}
                                >
                                  <PowerSettingsNew fontSize="small" />
                                </IconButton>
                              </Tooltip>
                            )}
                            {canDelete && (
                              <Tooltip title="Eliminar">
                                <IconButton
                                  size="small"
                                  onClick={() => handleOpenDelete(oferta)}
                                  color="error"
                                >
                                  <Delete fontSize="small" />
                                </IconButton>
                              </Tooltip>
                            )}
                          </Box>
                        </TableCell>
                      </TableRow>
                    );
                  })
                )}
              </TableBody>
            </Table>
          </TableContainer>
        )}

        {/* Paginación */}
        {lastPage > 1 && (
          <Box
            sx={{
              display: "flex",
              justifyContent: "center",
              alignItems: "center",
              pt: 2,
              pb: 1,
            }}
          >
            <Pagination
              count={lastPage}
              page={page}
              onChange={(_, newPage) => setPage(newPage)}
              size={isMobile ? "small" : "medium"}
              color="primary"
              showFirstButton
              showLastButton
            />
          </Box>
        )}
      </Paper>

      {/* ===== DIALOG CREAR/EDITAR ===== */}
      <Dialog
        open={formDialogOpen}
        onClose={handleCloseForm}
        maxWidth="sm"
        fullWidth
        fullScreen={isMobile}
      >
        <DialogTitle
          sx={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
          }}
        >
          <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
            <Campaign color="primary" />
            {formMode === "create" ? "Nueva Oferta" : "Editar Oferta"}
          </Box>
          <IconButton size="small" onClick={handleCloseForm}>
            <Close />
          </IconButton>
        </DialogTitle>
        <Divider />
        <DialogContent sx={{ pt: 2 }}>
          <Box sx={{ display: "flex", flexDirection: "column", gap: 2.5 }}>
            {/* Nombre */}
            <TextField
              fullWidth
              size="small"
              label="Nombre de la oferta *"
              value={formData.nombre}
              onChange={(e) =>
                setFormData({ ...formData, nombre: e.target.value })
              }
              placeholder="Ej: Promo Verano 2026, Descuento Lácteos, etc."
              helperText="Un nombre claro que identifique la promoción"
              inputProps={{ maxLength: 200 }}
              autoFocus
            />

            {/* Descripción */}
            <TextField
              fullWidth
              size="small"
              label="Descripción (opcional)"
              value={formData.descripcion}
              onChange={(e) =>
                setFormData({ ...formData, descripcion: e.target.value })
              }
              placeholder="Descripción interna de la oferta"
              multiline
              rows={2}
            />

            <Divider>
              <Typography variant="caption" color="text.secondary">
                Tipo y valor del descuento
              </Typography>
            </Divider>

            {/* Tipo de oferta */}
            <FormControl fullWidth size="small">
              <InputLabel>Tipo de oferta *</InputLabel>
              <Select
                value={formData.tipo}
                label="Tipo de oferta *"
                onChange={(e) =>
                  setFormData({ ...formData, tipo: e.target.value, valor: "" })
                }
              >
                {TIPOS_OFERTA.map((t) => (
                  <MenuItem key={t.value} value={t.value}>
                    <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
                      <Box sx={{ color: t.color }}>{t.icon}</Box>
                      <Box>
                        <Typography variant="body2">{t.label}</Typography>
                        <Typography variant="caption" color="text.secondary">
                          {t.ejemplo}
                        </Typography>
                      </Box>
                    </Box>
                  </MenuItem>
                ))}
              </Select>
            </FormControl>

            {/* Valor */}
            <TextField
              fullWidth
              size="small"
              label={
                formData.tipo === "descuento_porcentaje"
                  ? "Porcentaje de descuento *"
                  : formData.tipo === "descuento_monto"
                    ? "Monto de descuento (Gs.) *"
                    : "Precio especial (Gs.) *"
              }
              type="number"
              value={formData.valor}
              onChange={(e) =>
                setFormData({ ...formData, valor: e.target.value })
              }
              placeholder={
                formData.tipo === "descuento_porcentaje" ? "20" : "50000"
              }
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start">
                    {formData.tipo === "descuento_porcentaje" ? "%" : "Gs."}
                  </InputAdornment>
                ),
              }}
              helperText={getTipoInfo(formData.tipo).ayuda}
              inputProps={{
                min: 0,
                max: formData.tipo === "descuento_porcentaje" ? 100 : undefined,
              }}
            />

            <Divider>
              <Typography variant="caption" color="text.secondary">
                ¿A qué productos aplica?
              </Typography>
            </Divider>

            {/* Aplica a */}
            <FormControl fullWidth size="small">
              <InputLabel>Aplica a *</InputLabel>
              <Select
                value={formData.aplica_a}
                label="Aplica a *"
                onChange={(e) =>
                  setFormData({
                    ...formData,
                    aplica_a: e.target.value,
                    referencia_id: null,
                  })
                }
              >
                {APLICA_A_OPTIONS.map((opt) => (
                  <MenuItem key={opt.value} value={opt.value}>
                    <Box>
                      <Typography variant="body2">{opt.label}</Typography>
                      <Typography variant="caption" color="text.secondary">
                        {opt.ayuda}
                      </Typography>
                    </Box>
                  </MenuItem>
                ))}
              </Select>
            </FormControl>

            {/* Selector de referencia */}
            {formData.aplica_a === "marca" && (
              <Autocomplete
                size="small"
                options={marcas.filter((m) => m.active !== false)}
                getOptionLabel={(opt) => opt.descripcion || ""}
                value={
                  marcas.find((m) => m.id === formData.referencia_id) || null
                }
                onChange={(_, val) =>
                  setFormData({ ...formData, referencia_id: val?.id || null })
                }
                renderInput={(params) => (
                  <TextField
                    {...params}
                    label="Seleccionar marca *"
                    placeholder="Buscar marca..."
                  />
                )}
              />
            )}

            {formData.aplica_a === "categoria" && (
              <Autocomplete
                size="small"
                options={categorias}
                getOptionLabel={(opt) => opt.descripcion || opt.nombre || ""}
                value={
                  categorias.find((c) => c.id === formData.referencia_id) ||
                  null
                }
                onChange={(_, val) =>
                  setFormData({ ...formData, referencia_id: val?.id || null })
                }
                renderOption={(props, option) => (
                  <li {...props} key={option.id}>
                    <Box>
                      <Typography variant="body2">
                        {option.descripcion || option.nombre}
                      </Typography>
                      {option.color && (
                        <Box
                          sx={{
                            width: 12,
                            height: 12,
                            borderRadius: "50%",
                            bgcolor: option.color,
                            display: "inline-block",
                            ml: 1,
                          }}
                        />
                      )}
                    </Box>
                  </li>
                )}
                renderInput={(params) => (
                  <TextField
                    {...params}
                    label="Seleccionar categoría *"
                    placeholder="Buscar categoría..."
                    helperText="Escribí para filtrar las categorías disponibles"
                  />
                )}
              />
            )}

            {formData.aplica_a === "producto" && (
              <Autocomplete
                size="small"
                options={productosSearch}
                getOptionLabel={(opt) =>
                  opt.descripcion
                    ? `${opt.descripcion}${opt.codigo_barra ? ` (${opt.codigo_barra})` : ""}`
                    : ""
                }
                value={
                  productosSearch.find(
                    (p) => p.id === formData.referencia_id,
                  ) || null
                }
                onChange={(_, val) =>
                  setFormData({ ...formData, referencia_id: val?.id || null })
                }
                onInputChange={(_, value, reason) => {
                  if (reason === "input") handleProductoSearch(value);
                }}
                loading={productoSearchLoading}
                filterOptions={(x) => x}
                renderOption={(props, option) => (
                  <li {...props} key={option.id}>
                    <Box>
                      <Typography variant="body2">
                        {option.descripcion}
                      </Typography>
                      <Box sx={{ display: "flex", gap: 1 }}>
                        {option.codigo_barra && (
                          <Typography variant="caption" color="text.secondary">
                            Cód: {option.codigo_barra}
                          </Typography>
                        )}
                        {option.precio && (
                          <Typography variant="caption" color="primary">
                            Gs. {Number(option.precio).toLocaleString("es-PY")}
                          </Typography>
                        )}
                      </Box>
                    </Box>
                  </li>
                )}
                renderInput={(params) => (
                  <TextField
                    {...params}
                    label="Buscar producto *"
                    placeholder="Escribí el nombre, código o código de barra..."
                    helperText="Mínimo 2 caracteres para buscar"
                    InputProps={{
                      ...params.InputProps,
                      endAdornment: (
                        <>
                          {productoSearchLoading ? (
                            <CircularProgress color="inherit" size={18} />
                          ) : null}
                          {params.InputProps.endAdornment}
                        </>
                      ),
                    }}
                  />
                )}
              />
            )}

            <Divider>
              <Typography variant="caption" color="text.secondary">
                Vigencia y alcance
              </Typography>
            </Divider>

            {/* Fechas */}
            <Box
              sx={{
                display: "grid",
                gridTemplateColumns: { xs: "1fr", sm: "1fr 1fr" },
                gap: 2,
              }}
            >
              <TextField
                fullWidth
                size="small"
                label="Fecha inicio *"
                type="datetime-local"
                value={formData.fecha_inicio}
                onChange={(e) =>
                  setFormData({ ...formData, fecha_inicio: e.target.value })
                }
                InputLabelProps={{ shrink: true }}
                helperText="Desde cuándo aplica la oferta"
              />
              <TextField
                fullWidth
                size="small"
                label="Fecha fin *"
                type="datetime-local"
                value={formData.fecha_fin}
                onChange={(e) =>
                  setFormData({ ...formData, fecha_fin: e.target.value })
                }
                InputLabelProps={{ shrink: true }}
                helperText="Hasta cuándo estará vigente"
              />
            </Box>

            {/* Sucursales */}
            {sucursales.length > 0 && (
              <Autocomplete
                multiple
                size="small"
                options={sucursales}
                getOptionLabel={(opt) => opt.descripcion || opt.label || ""}
                value={sucursales.filter((s) =>
                  formData.sucursal_ids.includes(s.id),
                )}
                onChange={(_, vals) =>
                  setFormData({
                    ...formData,
                    sucursal_ids: vals.map((v) => v.id),
                  })
                }
                renderInput={(params) => (
                  <TextField
                    {...params}
                    label="Sucursales donde aplica"
                    placeholder="Dejar vacío = todas las sucursales"
                    helperText="Si no seleccionas ninguna, aplica en todas"
                  />
                )}
                renderTags={(tagValue, getTagProps) =>
                  tagValue.map((option, index) => (
                    <Chip
                      {...getTagProps({ index })}
                      key={option.id}
                      label={option.descripcion || option.label}
                      size="small"
                    />
                  ))
                }
              />
            )}

            {/* Prioridad */}
            <TextField
              fullWidth
              size="small"
              label="Prioridad"
              type="number"
              value={formData.prioridad}
              onChange={(e) =>
                setFormData({
                  ...formData,
                  prioridad: parseInt(e.target.value) || 0,
                })
              }
              helperText="Mayor número = más prioridad. Si dos ofertas aplican al mismo producto, gana la de mayor prioridad"
              inputProps={{ min: 0, max: 999 }}
            />

            {/* Acumulable con lista de precios */}
            <Box
              sx={{
                p: 1.5,
                borderRadius: 1,
                bgcolor: (theme) =>
                  formData.acumulable_lista_precios
                    ? theme.palette.mode === "dark"
                      ? "rgba(46, 125, 50, 0.12)"
                      : "rgba(46, 125, 50, 0.08)"
                    : theme.palette.mode === "dark"
                      ? "rgba(255, 255, 255, 0.05)"
                      : "rgba(0, 0, 0, 0.04)",
                border: "1px solid",
                borderColor: (theme) =>
                  formData.acumulable_lista_precios
                    ? theme.palette.mode === "dark"
                      ? "rgba(46, 125, 50, 0.3)"
                      : "rgba(46, 125, 50, 0.3)"
                    : theme.palette.divider,
              }}
            >
              <FormControlLabel
                control={
                  <Switch
                    checked={formData.acumulable_lista_precios}
                    onChange={(e) =>
                      setFormData({
                        ...formData,
                        acumulable_lista_precios: e.target.checked,
                      })
                    }
                    color="success"
                  />
                }
                label={
                  <Box>
                    <Typography variant="body2" fontWeight={500}>
                      Acumulable con listas de precios
                    </Typography>
                    <Typography variant="caption" color="text.secondary">
                      {formData.acumulable_lista_precios
                        ? "El descuento se aplica SOBRE el precio de lista del cliente (se acumulan)"
                        : "Se compara con el precio de lista y se aplica el mayor beneficio para el cliente"}
                    </Typography>
                  </Box>
                }
              />
            </Box>
          </Box>
        </DialogContent>
        <Divider />
        <DialogActions sx={{ p: 2 }}>
          <Button onClick={handleCloseForm} sx={{ textTransform: "none" }}>
            Cancelar
          </Button>
          <Button
            variant="contained"
            onClick={handleSubmit}
            disabled={createMutation.isPending || updateMutation.isPending}
            sx={{ textTransform: "none" }}
          >
            {createMutation.isPending || updateMutation.isPending
              ? "Guardando..."
              : formMode === "create"
                ? "Crear oferta"
                : "Guardar cambios"}
          </Button>
        </DialogActions>
      </Dialog>

      {/* ===== DIALOG DETALLE ===== */}
      <Dialog
        open={detalleDialogOpen}
        onClose={() => setDetalleDialogOpen(false)}
        maxWidth="sm"
        fullWidth
        fullScreen={isMobile}
      >
        {detalleOferta && (
          <>
            <DialogTitle
              sx={{
                display: "flex",
                alignItems: "center",
                justifyContent: "space-between",
              }}
            >
              <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
                <Box sx={{ color: getTipoInfo(detalleOferta.tipo).color }}>
                  {getTipoInfo(detalleOferta.tipo).icon}
                </Box>
                {detalleOferta.nombre}
              </Box>
              <IconButton
                size="small"
                onClick={() => setDetalleDialogOpen(false)}
              >
                <Close />
              </IconButton>
            </DialogTitle>
            <Divider />
            <DialogContent>
              <Box
                sx={{ display: "flex", flexDirection: "column", gap: 2, pt: 1 }}
              >
                {/* Estado y valor */}
                <Box
                  sx={{
                    display: "flex",
                    gap: 2,
                    flexWrap: "wrap",
                    alignItems: "center",
                  }}
                >
                  <Chip
                    label={getEstadoOferta(detalleOferta).label}
                    color={getEstadoOferta(detalleOferta).color}
                    size="small"
                  />
                  <Chip
                    label={formatValor(detalleOferta.tipo, detalleOferta.valor)}
                    sx={{
                      fontWeight: 700,
                      bgcolor: getTipoInfo(detalleOferta.tipo).color,
                      color: "#fff",
                    }}
                  />
                  <Chip
                    label={`${detalleOferta._count?.oferta_usos || 0} uso(s)`}
                    variant="outlined"
                    size="small"
                  />
                </Box>

                {/* Descripción */}
                {detalleOferta.descripcion && (
                  <Typography variant="body2" color="text.secondary">
                    {detalleOferta.descripcion}
                  </Typography>
                )}

                {/* Info grid */}
                <Box
                  sx={{
                    display: "grid",
                    gridTemplateColumns: "1fr 1fr",
                    gap: 1.5,
                  }}
                >
                  <Box>
                    <Typography variant="caption" color="text.secondary">
                      Tipo
                    </Typography>
                    <Typography variant="body2">
                      {getTipoInfo(detalleOferta.tipo).label}
                    </Typography>
                  </Box>
                  <Box>
                    <Typography variant="caption" color="text.secondary">
                      Prioridad
                    </Typography>
                    <Typography variant="body2">
                      {detalleOferta.prioridad || 0}
                    </Typography>
                  </Box>
                  <Box>
                    <Typography variant="caption" color="text.secondary">
                      Fecha inicio
                    </Typography>
                    <Typography variant="body2">
                      {formatDate(detalleOferta.fecha_inicio)}
                    </Typography>
                  </Box>
                  <Box>
                    <Typography variant="caption" color="text.secondary">
                      Fecha fin
                    </Typography>
                    <Typography variant="body2">
                      {formatDate(detalleOferta.fecha_fin)}
                    </Typography>
                  </Box>
                  <Box>
                    <Typography variant="caption" color="text.secondary">
                      Aplica a
                    </Typography>
                    <Typography variant="body2">
                      {getAplicaLabel(detalleOferta)}
                    </Typography>
                  </Box>
                  <Box>
                    <Typography variant="caption" color="text.secondary">
                      Sucursales
                    </Typography>
                    <Typography variant="body2">
                      {detalleOferta.oferta_sucursales?.length > 0
                        ? detalleOferta.oferta_sucursales
                            .map(
                              (s) =>
                                s.empresas_sucursales?.descripcion ||
                                s.sucursal_id,
                            )
                            .join(", ")
                        : "Todas"}
                    </Typography>
                  </Box>
                </Box>
              </Box>
            </DialogContent>
            <Divider />
            <DialogActions sx={{ p: 2, justifyContent: "space-between" }}>
              <Button
                variant="outlined"
                color="warning"
                onClick={() => {
                  setDetalleDialogOpen(false);
                  handleOpenEdit(detalleOferta);
                }}
                startIcon={<Edit />}
                sx={{ textTransform: "none" }}
              >
                Editar
              </Button>
              <Box sx={{ display: "flex", gap: 1 }}>
                <Button
                  onClick={() =>
                    toggleMutation.mutate(detalleOferta.id, {
                      onSuccess: () => setDetalleDialogOpen(false),
                    })
                  }
                  color={detalleOferta.active ? "error" : "success"}
                  variant="outlined"
                  sx={{ textTransform: "none" }}
                >
                  {detalleOferta.active ? "Desactivar" : "Activar"}
                </Button>
                <Button
                  onClick={() => setDetalleDialogOpen(false)}
                  sx={{ textTransform: "none" }}
                >
                  Cerrar
                </Button>
              </Box>
            </DialogActions>
          </>
        )}
      </Dialog>

      {/* ===== DIALOG CONFIRMAR DELETE ===== */}
      <Dialog
        open={deleteDialogOpen}
        onClose={handleCloseDelete}
        maxWidth="xs"
        fullWidth
        fullScreen={isMobile}
      >
        <DialogTitle sx={{ pb: 1 }}>Confirmar eliminación</DialogTitle>
        <DialogContent>
          <Typography>
            ¿Está seguro de desactivar la oferta{" "}
            <strong>&quot;{ofertaToDelete?.nombre}&quot;</strong>?
          </Typography>
          <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
            La oferta dejará de aplicarse pero se mantendrá en el historial.
          </Typography>
        </DialogContent>
        <DialogActions sx={{ p: 2, pt: 1 }}>
          <Button
            onClick={handleCloseDelete}
            variant="outlined"
            sx={{ textTransform: "none" }}
          >
            Cancelar
          </Button>
          <Button
            variant="contained"
            color="error"
            onClick={handleConfirmDelete}
            disabled={deleteMutation.isPending}
            sx={{ textTransform: "none" }}
          >
            {deleteMutation.isPending ? "Eliminando..." : "Desactivar"}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
}

// ==================== EMPTY STATE ====================

function EmptyState({ onCreateClick }) {
  return (
    <Box
      sx={{
        textAlign: "center",
        py: 6,
        px: 2,
      }}
    >
      <Campaign
        sx={{ fontSize: 64, color: "text.disabled", mb: 2, opacity: 0.5 }}
      />
      <Typography variant="h6" color="text.secondary" gutterBottom>
        No hay ofertas configuradas
      </Typography>
      <Typography
        variant="body2"
        color="text.secondary"
        sx={{ maxWidth: 400, mx: "auto", mb: 3 }}
      >
        Crea tu primera oferta para que se aplique automáticamente al facturar.
        Puedes hacer descuentos por porcentaje, monto fijo o precio especial.
      </Typography>
      <Button
        variant="contained"
        startIcon={<Add />}
        onClick={onCreateClick}
        sx={{ textTransform: "none" }}
      >
        Crear mi primera oferta
      </Button>
    </Box>
  );
}
