import {
  Add,
  AttachMoney,
  Delete,
  Edit,
  History,
  Star,
  StarBorder,
} from "@mui/icons-material";
import {
  Autocomplete,
  Box,
  Button,
  Card,
  CardContent,
  Chip,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Divider,
  IconButton,
  Paper,
  Stack,
  Tab,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Tabs,
  TextField,
  Tooltip,
  Typography,
  useMediaQuery,
  useTheme,
} from "@mui/material";
import { useState } from "react";
import { toast } from "sonner";
import { hoyISO } from "../../utils/fecha";
import { usePermission } from "../../hooks/usePermission";
import {
  useAddEmpresaMonedaMutation,
  useCotizacionesQuery,
  useCreateCotizacionMutation,
  useDeleteCotizacionMutation,
  useEmpresaMonedasQuery,
  useMonedasQuery,
  useRemoveEmpresaMonedaMutation,
  useUpdateEmpresaMonedaMutation,
} from "../../tanstack/MonedasStack";

export function MonedasConfigTab() {
  const [subTab, setSubTab] = useState(0);

  return (
    <Box sx={{ height: "100%" }}>
      <Paper sx={{ mb: 2 }}>
        {/* Tabs scrollables en mobile */}
        <Tabs
          value={subTab}
          onChange={(_, v) => setSubTab(v)}
          variant="scrollable"
          scrollButtons="auto"
          allowScrollButtonsMobile
          sx={{ borderBottom: 1, borderColor: "divider" }}
        >
          <Tab
            icon={<AttachMoney />}
            iconPosition="start"
            label="Monedas"
            sx={{
              fontSize: { xs: "0.75rem", sm: "0.875rem" },
              minWidth: { xs: 100, sm: 160 },
            }}
          />
          <Tab
            icon={<History />}
            iconPosition="start"
            label="Cotizaciones"
            sx={{
              fontSize: { xs: "0.75rem", sm: "0.875rem" },
              minWidth: { xs: 100, sm: 160 },
            }}
          />
        </Tabs>
      </Paper>

      {subTab === 0 && <EmpresaMonedasSection />}
      {subTab === 1 && <CotizacionesSection />}
    </Box>
  );
}

