import { Icon } from "@iconify/react/dist/iconify.js";
import {
  Alert,
  Box,
  Button,
  Chip,
  CircularProgress,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Divider,
  Grid,
  IconButton,
  Paper,
  Skeleton,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  Tooltip,
  Typography,
  useMediaQuery,
  useTheme,
} from "@mui/material";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { toast } from "sonner";
import {
  aprobarOrdenVenta,
  cancelarOrdenVenta,
  confirmarOrdenVenta,
  getOrdenVenta,
  iniciarOrdenVenta,
} from "../api/ordenes.service";
import { formatMoney } from "../utils/formatMoney";

// ─── Constantes ───────────────────────────────────────────────────────────────

const ESTADO_MAP = {
  borrador:          { label: "Borrador",       color: "default",   icon: "mdi:file-edit-outline" },
  confirmada:        { label: "Confirmada",     color: "primary",   icon: "mdi:check-circle-outline" },
  aprobada:          { label: "Aprobada",       color: "info",      icon: "mdi:thumb-up-outline" },
  en_proceso:        { label: "En proceso",     color: "warning",   icon: "mdi:progress-clock" },
  facturada_parcial: { label: "Fact. parcial",  color: "secondary", icon: "mdi:receipt-text-clock-outline" },
  facturada:         { label: "Facturada",      color: "success",   icon: "mdi:receipt-text-check-outline" },
  cancelada:         { label: "Cancelada",      color: "error",     icon: "mdi:close-circle-outline" },
  vencida:           { label: "Vencida",        color: "error",     icon: "mdi:calendar-remove-outline" },
};

// ─── Helpers ──────────────────────────────────────────────────────────────────

function fmt(str, withTime = false) {
  if (!str) return "—";
  const d = new Date(str);
  const fecha = d.toLocaleDateString("es-PY");
  if (!withTime) return fecha;
  const hora = d.toLocaleTimeString("es-PY", { hour: "2-digit", minute: "2-digit", second: "2-digit" });
  return `${fecha} ${hora}`;
}

function getNombreCliente(orden) {
  return orden.cliente?.personas?.razon_social || orden.cliente?.nombre_fantasia || "—";
}

function getOrigenOrdenLabel(orden) {
  const tipo = String(orden?.origen_tipo || "").toLowerCase();
  if (tipo === "presupuesto" || orden?.presupuesto_id) return "Presupuesto";
  if (tipo === "solicitud_credito") return "Solicitud de crédito";
  if (tipo === "importacion") return "Importación";
  if (tipo === "otro") return "Otro";
  return "Manual";
}

// ─── InfoRow ──────────────────────────────────────────────────────────────────

function InfoRow({ label, value }) {
  return (
    <Box sx={{ display: "flex", justifyContent: "space-between", py: 0.5 }}>
      <Typography variant="caption" color="text.secondary">{label}</Typography>
      <Typography variant="body2" fontWeight={500} textAlign="right" sx={{ maxWidth: "60%" }}>{value || "—"}</Typography>
    </Box>
  );
}

// ─── Dialog de cancelación ────────────────────────────────────────────────────

function CancelarDialog({ open, onClose, onConfirm, loading }) {
  const [motivo, setMotivo] = useState("");
  return (
    <Dialog open={open} onClose={onClose} maxWidth="xs" fullWidth>
      <DialogTitle>Cancelar orden</DialogTitle>
      <DialogContent>
        <Typography variant="body2" color="text.secondary" mb={2}>
          Esta acción no se puede deshacer. El stock reservado será liberado.
        </Typography>
        <TextField
          label="Motivo (opcional)"
          fullWidth
          multiline
          rows={2}
          size="small"
          value={motivo}
          onChange={(e) => setMotivo(e.target.value)}
        />
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose} disabled={loading}>Volver</Button>
        <Button
          variant="contained"
          color="error"
          onClick={() => onConfirm(motivo)}
          disabled={loading}
          startIcon={loading ? <CircularProgress size={14} /> : <Icon icon="mdi:close-circle" width={16} />}
        >
          Confirmar cancelación
        </Button>
      </DialogActions>
    </Dialog>
  );
}

// ─── Componente principal ─────────────────────────────────────────────────────

