import {
  Add,
  Calculate,
  Delete,
  Edit,
  PowerSettingsNew,
  Star,
  StarBorder,
} from "@mui/icons-material";
import {
  Alert,
  Box,
  Button,
  Card,
  CardContent,
  Chip,
  Dialog,
  DialogActions,
  DialogContent,
  DialogContentText,
  DialogTitle,
  Divider,
  FormControl,
  FormControlLabel,
  IconButton,
  InputLabel,
  MenuItem,
  Paper,
  Select,
  Skeleton,
  Stack,
  Switch,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  Tooltip,
  Typography,
  useMediaQuery,
  useTheme,
} from "@mui/material";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useMemo, useState } from "react";
import { toast } from "sonner";
import {
  actualizarPlan,
  calcularCuotas,
  crearPlan,
  eliminarPlan,
  getPlanesEmpresa,
} from "../../api/planes-cuotas.service";
import { CategoriaAutocomplete } from "../_standards";
import { usePermission } from "../../hooks/usePermission";
import { AccesoRestringido } from "../common/AccesoRestringido";
import { MonedaInput } from "../common/MonedaInput";

const formatNumber = (value) => {
  if (value === null || value === undefined) return "-";
  return Number(value).toLocaleString("es-PY");
};

const TIPOS_CALCULO = [
  {
    value: "automatico",
    label: "Automático",
    desc: "El sistema calcula las cuotas dividiendo el monto total automáticamente",
  },
  {
    value: "manual",
    label: "Manual",
    desc: "Permite definir el monto de cada cuota manualmente al facturar",
  },
  {
    value: "mixto",
    label: "Mixto",
    desc: "El sistema sugiere montos, pero se pueden ajustar manualmente",
  },
];

const TIPOS_INTERES = [
  {
    value: "simple",
    label: "Simple",
    desc: "El interés se calcula solo sobre el monto original. Ej: 100.000 × 10% = 10.000 de interés total",
  },
  {
    value: "compuesto",
    label: "Compuesto",
    desc: "El interés se acumula sobre el saldo + intereses anteriores. Genera un monto mayor",
  },
  {
    value: "frances",
    label: "Francés",
    desc: "Cuotas fijas: cada cuota incluye capital + interés. Es el sistema más común en financieras",
  },
];

const getCalcHelperText = (tipo) =>
  TIPOS_CALCULO.find((t) => t.value === tipo)?.desc || "";
const getInteresHelperText = (tipo) =>
  TIPOS_INTERES.find((t) => t.value === tipo)?.desc || "";

const defaultFormData = {
  codigo: "",
  nombre: "",
  descripcion: "",
  tipoCalculo: "automatico",
  cantidadCuotas: 3,
  intervaloDias: 30,
  tasaInteres: 0,
  tipoInteres: "simple",
  cuotaInicialRequerida: false,
  cuotaInicialMinima: "",
  montoMinimo: "",
  montoMaximo: "",
  categoriaId: null,
  precioProductoDesde: "",
  precioProductoHasta: "",
  activo: true,
  esDefault: false,
};