function EmpresaMonedasSection() {
  const muiTheme = useTheme();
  const isMobile = useMediaQuery(muiTheme.breakpoints.down("sm"));
  const { data: empresaMonedas = [], isLoading } = useEmpresaMonedasQuery();
  const { data: todasMonedas = [] } = useMonedasQuery();
  const addMutation = useAddEmpresaMonedaMutation();
  const updateMutation = useUpdateEmpresaMonedaMutation();
  const removeMutation = useRemoveEmpresaMonedaMutation();

  const [addDialogOpen, setAddDialogOpen] = useState(false);
  const [editDialogOpen, setEditDialogOpen] = useState(false);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [selectedMoneda, setSelectedMoneda] = useState(null);
  const [selectedEmpresaMoneda, setSelectedEmpresaMoneda] = useState(null);
  const [decimalesVisualizar, setDecimalesVisualizar] = useState(0);

  // Filtrar monedas que no están asignadas
  const monedasDisponibles = todasMonedas.filter(
    (m) => !empresaMonedas.some((em) => em.moneda_id === m.id),
  );

  const handleAdd = () => {
    if (!selectedMoneda) {
      toast.error("Seleccione una moneda");
      return;
    }
    addMutation.mutate(
      {
        moneda_id: selectedMoneda.id,
        decimales_visualizar: decimalesVisualizar,
        es_principal: empresaMonedas.length === 0,
      },
      {
        onSuccess: () => {
          setAddDialogOpen(false);
          setSelectedMoneda(null);
          setDecimalesVisualizar(0);
        },
      },
    );
  };

  const handleOpenEdit = (em) => {
    setSelectedEmpresaMoneda(em);
    setDecimalesVisualizar(em.decimales_visualizar || 0);
    setEditDialogOpen(true);
  };

  const handleUpdate = () => {
    updateMutation.mutate(
      {
        id: selectedEmpresaMoneda.id,
        data: { decimales_visualizar: decimalesVisualizar },
      },
      {
        onSuccess: () => {
          setEditDialogOpen(false);
          setSelectedEmpresaMoneda(null);
        },
      },
    );
  };

  const handleSetPrincipal = (em) => {
    updateMutation.mutate({
      id: em.id,
      data: { es_principal: true },
    });
  };

  const handleOpenDelete = (em) => {
    setSelectedEmpresaMoneda(em);
    setDeleteDialogOpen(true);
  };

  const handleDelete = () => {
    removeMutation.mutate(selectedEmpresaMoneda.id, {
      onSuccess: () => {
        setDeleteDialogOpen(false);
        setSelectedEmpresaMoneda(null);
      },
    });
  };

  return (
    <Paper sx={{ p: 2 }}>
      <Box
        sx={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          mb: 2,
          gap: 1,
        }}
      >
        <Box>
          <Typography
            variant="h6"
            sx={{ fontSize: { xs: "1rem", sm: "1.25rem" } }}
          >
            Monedas Configuradas
          </Typography>
          <Typography
            variant="body2"
            color="text.secondary"
            sx={{ fontSize: { xs: "0.75rem", sm: "0.875rem" } }}
          >
            Configure las monedas que utilizará su empresa para facturación
          </Typography>
        </Box>
        <Button
          variant="contained"
          startIcon={<Add />}
          onClick={() => setAddDialogOpen(true)}
          disabled={monedasDisponibles.length === 0}
          size={isMobile ? "small" : "medium"}
          sx={{ flexShrink: 0 }}
        >
          {isMobile ? "Agregar" : "Agregar Moneda"}
        </Button>
      </Box>

      {/* Vista mobile: cards | Vista desktop: tabla */}
      {isMobile ? (
        <Stack spacing={1.5}>
          {isLoading ? (
            <Typography color="text.secondary" textAlign="center" py={2}>
              Cargando...
            </Typography>
          ) : empresaMonedas.length === 0 ? (
            <Typography color="text.secondary" textAlign="center" py={2}>
              No hay monedas configuradas. Agregue al menos una moneda para
              comenzar.
            </Typography>
          ) : (
            empresaMonedas.map((em) => (
              <Card key={em.id} variant="outlined" sx={{ borderRadius: 2 }}>
                <CardContent sx={{ p: "12px !important" }}>
                  <Box
                    sx={{
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "space-between",
                      mb: 0.75,
                    }}
                  >
                    <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
                      <Chip
                        label={em.moneda?.codigo}
                        size="small"
                        color="primary"
                        variant="outlined"
                      />
                      <Typography variant="subtitle2" fontWeight={600}>
                        {em.moneda?.simbolo || "-"}
                      </Typography>
                    </Box>
                    {em.es_principal ? (
                      <Chip
                        icon={<Star />}
                        label="Principal"
                        size="small"
                        color="warning"
                      />
                    ) : (
                      <Tooltip title="Marcar como principal">
                        <IconButton
                          size="small"
                          onClick={() => handleSetPrincipal(em)}
                        >
                          <StarBorder fontSize="small" />
                        </IconButton>
                      </Tooltip>
                    )}
                  </Box>
                  <Typography
                    variant="caption"
                    color="text.secondary"
                    sx={{ display: "block" }}
                  >
                    {em.moneda?.descripcion}
                  </Typography>
                  <Typography
                    variant="caption"
                    color="text.secondary"
                    sx={{ display: "block", mb: 0.5 }}
                  >
                    Decimales: {em.decimales_visualizar}
                  </Typography>
                  <Box
                    sx={{
                      display: "flex",
                      gap: 0.5,
                      justifyContent: "flex-end",
                      borderTop: "1px solid",
                      borderColor: "divider",
                      pt: 1,
                      mt: 0.5,
                    }}
                  >
                    <Tooltip title="Editar decimales">
                      <IconButton
                        size="small"
                        onClick={() => handleOpenEdit(em)}
                        color="warning"
                      >
                        <Edit fontSize="small" />
                      </IconButton>
                    </Tooltip>
                    {!em.es_principal && (
                      <Tooltip title="Eliminar">
                        <IconButton
                          size="small"
                          onClick={() => handleOpenDelete(em)}
                          color="error"
                        >
                          <Delete fontSize="small" />
                        </IconButton>
                      </Tooltip>
                    )}
                  </Box>
                </CardContent>
              </Card>
            ))
          )}
        </Stack>
      ) : (
        <TableContainer>
          <Table size="small">
            <TableHead>
              <TableRow>
                <TableCell>Código</TableCell>
                <TableCell>Descripción</TableCell>
                <TableCell>Símbolo</TableCell>
                <TableCell align="center">Decimales a Mostrar</TableCell>
                <TableCell align="center">Principal</TableCell>
                <TableCell align="right">Acciones</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {isLoading ? (
                <TableRow>
                  <TableCell colSpan={6} align="center">
                    Cargando...
                  </TableCell>
                </TableRow>
              ) : empresaMonedas.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={6} align="center">
                    <Typography color="text.secondary" sx={{ py: 2 }}>
                      No hay monedas configuradas. Agregue al menos una moneda
                      para comenzar.
                    </Typography>
                  </TableCell>
                </TableRow>
              ) : (
                empresaMonedas.map((em) => (
                  <TableRow key={em.id} hover>
                    <TableCell>
                      <Chip
                        label={em.moneda?.codigo}
                        size="small"
                        color="primary"
                        variant="outlined"
                      />
                    </TableCell>
                    <TableCell>{em.moneda?.descripcion}</TableCell>
                    <TableCell>
                      <Typography variant="h6" sx={{ fontWeight: 600 }}>
                        {em.moneda?.simbolo || "-"}
                      </Typography>
                    </TableCell>
                    <TableCell align="center">
                      <Chip
                        label={em.decimales_visualizar}
                        size="small"
                        variant="outlined"
                      />
                    </TableCell>
                    <TableCell align="center">
                      {em.es_principal ? (
                        <Chip
                          icon={<Star />}
                          label="Principal"
                          size="small"
                          color="warning"
                        />
                      ) : (
                        <Tooltip title="Marcar como principal">
                          <IconButton
                            size="small"
                            onClick={() => handleSetPrincipal(em)}
                          >
                            <StarBorder />
                          </IconButton>
                        </Tooltip>
                      )}
                    </TableCell>
                    <TableCell align="right">
                      <Tooltip title="Editar decimales">
                        <IconButton
                          size="small"
                          onClick={() => handleOpenEdit(em)}
                          color="warning"
                        >
                          <Edit fontSize="small" />
                        </IconButton>
                      </Tooltip>
                      {!em.es_principal && (
                        <Tooltip title="Eliminar">
                          <IconButton
                            size="small"
                            onClick={() => handleOpenDelete(em)}
                            color="error"
                          >
                            <Delete fontSize="small" />
                          </IconButton>
                        </Tooltip>
                      )}
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </TableContainer>
      )}

      {/* Dialog Agregar Moneda */}
      <Dialog
        open={addDialogOpen}
        onClose={() => setAddDialogOpen(false)}
        maxWidth="sm"
        fullWidth
      >
        <DialogTitle>Agregar Moneda</DialogTitle>
        <DialogContent>
          <Box sx={{ display: "flex", flexDirection: "column", gap: 2, mt: 1 }}>
            <Autocomplete
              options={monedasDisponibles}
              getOptionLabel={(opt) =>
                `${opt.codigo} - ${opt.descripcion} (${opt.simbolo || ""})`
              }
              value={selectedMoneda}
              onChange={(_, v) => setSelectedMoneda(v)}
              renderInput={(params) => (
                <TextField
                  {...params}
                  label="Seleccionar Moneda"
                  size="small"
                />
              )}
            />
            <TextField
              label="Decimales a Visualizar"
              type="number"
              size="small"
              value={decimalesVisualizar}
              onChange={(e) =>
                setDecimalesVisualizar(
                  Math.max(0, Math.min(6, parseInt(e.target.value) || 0)),
                )
              }
              inputProps={{ min: 0, max: 6 }}
              helperText="Cantidad de decimales a mostrar en la UI (0-6)"
            />
          </Box>
        </DialogContent>
        <DialogActions sx={{ p: 2 }}>
          <Button onClick={() => setAddDialogOpen(false)}>Cancelar</Button>
          <Button
            variant="contained"
            onClick={handleAdd}
            disabled={addMutation.isPending}
          >
            {addMutation.isPending ? "Agregando..." : "Agregar"}
          </Button>
        </DialogActions>
      </Dialog>

      {/* Dialog Editar Decimales */}
      <Dialog
        open={editDialogOpen}
        onClose={() => setEditDialogOpen(false)}
        maxWidth="xs"
        fullWidth
      >
        <DialogTitle>
          Editar Configuración - {selectedEmpresaMoneda?.moneda?.codigo}
        </DialogTitle>
        <DialogContent>
          <TextField
            fullWidth
            label="Decimales a Visualizar"
            type="number"
            size="small"
            value={decimalesVisualizar}
            onChange={(e) =>
              setDecimalesVisualizar(
                Math.max(0, Math.min(6, parseInt(e.target.value) || 0)),
              )
            }
            inputProps={{ min: 0, max: 6 }}
            sx={{ mt: 2 }}
            helperText="Cantidad de decimales a mostrar en la UI (0-6)"
          />
        </DialogContent>
        <DialogActions sx={{ p: 2 }}>
          <Button onClick={() => setEditDialogOpen(false)}>Cancelar</Button>
          <Button
            variant="contained"
            onClick={handleUpdate}
            disabled={updateMutation.isPending}
          >
            {updateMutation.isPending ? "Guardando..." : "Guardar"}
          </Button>
        </DialogActions>
      </Dialog>

      {/* Dialog Confirmar Eliminación */}
      <Dialog
        open={deleteDialogOpen}
        onClose={() => setDeleteDialogOpen(false)}
        maxWidth="xs"
        fullWidth
      >
        <DialogTitle>Confirmar Eliminación</DialogTitle>
        <DialogContent>
          <Typography>
            ¿Está seguro de eliminar la moneda{" "}
            <strong>
              {selectedEmpresaMoneda?.moneda?.codigo} -{" "}
              {selectedEmpresaMoneda?.moneda?.descripcion}
            </strong>{" "}
            de la configuración de su empresa?
          </Typography>
        </DialogContent>
        <DialogActions sx={{ p: 2 }}>
          <Button onClick={() => setDeleteDialogOpen(false)} variant="outlined">
            Cancelar
          </Button>
          <Button
            variant="contained"
            color="error"
            onClick={handleDelete}
            disabled={removeMutation.isPending}
          >
            {removeMutation.isPending ? "Eliminando..." : "Eliminar"}
          </Button>
        </DialogActions>
      </Dialog>
    </Paper>
  );
}

function CotizacionesSection() {
  // Registrar, editar o eliminar cotizaciones pide ADM_COTIZ_REGISTRAR (el
  // backend lo exige); verlas, no.
  const { can } = usePermission("ADMINISTRACION");
  const puedeRegistrar = can("ADM_COTIZ_REGISTRAR");
  const muiTheme = useTheme();
  const isMobile = useMediaQuery(muiTheme.breakpoints.down("sm"));
  const { data: empresaMonedas = [] } = useEmpresaMonedasQuery();
  const [selectedMonedaId, setSelectedMonedaId] = useState(null);
  const { data: cotizaciones = [], isLoading } = useCotizacionesQuery(
    selectedMonedaId,
    50,
  );
  const createMutation = useCreateCotizacionMutation();
  const deleteMutation = useDeleteCotizacionMutation();

  const [formDialogOpen, setFormDialogOpen] = useState(false);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [cotizacionToDelete, setCotizacionToDelete] = useState(null);
  const [formData, setFormData] = useState({
    moneda_id: "",
    fecha: hoyISO(),
    cotizacion_compra: "",
    cotizacion_venta: "",
  });

  // Filtrar monedas que no son PYG (guaraní no necesita cotización)
  const monedasConCotizacion = empresaMonedas.filter(
    (em) => em.moneda?.codigo !== "PYG",
  );

  const handleOpenCreate = () => {
    setFormData({
      moneda_id: selectedMonedaId || monedasConCotizacion[0]?.moneda_id || "",
      fecha: hoyISO(),
      cotizacion_compra: "",
      cotizacion_venta: "",
    });
    setFormDialogOpen(true);
  };

  const handleCreate = () => {
    if (
      !formData.moneda_id ||
      !formData.fecha ||
      !formData.cotizacion_compra ||
      !formData.cotizacion_venta
    ) {
      toast.error("Complete todos los campos");
      return;
    }
    createMutation.mutate(
      {
        moneda_id: formData.moneda_id,
        fecha: formData.fecha,
        cotizacion_compra: parseFloat(formData.cotizacion_compra),
        cotizacion_venta: parseFloat(formData.cotizacion_venta),
      },
      {
        onSuccess: () => {
          setFormDialogOpen(false);
        },
      },
    );
  };

  const handleOpenDelete = (cot) => {
    setCotizacionToDelete(cot);
    setDeleteDialogOpen(true);
  };

  const handleDelete = () => {
    deleteMutation.mutate(cotizacionToDelete.id, {
      onSuccess: () => {
        setDeleteDialogOpen(false);
        setCotizacionToDelete(null);
      },
    });
  };

  const formatNumber = (num) => {
    return new Intl.NumberFormat("es-PY", {
      minimumFractionDigits: 2,
      maximumFractionDigits: 2,
    }).format(num);
  };

  const formatFecha = (fecha) => {
    if (!fecha) return "-";
    // La fecha puede venir como string, Date object, o ISO string
    let dateObj;
    if (fecha instanceof Date) {
      dateObj = fecha;
    } else if (typeof fecha === "string") {
      dateObj = new Date(fecha);
    } else {
      return "-";
    }
    const day = String(dateObj.getUTCDate()).padStart(2, "0");
    const month = String(dateObj.getUTCMonth() + 1).padStart(2, "0");
    const year = dateObj.getUTCFullYear();
    return `${day}/${month}/${year}`;
  };

  return (
    <Paper sx={{ p: 2 }}>
      <Box
        sx={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "flex-start",
          mb: 2,
          flexWrap: "wrap",
          gap: 1.5,
        }}
      >
        <Box>
          <Typography
            variant="h6"
            sx={{ fontSize: { xs: "1rem", sm: "1.25rem" } }}
          >
            Historial de Cotizaciones
          </Typography>
          <Typography
            variant="body2"
            color="text.secondary"
            sx={{ fontSize: { xs: "0.75rem", sm: "0.875rem" } }}
          >
            Registre las cotizaciones diarias para monedas extranjeras
          </Typography>
        </Box>
        <Box
          sx={{
            display: "flex",
            gap: 1.5,
            alignItems: "center",
            flexWrap: "wrap",
            width: { xs: "100%", sm: "auto" },
          }}
        >
          <Autocomplete
            size="small"
            sx={{ flex: "1 1 150px", minWidth: 140 }}
            options={monedasConCotizacion}
            getOptionLabel={(opt) =>
              `${opt.moneda?.codigo} - ${opt.moneda?.descripcion}`
            }
            value={
              monedasConCotizacion.find(
                (m) => m.moneda_id === selectedMonedaId,
              ) || null
            }
            onChange={(_, v) => setSelectedMonedaId(v?.moneda_id || null)}
            renderInput={(params) => (
              <TextField {...params} label="Filtrar por moneda" />
            )}
          />
          {puedeRegistrar && (
          <Button
            variant="contained"
            startIcon={<Add />}
            onClick={handleOpenCreate}
            disabled={monedasConCotizacion.length === 0}
            size={isMobile ? "small" : "medium"}
            sx={{ flexShrink: 0 }}
          >
            {isMobile ? "Nueva" : "Nueva Cotización"}
          </Button>
          )}
        </Box>
      </Box>

      {monedasConCotizacion.length === 0 ? (
        <Box sx={{ textAlign: "center", py: 4 }}>
          <Typography color="text.secondary">
            No hay monedas extranjeras configuradas. Agregue monedas diferentes
            a PYG para registrar cotizaciones.
          </Typography>
        </Box>
      ) : isMobile ? (
        /* Vista mobile: cards de cotizaciones */
        <Stack spacing={1.5}>
          {isLoading ? (
            <Typography color="text.secondary" textAlign="center" py={2}>
              Cargando...
            </Typography>
          ) : cotizaciones.length === 0 ? (
            <Typography color="text.secondary" textAlign="center" py={2}>
              No hay cotizaciones registradas
            </Typography>
          ) : (
            cotizaciones.map((cot) => (
              <Card key={cot.id} variant="outlined" sx={{ borderRadius: 2 }}>
                <CardContent sx={{ p: "12px !important" }}>
                  <Box
                    sx={{
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "space-between",
                      mb: 0.5,
                    }}
                  >
                    <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
                      <Chip
                        label={cot.moneda?.codigo}
                        size="small"
                        color="primary"
                        variant="outlined"
                      />
                      <Typography variant="caption" color="text.secondary">
                        {formatFecha(cot.fecha)}
                      </Typography>
                    </Box>
                    {puedeRegistrar && (
                    <Tooltip title="Eliminar">
                      <IconButton
                        size="small"
                        onClick={() => handleOpenDelete(cot)}
                        color="error"
                      >
                        <Delete fontSize="small" />
                      </IconButton>
                    </Tooltip>
                    )}
                  </Box>
                  <Box sx={{ display: "flex", gap: 2 }}>
                    <Box>
                      <Typography variant="caption" color="text.secondary">
                        Compra
                      </Typography>
                      <Typography variant="body2" fontWeight={500}>
                        {formatNumber(cot.cotizacion_compra)} ₲
                      </Typography>
                    </Box>
                    <Box>
                      <Typography variant="caption" color="text.secondary">
                        Venta
                      </Typography>
                      <Typography variant="body2" fontWeight={500}>
                        {formatNumber(cot.cotizacion_venta)} ₲
                      </Typography>
                    </Box>
                  </Box>
                </CardContent>
              </Card>
            ))
          )}
        </Stack>
      ) : (
        /* Vista desktop: tabla */
        <TableContainer>
          <Table size="small">
            <TableHead>
              <TableRow>
                <TableCell>Fecha</TableCell>
                <TableCell>Moneda</TableCell>
                <TableCell align="right">Cotización Compra</TableCell>
                <TableCell align="right">Cotización Venta</TableCell>
                <TableCell align="right">Acciones</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {isLoading ? (
                <TableRow>
                  <TableCell colSpan={5} align="center">
                    Cargando...
                  </TableCell>
                </TableRow>
              ) : cotizaciones.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={5} align="center">
                    <Typography color="text.secondary" sx={{ py: 2 }}>
                      No hay cotizaciones registradas
                    </Typography>
                  </TableCell>
                </TableRow>
              ) : (
                cotizaciones.map((cot) => (
                  <TableRow key={cot.id} hover>
                    <TableCell>{formatFecha(cot.fecha)}</TableCell>
                    <TableCell>
                      <Chip
                        label={cot.moneda?.codigo}
                        size="small"
                        color="primary"
                        variant="outlined"
                      />
                    </TableCell>
                    <TableCell align="right">
                      <Typography fontWeight={500}>
                        {formatNumber(cot.cotizacion_compra)} ₲
                      </Typography>
                    </TableCell>
                    <TableCell align="right">
                      <Typography fontWeight={500}>
                        {formatNumber(cot.cotizacion_venta)} ₲
                      </Typography>
                    </TableCell>
                    <TableCell align="right">
                      {puedeRegistrar && (
                      <Tooltip title="Eliminar">
                        <IconButton
                          size="small"
                          onClick={() => handleOpenDelete(cot)}
                          color="error"
                        >
                          <Delete fontSize="small" />
                        </IconButton>
                      </Tooltip>
                      )}
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </TableContainer>
      )}

      {/* Dialog Nueva Cotización */}
      <Dialog
        open={formDialogOpen}
        onClose={() => setFormDialogOpen(false)}
        maxWidth="sm"
        fullWidth
      >
        <DialogTitle>Nueva Cotización</DialogTitle>
        <DialogContent>
          <Box sx={{ display: "flex", flexDirection: "column", gap: 2, mt: 1 }}>
            <Autocomplete
              size="small"
              options={monedasConCotizacion}
              getOptionLabel={(opt) =>
                `${opt.moneda?.codigo} - ${opt.moneda?.descripcion}`
              }
              value={
                monedasConCotizacion.find(
                  (m) => m.moneda_id === formData.moneda_id,
                ) || null
              }
              onChange={(_, v) =>
                setFormData({ ...formData, moneda_id: v?.moneda_id || "" })
              }
              renderInput={(params) => (
                <TextField {...params} label="Moneda *" />
              )}
            />
            <TextField
              label="Fecha *"
              type="date"
              size="small"
              value={formData.fecha}
              onChange={(e) =>
                setFormData({ ...formData, fecha: e.target.value })
              }
              InputLabelProps={{ shrink: true }}
            />
            <Divider />
            <Box sx={{ display: "flex", gap: 2 }}>
              <TextField
                fullWidth
                label="Cotización Compra (₲) *"
                type="number"
                size="small"
                value={formData.cotizacion_compra}
                onChange={(e) =>
                  setFormData({
                    ...formData,
                    cotizacion_compra: e.target.value,
                  })
                }
                placeholder="Ej: 7300"
              />
              <TextField
                fullWidth
                label="Cotización Venta (₲) *"
                type="number"
                size="small"
                value={formData.cotizacion_venta}
                onChange={(e) =>
                  setFormData({ ...formData, cotizacion_venta: e.target.value })
                }
                placeholder="Ej: 7400"
              />
            </Box>
          </Box>
        </DialogContent>
        <DialogActions sx={{ p: 2 }}>
          <Button onClick={() => setFormDialogOpen(false)}>Cancelar</Button>
          <Button
            variant="contained"
            onClick={handleCreate}
            disabled={createMutation.isPending}
          >
            {createMutation.isPending ? "Guardando..." : "Guardar"}
          </Button>
        </DialogActions>
      </Dialog>

      {/* Dialog Confirmar Eliminación */}
      <Dialog
        open={deleteDialogOpen}
        onClose={() => setDeleteDialogOpen(false)}
        maxWidth="xs"
        fullWidth
      >
        <DialogTitle>Confirmar Eliminación</DialogTitle>
        <DialogContent>
          <Typography>
            ¿Está seguro de eliminar la cotización del{" "}
            <strong>
              {cotizacionToDelete && formatFecha(cotizacionToDelete.fecha)}
            </strong>{" "}
            para <strong>{cotizacionToDelete?.moneda?.codigo}</strong>?
          </Typography>
        </DialogContent>
        <DialogActions sx={{ p: 2 }}>
          <Button onClick={() => setDeleteDialogOpen(false)} variant="outlined">
            Cancelar
          </Button>
          <Button
            variant="contained"
            color="error"
            onClick={handleDelete}
            disabled={deleteMutation.isPending}
          >
            {deleteMutation.isPending ? "Eliminando..." : "Eliminar"}
          </Button>
        </DialogActions>
      </Dialog>
    </Paper>
  );
}