export function OrdenVentaDetalle() {
  const { id } = useParams();
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down("md"));
  const [cancelarOpen, setCancelarOpen] = useState(false);

  const { data: orden, isLoading, error } = useQuery({
    queryKey: ["ordenes-venta", "detalle", id],
    queryFn: () => getOrdenVenta(id),
    select: (r) => r?.data ?? r,
  });

  const invalidar = () => {
    queryClient.invalidateQueries({ queryKey: ["ordenes-venta", "detalle", id] });
    queryClient.invalidateQueries({ queryKey: ["ordenes-venta", "list"] });
    queryClient.invalidateQueries({ queryKey: ["ordenes-venta", "stats"] });
  };

  const confirmarMut = useMutation({
    mutationFn: () => confirmarOrdenVenta(id),
    onSuccess: (res) => { toast.success(res?.message ?? "Orden confirmada"); invalidar(); },
    onError: (e) => toast.error(e?.response?.data?.message ?? "Error al confirmar"),
  });

  const aprobarMut = useMutation({
    mutationFn: () => aprobarOrdenVenta(id),
    onSuccess: (res) => { toast.success(res?.message ?? "Orden aprobada"); invalidar(); },
    onError: (e) => toast.error(e?.response?.data?.message ?? "Error al aprobar"),
  });

  const iniciarMut = useMutation({
    mutationFn: () => iniciarOrdenVenta(id),
    onSuccess: (res) => { toast.success(res?.message ?? "Orden en proceso"); invalidar(); },
    onError: (e) => toast.error(e?.response?.data?.message ?? "Error al iniciar"),
  });

  const cancelarMut = useMutation({
    mutationFn: (motivo) => cancelarOrdenVenta(id, motivo),
    onSuccess: () => { toast.success("Orden cancelada"); invalidar(); setCancelarOpen(false); },
    onError: (e) => toast.error(e?.response?.data?.message ?? "Error al cancelar"),
  });

  if (isLoading) return (
    <Box sx={{ p: 3 }}>
      <Skeleton width={200} height={28} sx={{ mb: 2 }} />
      <Grid container spacing={2}>
        <Grid item xs={12} md={8}><Skeleton variant="rectangular" height={300} /></Grid>
        <Grid item xs={12} md={4}><Skeleton variant="rectangular" height={300} /></Grid>
      </Grid>
    </Box>
  );

  if (error || !orden) return (
    <Box sx={{ p: 3 }}>
      <Alert severity="error">No se pudo cargar la orden de venta.</Alert>
    </Box>
  );

  const estadoInfo = ESTADO_MAP[orden.estado_orden] ?? {};
  const items = orden.detalle ?? [];
  const historial = orden.historial ?? [];
  const anyMutPending = confirmarMut.isPending || aprobarMut.isPending || iniciarMut.isPending || cancelarMut.isPending;

  const totalOrden = Number(orden.total ?? 0);
  const subtotal = Number(orden.subtotal ?? 0);
  const totalIva = Number(orden.total_iva ?? 0);
  const totalDesc = Number(orden.total_descuento ?? 0);
  const montoFacturado = Number(orden.monto_facturado ?? 0);
  const pendienteFact = totalOrden - montoFacturado;

  return (
    <Box sx={{ p: { xs: 1.5, sm: 3 } }}>

      {/* ── Header ──────────────────────────────────────────── */}
      <Box sx={{ display: "flex", alignItems: "center", gap: 1, mb: 2, flexWrap: "wrap" }}>
        <Tooltip title="Volver a la lista">
          <IconButton size="small" onClick={() => navigate("/ventas?tab=ordenes-venta")}>
            <Icon icon="mdi:arrow-left" width={20} />
          </IconButton>
        </Tooltip>
        <Typography variant="h6" fontFamily="monospace" fontWeight={700}>
          {orden.numero_pedido ?? (
            <Typography component="span" variant="body1" color="text.disabled" fontStyle="italic">
              Borrador sin número
            </Typography>
          )}
        </Typography>
        <Tooltip title={`Estado: ${estadoInfo.label}`}>
          <Chip
            size="small"
            label={estadoInfo.label}
            color={estadoInfo.color ?? "default"}
            icon={estadoInfo.icon ? <Icon icon={estadoInfo.icon} width={13} /> : undefined}
          />
        </Tooltip>
        {orden.stock_reservado && (
          <Chip size="small" label="Stock reservado" icon={<Icon icon="mdi:package-variant-closed" width={13} />} variant="outlined" />
        )}
        <Box sx={{ flex: 1 }} />

        {/* ── Botones de acción ──────────────────────────────── */}
        {orden.estado_orden === "borrador" && (
          <>
            <Button
              size="small"
              variant="outlined"
              startIcon={<Icon icon="mdi:pencil" width={15} />}
              onClick={() => navigate(`/ordenes-venta/${id}/editar`)}
            >
              Editar
            </Button>
            <Button
              size="small"
              variant="contained"
              color="primary"
              startIcon={<Icon icon="mdi:check-circle" width={15} />}
              onClick={() => confirmarMut.mutate()}
              disabled={anyMutPending}
            >
              Confirmar
            </Button>
          </>
        )}

        {orden.estado_orden === "confirmada" && (
          <Button
            size="small"
            variant="contained"
            color="success"
            startIcon={<Icon icon="mdi:thumb-up" width={15} />}
            onClick={() => aprobarMut.mutate()}
            disabled={anyMutPending}
          >
            Aprobar
          </Button>
        )}

        {orden.estado_orden === "aprobada" && (
          <Button
            size="small"
            variant="contained"
            color="warning"
            startIcon={<Icon icon="mdi:progress-clock" width={15} />}
            onClick={() => iniciarMut.mutate()}
            disabled={anyMutPending}
          >
            Iniciar proceso
          </Button>
        )}

        {["en_proceso", "facturada_parcial"].includes(orden.estado_orden) && (
          <Tooltip title="Próximamente — Facturar desde POS">
            <span>
              <Button
                size="small"
                variant="contained"
                color="success"
                startIcon={<Icon icon="mdi:receipt-text-plus" width={15} />}
                disabled
              >
                Facturar
              </Button>
            </span>
          </Tooltip>
        )}

        {orden.estado_orden === "facturada" && orden.factura && (
          <Button
            size="small"
            variant="outlined"
            startIcon={<Icon icon="mdi:receipt-text-check-outline" width={15} />}
            onClick={() => navigate(`/ventas?facturaId=${orden.factura.id}`)}
          >
            Ver factura
          </Button>
        )}

        {["borrador", "confirmada", "aprobada", "en_proceso"].includes(orden.estado_orden) && (
          <Button
            size="small"
            variant="outlined"
            color="error"
            startIcon={<Icon icon="mdi:close-circle" width={15} />}
            onClick={() => setCancelarOpen(true)}
            disabled={anyMutPending}
          >
            Cancelar
          </Button>
        )}
      </Box>

      {/* ── Body ────────────────────────────────────────────── */}
      <Grid container spacing={2}>

        {/* ── Panel izquierdo: items + historial ──────────── */}
        <Grid item xs={12} md={8}>

          {/* Items */}
          <Paper variant="outlined" sx={{ mb: 2 }}>
            <Box sx={{ px: 2, py: 1.5, borderBottom: 1, borderColor: "divider" }}>
              <Typography variant="subtitle2">Ítems ({items.length})</Typography>
            </Box>
            {items.length === 0 ? (
              <Box sx={{ p: 3, textAlign: "center" }}>
                <Typography color="text.disabled" variant="body2">Sin ítems registrados</Typography>
              </Box>
            ) : (
              <TableContainer>
                <Table size="small">
                  <TableHead>
                    <TableRow>
                      <TableCell>#</TableCell>
                      <TableCell>Producto</TableCell>
                      {!isMobile && <TableCell>Presentación</TableCell>}
                      <TableCell align="right">Cantidad</TableCell>
                      <TableCell align="right">Precio unit.</TableCell>
                      {!isMobile && <TableCell align="right">Desc.</TableCell>}
                      <TableCell align="right">Total</TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {items.map((it) => (
                      <TableRow key={it.id ?? it.item} hover>
                        <TableCell>
                          <Typography variant="caption" color="text.secondary">{it.item}</Typography>
                        </TableCell>
                        <TableCell>
                          <Typography variant="body2" fontWeight={500}>{it.producto?.descripcion ?? "—"}</Typography>
                          {it.producto?.codigo_barra && (
                            <Typography variant="caption" color="text.disabled">{it.producto.codigo_barra}</Typography>
                          )}
                        </TableCell>
                        {!isMobile && (
                          <TableCell>
                            <Typography variant="caption">{it.presentacion?.nombre ?? "—"}</Typography>
                          </TableCell>
                        )}
                        <TableCell align="right">
                          <Typography variant="body2">
                            {Number(it.cantidad ?? it.cantidad_base ?? 0).toLocaleString("es-PY")}
                          </Typography>
                        </TableCell>
                        <TableCell align="right">
                          <Typography variant="body2">
                            {formatMoney(Number(it.precio_negociado ?? it.precio_unitario ?? 0))}
                          </Typography>
                        </TableCell>
                        {!isMobile && (
                          <TableCell align="right">
                            <Typography variant="body2" color={Number(it.descuento_porcentaje) > 0 ? "warning.main" : "text.secondary"}>
                              {Number(it.descuento_porcentaje ?? 0) > 0 ? `${it.descuento_porcentaje}%` : "—"}
                            </Typography>
                          </TableCell>
                        )}
                        <TableCell align="right">
                          <Typography variant="body2" fontWeight={600}>
                            {formatMoney(Number(it.total_item ?? it.subtotal ?? 0))}
                          </Typography>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </TableContainer>
            )}
          </Paper>

          {/* Historial */}
          {historial.length > 0 && (
            <Paper variant="outlined">
              <Box sx={{ px: 2, py: 1.5, borderBottom: 1, borderColor: "divider" }}>
                <Typography variant="subtitle2">Historial de cambios</Typography>
              </Box>
              <Stack spacing={0} divider={<Divider />}>
                {historial.map((h, i) => {
                  const eInfo = ESTADO_MAP[h.estado] ?? {};
                  return (
                    <Box key={i} sx={{ px: 2, py: 1.2, display: "flex", alignItems: "flex-start", gap: 1.5 }}>
                      <Chip
                        size="small"
                        label={eInfo.label ?? h.estado}
                        color={eInfo.color ?? "default"}
                        icon={eInfo.icon ? <Icon icon={eInfo.icon} width={12} /> : undefined}
                        sx={{ mt: 0.2 }}
                      />
                      <Box sx={{ flex: 1 }}>
                        {h.descripcion && (
                          <Typography variant="body2" color="text.secondary">{h.descripcion}</Typography>
                        )}
                        <Typography variant="caption" color="text.disabled">
                          {fmt(h.created_at, true)} · {h.usuario?.username ?? "Sistema"}
                        </Typography>
                      </Box>
                    </Box>
                  );
                })}
              </Stack>
            </Paper>
          )}
        </Grid>

        {/* ── Panel derecho: info + totales ────────────────── */}
        <Grid item xs={12} md={4}>
          <Stack spacing={2}>

            {/* Info de la orden */}
            <Paper variant="outlined" sx={{ p: 2 }}>
              <Typography variant="subtitle2" mb={1}>Información</Typography>
              <InfoRow label="Cliente" value={getNombreCliente(orden)} />
              {orden.cliente?.personas?.ruc && (
                <InfoRow label="RUC" value={orden.cliente.personas.ruc} />
              )}
              <InfoRow label="Vendedor" value={orden.vendedor ? `${orden.vendedor.nombre} ${orden.vendedor.apellido}` : null} />
              <InfoRow label="Origen" value={getOrigenOrdenLabel(orden)} />
              <InfoRow label="Sucursal" value={orden.sucursal?.descripcion} />
              <InfoRow label="Depósito" value={orden.deposito?.descripcion} />
              <InfoRow label="Moneda" value={orden.moneda ? `${orden.moneda.descripcion} (${orden.moneda.codigo})` : null} />
              <InfoRow label="Lista de precios" value={orden.lista_precios?.nombre} />
              <Divider sx={{ my: 1 }} />
              <InfoRow label="Fecha" value={fmt(orden.fecha_pedido, true)} />
              <InfoRow label="Vencimiento" value={fmt(orden.fecha_venc_orden)} />
              <InfoRow label="Confirmada" value={fmt(orden.fecha_confirmacion)} />
              <InfoRow label="Creado por" value={orden.creador?.username} />
            </Paper>

            {/* Totales */}
            <Paper variant="outlined" sx={{ p: 2 }}>
              <Typography variant="subtitle2" mb={1}>Totales</Typography>
              {subtotal > 0 && subtotal !== totalOrden && (
                <InfoRow label="Subtotal" value={formatMoney(subtotal)} />
              )}
              {totalDesc > 0 && (
                <InfoRow label="Descuento" value={`− ${formatMoney(totalDesc)}`} />
              )}
              {totalIva > 0 && (
                <InfoRow label="IVA" value={formatMoney(totalIva)} />
              )}
              <Divider sx={{ my: 1 }} />
              <Box sx={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                <Typography variant="body2" fontWeight={700}>Total</Typography>
                <Typography variant="h6" fontWeight={700} color="success.main">
                  {formatMoney(totalOrden)}
                </Typography>
              </Box>
              {montoFacturado > 0 && (
                <>
                  <Divider sx={{ my: 1 }} />
                  <InfoRow label="Facturado" value={formatMoney(montoFacturado)} />
                  <InfoRow label="Pendiente" value={formatMoney(pendienteFact)} />
                </>
              )}
            </Paper>

          </Stack>
        </Grid>
      </Grid>

      {/* ── Dialog cancelar ──────────────────────────────────── */}
      <CancelarDialog
        open={cancelarOpen}
        onClose={() => setCancelarOpen(false)}
        onConfirm={(motivo) => cancelarMut.mutate(motivo)}
        loading={cancelarMut.isPending}
      />
    </Box>
  );
}

export default OrdenVentaDetalle;