export function PlanesCuotasTab() {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down("sm"));
  const queryClient = useQueryClient();
  const { can } = usePermission("VENTAS");
  const canRead = can("VEN_PCA_PLAN_VER");
  const canCreate = can("VEN_PCA_PLAN_CREAR");
  const canEdit = can("VEN_PCA_PLAN_EDITAR");
  const canDelete = can("VEN_PCA_PLAN_ELIMINAR");

  const [formOpen, setFormOpen] = useState(false);
  const [formMode, setFormMode] = useState("create");
  const [editingPlan, setEditingPlan] = useState(null);
  const [formData, setFormData] = useState(defaultFormData);
  const [deleteConfirm, setDeleteConfirm] = useState(null);
  const [simuladorOpen, setSimuladorOpen] = useState(false);
  const [simuladorPlan, setSimuladorPlan] = useState(null);
  const [simuladorMonto, setSimuladorMonto] = useState("");
  const [simuladorEntrada, setSimuladorEntrada] = useState("");
  const [simuladorCuotas, setSimuladorCuotas] = useState("");
  const [simuladorResultado, setSimuladorResultado] = useState(null);

  // La tasa que se carga es EFECTIVA ANUAL (TEA): el costo real del año. La tasa
  // que se aplica a cada cuota se deriva por equivalencia según el intervalo
  // (mismo cálculo del backend, calculo-interes.util.ts). Se muestra acá porque
  // es la fuente de confusión más común: las calculadoras de "sistema francés"
  // suelen pedir TNA (tasa nominal), que se divide por 12 y da un número muy
  // distinto — ej. 96% TEA = 5,69% por 30 días, mientras 96% TNA = 8%.
  const tasaPeriodoHint = useMemo(() => {
    const tea = Number(formData.tasaInteres) || 0;
    if (tea <= 0) return "0 = sin interés (cuotas iguales)";
    const dias = Number(formData.intervaloDias) || 30;
    const tipo = formData.tipoInteres;
    if (tipo === "simple") {
      return `Recargo único de ${tea}% sobre el monto financiado (no depende del plazo).`;
    }
    const tasaPeriodo = (Math.pow(1 + tea / 100, dias / 365) - 1) * 100;
    const tnaEquiv = tasaPeriodo * (365 / dias);
    return `${tea}% TEA = ${tasaPeriodo.toFixed(2)}% por período de ${dias} días (≈ ${tnaEquiv.toFixed(2)}% TNA).`;
  }, [formData.tasaInteres, formData.intervaloDias, formData.tipoInteres]);

  // --- Query ---
  const { data: planesResponse, isLoading } = useQuery({
    queryKey: ["planes-cuotas-empresa"],
    queryFn: () => getPlanesEmpresa(),
    staleTime: 30 * 1000,
  });

  const planes = planesResponse?.data || [];

  // --- Mutations ---
  const crearMutation = useMutation({
    mutationFn: (datos) => crearPlan(datos),
    onSuccess: () => {
      toast.success("Plan de cuotas creado exitosamente");
      queryClient.invalidateQueries({ queryKey: ["planes-cuotas-empresa"] });
      handleCloseForm();
    },
    onError: (error) => {
      toast.error(
        error?.response?.data?.message || "Error al crear el plan de cuotas",
      );
    },
  });

  const actualizarMutation = useMutation({
    mutationFn: ({ id, datos }) => actualizarPlan(id, datos),
    onSuccess: () => {
      toast.success("Plan de cuotas actualizado exitosamente");
      queryClient.invalidateQueries({ queryKey: ["planes-cuotas-empresa"] });
      handleCloseForm();
    },
    onError: (error) => {
      toast.error(
        error?.response?.data?.message ||
          "Error al actualizar el plan de cuotas",
      );
    },
  });

  const eliminarMutation = useMutation({
    mutationFn: (id) => eliminarPlan(id),
    onSuccess: () => {
      toast.success("Plan de cuotas eliminado exitosamente");
      queryClient.invalidateQueries({ queryKey: ["planes-cuotas-empresa"] });
      setDeleteConfirm(null);
    },
    onError: (error) => {
      toast.error(
        error?.response?.data?.message || "Error al eliminar el plan de cuotas",
      );
    },
  });

  const toggleActivoMutation = useMutation({
    mutationFn: ({ id, activo }) => actualizarPlan(id, { activo }),
    onSuccess: (_, variables) => {
      toast.success(variables.activo ? "Plan activado" : "Plan desactivado");
      queryClient.invalidateQueries({ queryKey: ["planes-cuotas-empresa"] });
    },
    onError: (error) => {
      toast.error(
        error?.response?.data?.message || "Error al cambiar estado del plan",
      );
    },
  });

  const toggleDefaultMutation = useMutation({
    mutationFn: ({ id, esDefault }) => actualizarPlan(id, { esDefault }),
    onSuccess: () => {
      toast.success("Plan por defecto actualizado");
      queryClient.invalidateQueries({ queryKey: ["planes-cuotas-empresa"] });
    },
    onError: (error) => {
      toast.error(
        error?.response?.data?.message ||
          "Error al establecer plan por defecto",
      );
    },
  });

  const simularMutation = useMutation({
    mutationFn: (datos) => calcularCuotas(datos),
    onSuccess: (response) => {
      setSimuladorResultado(response?.data);
    },
    onError: (error) => {
      toast.error(error?.response?.data?.message || "Error al simular cuotas");
    },
  });

  // --- Handlers ---
  const handleOpenCreate = () => {
    setFormMode("create");
    setFormData(defaultFormData);
    setEditingPlan(null);
    setFormOpen(true);
  };

  const handleOpenEdit = (plan) => {
    setFormMode("edit");
    setEditingPlan(plan);
    setFormData({
      codigo: plan.codigo || "",
      nombre: plan.nombre || "",
      descripcion: plan.descripcion || "",
      tipoCalculo: plan.tipo_calculo || "automatico",
      cantidadCuotas: plan.cantidad_cuotas || 3,
      intervaloDias: plan.intervalo_dias || 30,
      tasaInteres: Number(plan.tasa_interes) || 0,
      tipoInteres: plan.tipo_interes || "simple",
      cuotaInicialRequerida: plan.cuota_inicial_requerida || false,
      cuotaInicialMinima: plan.cuota_inicial_minima?.toString() || "",
      montoMinimo: plan.monto_minimo?.toString() || "",
      montoMaximo: plan.monto_maximo?.toString() || "",
      categoriaId: plan.categoria_id || null,
      precioProductoDesde: plan.precio_producto_desde?.toString() || "",
      precioProductoHasta: plan.precio_producto_hasta?.toString() || "",
      activo: plan.activo ?? true,
      esDefault: plan.es_default || false,
    });
    setFormOpen(true);
  };

  const handleCloseForm = () => {
    setFormOpen(false);
    setFormData(defaultFormData);
    setEditingPlan(null);
  };

  const handleSubmit = () => {
    if (!formData.codigo.trim()) {
      toast.error("El código es requerido");
      return;
    }
    if (!formData.nombre.trim()) {
      toast.error("El nombre es requerido");
      return;
    }

    const datos = {
      nombre: formData.nombre.trim(),
      descripcion: formData.descripcion.trim() || undefined,
      tipoCalculo: formData.tipoCalculo,
      cantidadCuotas: Number(formData.cantidadCuotas) || undefined,
      intervaloDias: Number(formData.intervaloDias) || 30,
      tasaInteres: Number(formData.tasaInteres) || 0,
      tipoInteres: formData.tipoInteres,
      cuotaInicialRequerida: formData.cuotaInicialRequerida,
      cuotaInicialMinima: formData.cuotaInicialMinima
        ? Number(formData.cuotaInicialMinima)
        : undefined,
      montoMinimo: formData.montoMinimo
        ? Number(formData.montoMinimo)
        : undefined,
      montoMaximo: formData.montoMaximo
        ? Number(formData.montoMaximo)
        : undefined,
      categoriaId: formData.categoriaId || null,
      precioProductoDesde: formData.precioProductoDesde ? Number(formData.precioProductoDesde) : null,
      precioProductoHasta: formData.precioProductoHasta ? Number(formData.precioProductoHasta) : null,
      activo: formData.activo,
      esDefault: formData.esDefault,
    };

    if (formMode === "edit" && editingPlan) {
      actualizarMutation.mutate({ id: editingPlan.id, datos });
    } else {
      crearMutation.mutate({ ...datos, codigo: formData.codigo.trim() });
    }
  };

  const handleOpenSimulador = (plan) => {
    setSimuladorPlan(plan);
    setSimuladorMonto("");
    setSimuladorEntrada("");
    setSimuladorCuotas(plan.cantidad_cuotas || "");
    setSimuladorResultado(null);
    setSimuladorOpen(true);
  };

  const handleSimular = () => {
    if (!simuladorMonto || Number(simuladorMonto) <= 0) {
      toast.error("Ingresa un monto válido");
      return;
    }
    const maximoCuotas = simuladorPlan?.cantidad_cuotas || 1;
    if (simuladorCuotas && Number(simuladorCuotas) > maximoCuotas) {
      toast.error(`Este plan admite hasta ${maximoCuotas} cuotas`);
      return;
    }
    simularMutation.mutate({
      planCuotaId: simuladorPlan.id,
      montoTotal: Number(simuladorMonto),
      cuotaInicial: simuladorEntrada ? Number(simuladorEntrada) : undefined,
      cantidadCuotas:
        simuladorPlan?.tipo_calculo === "automatico" && simuladorCuotas
          ? Number(simuladorCuotas)
          : undefined,
    });
  };

  const handleChange = (field) => (e) => {
    const value =
      e.target.type === "checkbox" ? e.target.checked : e.target.value;
    setFormData((prev) => ({ ...prev, [field]: value }));
  };

  const isSaving = crearMutation.isPending || actualizarMutation.isPending;

  if (!canRead) {
    return (
      <AccesoRestringido mensaje="No tienes permisos para ver los planes de cuotas." />
    );
  }

  return (
    <Box>
      {/* Header */}
      <Box
        sx={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          mb: 3,
        }}
      >
        <Box>
          <Typography variant="h5" fontWeight={600}>
            Planes de Cuotas
          </Typography>
          <Typography variant="body2" color="text.secondary">
            Configura los planes de financiamiento disponibles para tus ventas
          </Typography>
        </Box>
        {canCreate && (
          <Button
            variant="contained"
            startIcon={<Add />}
            onClick={handleOpenCreate}
          >
            Nuevo Plan
          </Button>
        )}
      </Box>

      {/* Vista mobile: cards | Vista desktop: tabla */}
      {isMobile ? (
        <Stack spacing={1.5}>
          {isLoading ? (
            [...Array(3)].map((_, i) => (
              <Card key={i} variant="outlined" sx={{ borderRadius: 2 }}>
                <CardContent sx={{ p: "12px !important" }}>
                  <Skeleton variant="text" width="60%" />
                  <Skeleton variant="text" width="40%" />
                  <Skeleton variant="text" width="80%" />
                </CardContent>
              </Card>
            ))
          ) : planes.length === 0 ? (
            <Box sx={{ textAlign: "center", py: 6 }}>
              <Calculate
                sx={{ fontSize: 48, color: theme.palette.text.disabled, mb: 1 }}
              />
              <Typography variant="h6" color="text.secondary" gutterBottom>
                Sin planes de cuotas
              </Typography>
              <Typography variant="body2" color="text.secondary">
                Crea tu primer plan para ofrecer financiamiento en tus ventas.
              </Typography>
            </Box>
          ) : (
            planes.map((plan) => (
              <Card
                key={plan.id}
                variant="outlined"
                sx={{ borderRadius: 2, opacity: plan.activo ? 1 : 0.6 }}
              >
                <CardContent sx={{ p: "12px !important" }}>
                  {/* Fila: estrella + código + estado */}
                  <Box
                    sx={{
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "space-between",
                      mb: 0.5,
                    }}
                  >
                    <Box
                      sx={{
                        display: "flex",
                        alignItems: "center",
                        gap: 0.5,
                        minWidth: 0,
                      }}
                    >
                      <Tooltip
                        title={
                          plan.es_default
                            ? "Plan por defecto"
                            : "Marcar como plan por defecto"
                        }
                      >
                        <IconButton
                          size="small"
                          sx={{ p: 0.25 }}
                          onClick={() =>
                            toggleDefaultMutation.mutate({
                              id: plan.id,
                              esDefault: !plan.es_default,
                            })
                          }
                        >
                          {plan.es_default ? (
                            <Star
                              fontSize="small"
                              sx={{ color: theme.palette.warning.main }}
                            />
                          ) : (
                            <StarBorder fontSize="small" />
                          )}
                        </IconButton>
                      </Tooltip>
                      <Typography variant="subtitle2" fontWeight={600} noWrap>
                        {plan.codigo}
                      </Typography>
                    </Box>
                    <Box
                      sx={{
                        display: "flex",
                        gap: 0.5,
                        alignItems: "center",
                        flexShrink: 0,
                      }}
                    >
                      <Chip
                        label={plan.activo ? "Activo" : "Inactivo"}
                        size="small"
                        color={plan.activo ? "success" : "default"}
                        variant="outlined"
                        sx={{ fontSize: "0.65rem" }}
                      />
                    </Box>
                  </Box>
                  {/* Nombre */}
                  <Typography variant="body2">{plan.nombre}</Typography>
                  {plan.descripcion && (
                    <Typography
                      variant="caption"
                      color="text.secondary"
                      sx={{ display: "block" }}
                    >
                      {plan.descripcion}
                    </Typography>
                  )}
                  <Divider sx={{ my: 0.75 }} />
                  {/* Info: tipo + cuotas + interés */}
                  <Box
                    sx={{ display: "flex", gap: 1, flexWrap: "wrap", mb: 0.75 }}
                  >
                    <Chip
                      label={
                        TIPOS_CALCULO.find((t) => t.value === plan.tipo_calculo)
                          ?.label || plan.tipo_calculo
                      }
                      size="small"
                      color={
                        plan.tipo_calculo === "automatico"
                          ? "primary"
                          : plan.tipo_calculo === "manual"
                            ? "warning"
                            : "info"
                      }
                      variant="outlined"
                      sx={{ fontSize: "0.65rem" }}
                    />
                    <Chip
                      label={`${plan.cantidad_cuotas || "-"} cuotas`}
                      size="small"
                      variant="outlined"
                      sx={{ fontSize: "0.65rem" }}
                    />
                    <Chip
                      label={`c/ ${plan.intervalo_dias}d`}
                      size="small"
                      variant="outlined"
                      sx={{ fontSize: "0.65rem" }}
                    />
                    <Chip
                      label={
                        Number(plan.tasa_interes) > 0
                          ? `${Number(plan.tasa_interes)}% interés`
                          : "Sin interés"
                      }
                      size="small"
                      variant="outlined"
                      color={
                        Number(plan.tasa_interes) > 0 ? "warning" : "success"
                      }
                      sx={{ fontSize: "0.65rem" }}
                    />
                  </Box>
                  {/* Acciones */}
                  <Box
                    sx={{
                      display: "flex",
                      gap: 0.5,
                      justifyContent: "flex-end",
                      borderTop: "1px solid",
                      borderColor: "divider",
                      pt: 0.75,
                    }}
                  >
                    <Tooltip title="Simular cuotas">
                      <IconButton
                        size="small"
                        color="info"
                        onClick={() => handleOpenSimulador(plan)}
                      >
                        <Calculate fontSize="small" />
                      </IconButton>
                    </Tooltip>
                    {canEdit && (
                      <Tooltip title="Editar">
                        <IconButton
                          size="small"
                          color="warning"
                          onClick={() => handleOpenEdit(plan)}
                        >
                          <Edit fontSize="small" />
                        </IconButton>
                      </Tooltip>
                    )}
                    {canEdit && (
                      <Tooltip title={plan.activo ? "Desactivar" : "Activar"}>
                        <IconButton
                          size="small"
                          color={plan.activo ? "error" : "success"}
                          onClick={() =>
                            toggleActivoMutation.mutate({
                              id: plan.id,
                              activo: !plan.activo,
                            })
                          }
                        >
                          <PowerSettingsNew fontSize="small" />
                        </IconButton>
                      </Tooltip>
                    )}
                    {canDelete && (
                      <Tooltip title="Eliminar">
                        <IconButton
                          size="small"
                          color="error"
                          onClick={() => setDeleteConfirm(plan)}
                          disabled={plan._count?.cuotas_calculadas > 0}
                        >
                          <Delete fontSize="small" />
                        </IconButton>
                      </Tooltip>
                    )}
                  </Box>
                </CardContent>
              </Card>
            ))
          )}
        </Stack>
      ) : (
        /* Vista desktop: tabla */
        <TableContainer component={Paper} variant="outlined">
          <Table size="small">
            <TableHead>
              <TableRow>
                <TableCell>Código</TableCell>
                <TableCell>Nombre</TableCell>
                <TableCell>Tipo</TableCell>
                <TableCell align="center">Cuotas</TableCell>
                <TableCell align="center">Intervalo</TableCell>
                <TableCell align="center">Interés</TableCell>
                <TableCell align="center">Estado</TableCell>
                <TableCell align="center">Acciones</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {isLoading ? (
                [...Array(3)].map((_, i) => (
                  <TableRow key={i}>
                    {[...Array(8)].map((__, j) => (
                      <TableCell key={j}>
                        <Skeleton variant="text" />
                      </TableCell>
                    ))}
                  </TableRow>
                ))
              ) : planes.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={8} align="center" sx={{ py: 6 }}>
                    <Calculate
                      sx={{
                        fontSize: 48,
                        color: theme.palette.text.disabled,
                        mb: 1,
                      }}
                    />
                    <Typography
                      variant="h6"
                      color="text.secondary"
                      gutterBottom
                    >
                      Sin planes de cuotas
                    </Typography>
                    <Typography variant="body2" color="text.secondary">
                      Crea tu primer plan para ofrecer financiamiento en tus
                      ventas.
                    </Typography>
                  </TableCell>
                </TableRow>
              ) : (
                planes.map((plan) => (
                  <TableRow
                    key={plan.id}
                    sx={{
                      opacity: plan.activo ? 1 : 0.5,
                      "&:hover": {
                        backgroundColor: theme.palette.action.hover,
                      },
                    }}
                  >
                    <TableCell>
                      <Box
                        sx={{ display: "flex", alignItems: "center", gap: 1 }}
                      >
                        <Tooltip
                          title={
                            plan.es_default
                              ? "Plan por defecto"
                              : "Marcar como plan por defecto"
                          }
                        >
                          <IconButton
                            size="small"
                            onClick={() =>
                              toggleDefaultMutation.mutate({
                                id: plan.id,
                                esDefault: !plan.es_default,
                              })
                            }
                          >
                            {plan.es_default ? (
                              <Star
                                fontSize="small"
                                sx={{ color: theme.palette.warning.main }}
                              />
                            ) : (
                              <StarBorder fontSize="small" />
                            )}
                          </IconButton>
                        </Tooltip>
                        <Typography variant="body2" fontWeight={500}>
                          {plan.codigo}
                        </Typography>
                      </Box>
                    </TableCell>
                    <TableCell>
                      <Typography variant="body2">{plan.nombre}</Typography>
                      {plan.descripcion && (
                        <Typography variant="caption" color="text.secondary">
                          {plan.descripcion}
                        </Typography>
                      )}
                    </TableCell>
                    <TableCell>
                      <Chip
                        label={
                          TIPOS_CALCULO.find(
                            (t) => t.value === plan.tipo_calculo,
                          )?.label || plan.tipo_calculo
                        }
                        size="small"
                        color={
                          plan.tipo_calculo === "automatico"
                            ? "primary"
                            : plan.tipo_calculo === "manual"
                              ? "warning"
                              : "info"
                        }
                        variant="outlined"
                        sx={{ fontSize: "0.7rem" }}
                      />
                    </TableCell>
                    <TableCell align="center">
                      <Typography variant="body2">
                        {plan.cantidad_cuotas || "-"}
                      </Typography>
                    </TableCell>
                    <TableCell align="center">
                      <Typography variant="body2">
                        {plan.intervalo_dias} días
                      </Typography>
                    </TableCell>
                    <TableCell align="center">
                      <Typography
                        variant="body2"
                        color={
                          Number(plan.tasa_interes) > 0
                            ? "warning.main"
                            : "success.main"
                        }
                        fontWeight={500}
                      >
                        {Number(plan.tasa_interes) > 0
                          ? `${Number(plan.tasa_interes)}%`
                          : "Sin interés"}
                      </Typography>
                    </TableCell>
                    <TableCell align="center">
                      <Chip
                        label={plan.activo ? "Activo" : "Inactivo"}
                        size="small"
                        color={plan.activo ? "success" : "default"}
                        variant="outlined"
                        sx={{ fontSize: "0.65rem" }}
                      />
                    </TableCell>
                    <TableCell align="center">
                      <Box
                        sx={{
                          display: "flex",
                          gap: 0.5,
                          justifyContent: "center",
                        }}
                      >
                        <Tooltip title="Simular cuotas">
                          <IconButton
                            size="small"
                            color="info"
                            onClick={() => handleOpenSimulador(plan)}
                          >
                            <Calculate fontSize="small" />
                          </IconButton>
                        </Tooltip>
                        {canEdit && (
                          <Tooltip title="Editar">
                            <IconButton
                              size="small"
                              color="warning"
                              onClick={() => handleOpenEdit(plan)}
                            >
                              <Edit fontSize="small" />
                            </IconButton>
                          </Tooltip>
                        )}
                        {canEdit && (
                          <Tooltip
                            title={plan.activo ? "Desactivar" : "Activar"}
                          >
                            <IconButton
                              size="small"
                              color={plan.activo ? "error" : "success"}
                              onClick={() =>
                                toggleActivoMutation.mutate({
                                  id: plan.id,
                                  activo: !plan.activo,
                                })
                              }
                            >
                              <PowerSettingsNew fontSize="small" />
                            </IconButton>
                          </Tooltip>
                        )}
                        {canDelete && (
                          <Tooltip title="Eliminar">
                            <IconButton
                              size="small"
                              color="error"
                              onClick={() => setDeleteConfirm(plan)}
                              disabled={plan._count?.cuotas_calculadas > 0}
                            >
                              <Delete fontSize="small" />
                            </IconButton>
                          </Tooltip>
                        )}
                      </Box>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </TableContainer>
      )}

      {/* Dialog Crear/Editar */}
      <Dialog open={formOpen} onClose={handleCloseForm} maxWidth="sm" fullWidth>
        <DialogTitle>
          {formMode === "create"
            ? "Nuevo Plan de Cuotas"
            : "Editar Plan de Cuotas"}
        </DialogTitle>
        <DialogContent>
          <Box
            sx={{
              display: "grid",
              gridTemplateColumns: "1fr 1fr",
              gap: 2,
              mt: 1,
            }}
          >
            {/* Datos básicos */}
            <Typography
              variant="caption"
              color="text.secondary"
              fontWeight={600}
              sx={{
                gridColumn: "1 / -1",
                textTransform: "uppercase",
                letterSpacing: 0.5,
              }}
            >
              Datos del plan
            </Typography>
            <TextField
              size="small"
              label="Código *"
              value={formData.codigo}
              onChange={handleChange("codigo")}
              inputProps={{ maxLength: 20 }}
              disabled={formMode === "edit"}
              helperText="Identificador único, ej: CUOTA-3, SIN-INT-6"
            />
            <TextField
              size="small"
              label="Nombre *"
              value={formData.nombre}
              onChange={handleChange("nombre")}
              inputProps={{ maxLength: 100 }}
              helperText="Nombre visible para el vendedor"
            />
            <TextField
              size="small"
              label="Descripción"
              value={formData.descripcion}
              onChange={handleChange("descripcion")}
              multiline
              rows={2}
              sx={{ gridColumn: "1 / -1" }}
              helperText="Opcional — descripción interna del plan"
            />
            <Divider sx={{ gridColumn: "1 / -1", my: 0.5 }} />
            {/* Configuración de cuotas */}
            <Typography
              variant="caption"
              color="text.secondary"
              fontWeight={600}
              sx={{
                gridColumn: "1 / -1",
                textTransform: "uppercase",
                letterSpacing: 0.5,
              }}
            >
              Configuración de cuotas
            </Typography>
            <FormControl size="small">
              <InputLabel>Tipo de Cálculo</InputLabel>
              <Select
                value={formData.tipoCalculo}
                onChange={handleChange("tipoCalculo")}
                label="Tipo de Cálculo"
              >
                {TIPOS_CALCULO.map((t) => (
                  <MenuItem key={t.value} value={t.value}>
                    <Box>
                      <Typography variant="body2">{t.label}</Typography>
                      <Typography variant="caption" color="text.secondary">
                        {t.desc}
                      </Typography>
                    </Box>
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
            <TextField
              size="small"
              label="Cantidad máxima de Cuotas"
              type="number"
              value={formData.cantidadCuotas}
              onChange={handleChange("cantidadCuotas")}
              inputProps={{ min: 1, max: 60 }}
              helperText={
                formData.tipoCalculo === "automatico"
                  ? "Al facturar se puede elegir esta cantidad o menos (ej. plan de hasta 12 permite 3, 6 o 12)"
                  : "Número total de cuotas del plan"
              }
              disabled={formData.tipoCalculo === "manual"}
            />
            <Alert
              severity="info"
              variant="outlined"
              sx={{
                gridColumn: "1 / -1",
                py: 0,
                "& .MuiAlert-message": { py: 0.5 },
              }}
            >
              <Typography variant="caption">
                {getCalcHelperText(formData.tipoCalculo)}
              </Typography>
            </Alert>
            <TextField
              size="small"
              label="Intervalo entre cuotas (días)"
              type="number"
              value={formData.intervaloDias}
              onChange={handleChange("intervaloDias")}
              inputProps={{ min: 1, max: 365 }}
              helperText="30 = mensual, 15 = quincenal, 7 = semanal"
            />
            <Box /> {/* spacer */}
            <Divider sx={{ gridColumn: "1 / -1", my: 0.5 }} />
            {/* Interés */}
            <Typography
              variant="caption"
              color="text.secondary"
              fontWeight={600}
              sx={{
                gridColumn: "1 / -1",
                textTransform: "uppercase",
                letterSpacing: 0.5,
              }}
            >
              Interés
            </Typography>
            <TextField
              size="small"
              label="Tasa Efectiva Anual — TEA (%)"
              type="number"
              value={formData.tasaInteres}
              onChange={handleChange("tasaInteres")}
              inputProps={{ min: 0, max: 1000, step: 0.01 }}
              helperText={tasaPeriodoHint}
            />
            <FormControl size="small">
              <InputLabel>Tipo de Interés</InputLabel>
              <Select
                value={formData.tipoInteres}
                onChange={handleChange("tipoInteres")}
                label="Tipo de Interés"
                disabled={Number(formData.tasaInteres) === 0}
              >
                {TIPOS_INTERES.map((t) => (
                  <MenuItem key={t.value} value={t.value}>
                    <Box>
                      <Typography variant="body2">{t.label}</Typography>
                      <Typography variant="caption" color="text.secondary">
                        {t.desc}
                      </Typography>
                    </Box>
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
            {Number(formData.tasaInteres) > 0 && (
              <Alert
                severity="warning"
                variant="outlined"
                sx={{
                  gridColumn: "1 / -1",
                  py: 0,
                  "& .MuiAlert-message": { py: 0.5 },
                }}
              >
                <Typography variant="caption">
                  {getInteresHelperText(formData.tipoInteres)}
                </Typography>
              </Alert>
            )}
            <Divider sx={{ gridColumn: "1 / -1", my: 0.5 }} />
            {/* Límites */}
            <Typography
              variant="caption"
              color="text.secondary"
              fontWeight={600}
              sx={{
                gridColumn: "1 / -1",
                textTransform: "uppercase",
                letterSpacing: 0.5,
              }}
            >
              Límites (opcional)
            </Typography>
            <MonedaInput
              size="small"
              label="Monto Mínimo"
              value={Number(formData.montoMinimo) || 0}
              onChange={(v) => setFormData((prev) => ({ ...prev, montoMinimo: v || "" }))}
              helperText="Monto mínimo de venta para usar este plan (0 = sin mínimo)"
              fullWidth
            />
            <MonedaInput
              size="small"
              label="Monto Máximo"
              value={Number(formData.montoMaximo) || 0}
              onChange={(v) => setFormData((prev) => ({ ...prev, montoMaximo: v || "" }))}
              helperText="Monto máximo de venta para usar este plan (0 = sin máximo)"
              fullWidth
            />
            <Box sx={{ gridColumn: "1 / -1" }}>
              <CategoriaAutocomplete
                value={formData.categoriaId}
                onChange={(categoriaId) => setFormData((prev) => ({ ...prev, categoriaId }))}
                allowGlobalLabel="Cualquier categoría"
              />
            </Box>
            <MonedaInput
              size="small"
              label="Precio de producto desde"
              value={Number(formData.precioProductoDesde) || 0}
              onChange={(v) => setFormData((prev) => ({ ...prev, precioProductoDesde: v || "" }))}
              helperText="Precio de catálogo del producto (no el monto de la venta) desde el cual este plan se ofrece"
              fullWidth
            />
            <MonedaInput
              size="small"
              label="Precio de producto hasta"
              value={Number(formData.precioProductoHasta) || 0}
              onChange={(v) => setFormData((prev) => ({ ...prev, precioProductoHasta: v || "" }))}
              helperText="Vacío = sin tope superior"
              fullWidth
            />
            <Box sx={{ gridColumn: "1 / -1" }}>
              <FormControlLabel
                control={
                  <Switch
                    checked={formData.cuotaInicialRequerida}
                    onChange={handleChange("cuotaInicialRequerida")}
                  />
                }
                label="Requiere cuota inicial (entrada)"
              />
              <Typography
                variant="caption"
                color="text.secondary"
                sx={{ display: "block", ml: 6 }}
              >
                Si se activa, el cliente debe pagar un porcentaje al momento de
                la compra
              </Typography>
            </Box>
            {formData.cuotaInicialRequerida && (
              <TextField
                size="small"
                label="% Mínimo de Entrada"
                type="number"
                value={formData.cuotaInicialMinima}
                onChange={handleChange("cuotaInicialMinima")}
                inputProps={{ min: 0, max: 100, step: 0.01 }}
                sx={{ gridColumn: "1 / -1" }}
                helperText="Porcentaje mínimo del total que el cliente debe pagar como entrada"
              />
            )}
            <Divider sx={{ gridColumn: "1 / -1", my: 0.5 }} />
            <Box sx={{ gridColumn: "1 / -1", display: "flex", gap: 2 }}>
              <FormControlLabel
                control={
                  <Switch
                    checked={formData.activo}
                    onChange={handleChange("activo")}
                  />
                }
                label="Activo"
              />
              <FormControlLabel
                control={
                  <Switch
                    checked={formData.esDefault}
                    onChange={handleChange("esDefault")}
                  />
                }
                label="Plan por defecto"
              />
            </Box>
            <Typography
              variant="caption"
              color="text.secondary"
              sx={{ gridColumn: "1 / -1", mt: -1 }}
            >
              El plan por defecto se selecciona automáticamente al ofrecer
              financiamiento en ventas
            </Typography>
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseForm} disabled={isSaving}>
            Cancelar
          </Button>
          <Button
            variant="contained"
            onClick={handleSubmit}
            disabled={isSaving}
          >
            {isSaving
              ? "Guardando..."
              : formMode === "create"
                ? "Crear Plan"
                : "Guardar Cambios"}
          </Button>
        </DialogActions>
      </Dialog>

      {/* Dialog Confirmar Eliminar */}
      <Dialog
        open={!!deleteConfirm}
        onClose={() => setDeleteConfirm(null)}
        maxWidth="xs"
        fullWidth
      >
        <DialogTitle>Eliminar Plan de Cuotas</DialogTitle>
        <DialogContent>
          <DialogContentText>
            ¿Estás seguro de eliminar el plan{" "}
            <strong>&quot;{deleteConfirm?.nombre}&quot;</strong>? Esta acción no
            se puede deshacer.
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button
            onClick={() => setDeleteConfirm(null)}
            disabled={eliminarMutation.isPending}
          >
            Cancelar
          </Button>
          <Button
            variant="contained"
            color="error"
            onClick={() => eliminarMutation.mutate(deleteConfirm?.id)}
            disabled={eliminarMutation.isPending}
          >
            {eliminarMutation.isPending ? "Eliminando..." : "Eliminar"}
          </Button>
        </DialogActions>
      </Dialog>

      {/* Dialog Simulador de Cuotas */}
      <Dialog
        open={simuladorOpen}
        onClose={() => {
          setSimuladorOpen(false);
          setSimuladorResultado(null);
        }}
        maxWidth="sm"
        fullWidth
      >
        <DialogTitle>Simulador de Cuotas — {simuladorPlan?.nombre}</DialogTitle>
        <DialogContent>
          <Box sx={{ display: "flex", gap: 2, mt: 1, mb: 2 }}>
            <MonedaInput
              size="small"
              label="Monto Total *"
              value={Number(simuladorMonto) || 0}
              onChange={(v) => setSimuladorMonto(v || "")}
              fullWidth
            />
            {simuladorPlan?.tipo_calculo === "automatico" && (
              <TextField
                size="small"
                label="Cuotas"
                type="number"
                value={simuladorCuotas}
                onChange={(e) => setSimuladorCuotas(e.target.value)}
                inputProps={{ min: 1, max: simuladorPlan?.cantidad_cuotas || 60 }}
                helperText={`Máx. ${simuladorPlan?.cantidad_cuotas}`}
                sx={{ minWidth: 110 }}
              />
            )}
            {simuladorPlan?.cuota_inicial_requerida && (
              <MonedaInput
                size="small"
                label="Cuota Inicial"
                value={Number(simuladorEntrada) || 0}
                onChange={(v) => setSimuladorEntrada(v || "")}
                fullWidth
              />
            )}
            <Button
              variant="contained"
              onClick={handleSimular}
              disabled={simularMutation.isPending}
              sx={{ minWidth: 120 }}
            >
              {simularMutation.isPending ? "Calculando..." : "Simular"}
            </Button>
          </Box>

          {/* Info del plan */}
          <Box
            sx={{
              p: 1.5,
              borderRadius: 1,
              backgroundColor: theme.palette.action.hover,
              mb: 2,
            }}
          >
            <Typography variant="caption" color="text.secondary">
              hasta {simuladorPlan?.cantidad_cuotas} cuotas · Cada{" "}
              {simuladorPlan?.intervalo_dias} días · Interés:{" "}
              {Number(simuladorPlan?.tasa_interes) > 0
                ? `${Number(simuladorPlan?.tasa_interes)}% (${simuladorPlan?.tipo_interes})`
                : "Sin interés"}
            </Typography>
          </Box>

          {/* Resultado */}
          {simuladorResultado && (
            <Box>
              <Typography variant="subtitle2" fontWeight={600} gutterBottom>
                Resultado de la simulación
              </Typography>

              {simuladorResultado.cuota_inicial > 0 && (
                <Box
                  sx={{
                    p: 1.5,
                    mb: 1,
                    borderRadius: 1,
                    border: `1px solid ${theme.palette.divider}`,
                  }}
                >
                  <Typography variant="body2">
                    Cuota Inicial:{" "}
                    <strong>
                      {formatNumber(simuladorResultado.cuota_inicial)}
                    </strong>
                  </Typography>
                </Box>
              )}

              {(() => {
                const detalle = simuladorResultado.cuotas_calculadas_detalle || [];
                const tieneDesglose = detalle.some((c) => c.capital != null);
                return (
              <Table size="small">
                <TableHead>
                  <TableRow>
                    <TableCell>#</TableCell>
                    {tieneDesglose && (
                      <>
                        <TableCell align="right">Capital</TableCell>
                        <TableCell align="right">+ Interés</TableCell>
                      </>
                    )}
                    <TableCell align="right">{tieneDesglose ? "= Monto Cuota" : "Monto"}</TableCell>
                    <TableCell>Vencimiento</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {detalle.map(
                    (cuota) => (
                      <TableRow key={cuota.numero_cuota}>
                        <TableCell>{cuota.numero_cuota}</TableCell>
                        {cuota.capital != null && (
                          <>
                            <TableCell align="right">
                              <Typography variant="body2" color="text.secondary">
                                {formatNumber(cuota.capital)}
                              </Typography>
                            </TableCell>
                            <TableCell align="right">
                              <Typography variant="body2" color="warning.main">
                                {formatNumber(cuota.interes)}
                              </Typography>
                            </TableCell>
                          </>
                        )}
                        <TableCell align="right">
                          <Typography variant="body2" fontWeight={700}>
                            {formatNumber(cuota.monto_cuota)}
                          </Typography>
                        </TableCell>
                        <TableCell>
                          <Typography variant="body2" color="text.secondary">
                            {cuota.fecha_vencimiento
                              ? new Date(
                                  cuota.fecha_vencimiento,
                                ).toLocaleDateString("es-PY")
                              : "-"}
                          </Typography>
                        </TableCell>
                      </TableRow>
                    ),
                  )}
                </TableBody>
              </Table>
                );
              })()}

              <Box
                sx={{
                  mt: 2,
                  p: 1.5,
                  borderRadius: 1,
                  backgroundColor: theme.palette.action.hover,
                  display: "flex",
                  justifyContent: "space-between",
                  flexWrap: "wrap",
                  gap: 1,
                }}
              >
                <Typography variant="body2">
                  Financiado:{" "}
                  <strong>
                    {formatNumber(simuladorResultado.monto_total)}
                  </strong>
                </Typography>
                {(simuladorResultado.cuotas_calculadas_detalle || []).some(
                  (c) => c.interes != null,
                ) && (
                  <>
                    <Typography variant="body2">
                      Total a pagar:{" "}
                      <strong>
                        {formatNumber(
                          (simuladorResultado.cuotas_calculadas_detalle || []).reduce(
                            (s, c) => s + Number(c.monto_cuota || 0),
                            0,
                          ),
                        )}
                      </strong>
                    </Typography>
                    <Typography variant="body2" color="warning.main">
                      Interés total:{" "}
                      <strong>
                        {formatNumber(
                          (simuladorResultado.cuotas_calculadas_detalle || []).reduce(
                            (s, c) => s + Number(c.interes || 0),
                            0,
                          ),
                        )}
                      </strong>
                    </Typography>
                  </>
                )}
                <Typography variant="body2">
                  Cuotas: <strong>{simuladorResultado.cantidad_cuotas}</strong>
                </Typography>
              </Box>
            </Box>
          )}
        </DialogContent>
        <DialogActions>
          <Button
            onClick={() => {
              setSimuladorOpen(false);
              setSimuladorResultado(null);
            }}
          >
            Cerrar
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
}
