import { Icon } from "@iconify/react/dist/iconify.js";
import {
  Box,
  Chip,
  CircularProgress,
  Dialog,
  DialogContent,
  DialogTitle,
  IconButton,
  InputAdornment,
  MenuItem,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { useEffect, useMemo, useState } from "react";
import { toast } from "sonner";
import styled from "styled-components";
import { getPedidosPendientesCaja, getPedidosPendientesCliente } from "../../../api/pedidos.service";
import { getMoneda } from "../../../api/monedas.service";
import { formatMoney } from "../../../utils/formatMoney";

export function PedidosPendientesDialog({ open, onClose, onSelectPedido, sucursalId, clienteId }) {
  const [pedidos, setPedidos] = useState([]);
  const [loading, setLoading] = useState(false);
  const [busqueda, setBusqueda] = useState("");
  const [filtroEstado, setFiltroEstado] = useState("todos");
  const [filtroVencimiento, setFiltroVencimiento] = useState("todos");
  const [monedasCache, setMonedasCache] = useState({});

  useEffect(() => {
    if (!open) return;
    setBusqueda("");
    setFiltroEstado("todos");
    setFiltroVencimiento("todos");
    let cancelled = false;
    setLoading(true);

    const fetcher = clienteId
      ? getPedidosPendientesCliente(clienteId, sucursalId)
      : getPedidosPendientesCaja(sucursalId);

    fetcher
      .then((data) => {
        if (cancelled) return;
        const lista = Array.isArray(data) ? data : data?.dataFormat || data?.data || [];
        setPedidos(lista);

        // Cargar monedas únicas para formateo
        const monedaIds = [...new Set(lista.map((p) => p.moneda_id).filter(Boolean))];
        monedaIds.forEach((id) => {
          if (!monedasCache[id]) {
            getMoneda(id)
              .then((m) => {
                if (!cancelled) {
                  setMonedasCache((prev) => ({ ...prev, [id]: m }));
                }
              })
              .catch(() => {});
          }
        });
      })
      .catch(() => {
        if (!cancelled) {
          toast.error("Error cargando pedidos pendientes");
          setPedidos([]);
        }
      })
      .finally(() => {
        if (!cancelled) setLoading(false);
      });
    return () => { cancelled = true; };
  }, [open, sucursalId, clienteId]);

  const getEstadoVencimiento = (fechaVenc) => {
    if (!fechaVenc) return "sin_fecha";
    const hoy = new Date();
    hoy.setHours(0, 0, 0, 0);
    const venc = new Date(fechaVenc);
    venc.setHours(0, 0, 0, 0);
    const diffDias = Math.ceil((venc - hoy) / (1000 * 60 * 60 * 24));
    if (diffDias < 0) return "vencido";
    if (diffDias <= 3) return "por_vencer";
    return "vigente";
  };

  const fmtMoneda = (val, monedaId) => {
    const moneda = monedasCache[monedaId];
    if (moneda?.codigo) {
      return formatMoney(val, moneda.codigo);
    }
    return formatMoney(val, "PYG");
  };

  const pedidosFiltrados = useMemo(() => {
    return pedidos.filter((pedido) => {
      // Filtro de búsqueda
      if (busqueda.trim()) {
        const term = busqueda.toLowerCase();
        const cliente = pedido.cliente;
        const razonSocial = (cliente?.personas?.razon_social || cliente?.nombre_fantasia || "").toLowerCase();
        const ruc = (cliente?.personas?.ruc || "").toLowerCase();
        const numero = (pedido.numero_pedido || "").toLowerCase();
        const vendedorNombre = pedido.vendedor ? `${pedido.vendedor.nombre || ""} ${pedido.vendedor.apellido || ""}`.toLowerCase() : "";
        if (
          !razonSocial.includes(term) &&
          !ruc.includes(term) &&
          !numero.includes(term) &&
          !vendedorNombre.includes(term)
        ) {
          return false;
        }
      }

      // Filtro de estado
      if (filtroEstado !== "todos" && pedido.estado !== filtroEstado) {
        return false;
      }

      // Filtro de vencimiento
      if (filtroVencimiento !== "todos") {
        const estadoVenc = getEstadoVencimiento(pedido.fecha_vencimiento);
        if (filtroVencimiento !== estadoVenc) return false;
      }

      return true;
    });
  }, [pedidos, busqueda, filtroEstado, filtroVencimiento]);

  const handleSelect = (pedido) => {
    onSelectPedido(pedido);
    onClose();
  };

  return (
    <Dialog open={open} onClose={onClose} maxWidth="md" fullWidth>
      <DialogTitle sx={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
          <Icon icon="mdi:clipboard-list" width={24} />
          Pedidos Pendientes{clienteId ? " del Cliente" : " de Cobro"}
          {!loading && pedidos.length > 0 && (
            <Chip label={pedidosFiltrados.length} size="small" sx={{ ml: 0.5 }} />
          )}
        </Box>
        <IconButton onClick={onClose} size="small">
          <Icon icon="mdi:close" width={20} />
        </IconButton>
      </DialogTitle>
      <DialogContent>
        {loading ? (
          <Box sx={{ display: "flex", justifyContent: "center", py: 6 }}>
            <CircularProgress />
          </Box>
        ) : pedidos.length === 0 ? (
          <EmptyState>
            <Icon icon="mdi:clipboard-check" width={48} />
            <Typography variant="h6" sx={{ mt: 2 }}>
              No hay pedidos pendientes
            </Typography>
            <Typography variant="body2" color="text.secondary">
              {clienteId
                ? "Este cliente no tiene pedidos pendientes"
                : "Los pedidos confirmados aparecerán aquí para ser cobrados"}
            </Typography>
          </EmptyState>
        ) : (
          <>
            {/* Buscador y filtros */}
            <FiltersBar>
              <TextField
                size="small"
                placeholder="Buscar por nro, cliente, RUC, vendedor..."
                value={busqueda}
                onChange={(e) => setBusqueda(e.target.value)}
                sx={{ flex: 1, minWidth: 200 }}
                slotProps={{
                  input: {
                    startAdornment: (
                      <InputAdornment position="start">
                        <Icon icon="mdi:magnify" width={20} />
                      </InputAdornment>
                    ),
                    ...(busqueda && {
                      endAdornment: (
                        <InputAdornment position="end">
                          <IconButton size="small" onClick={() => setBusqueda("")}>
                            <Icon icon="mdi:close" width={16} />
                          </IconButton>
                        </InputAdornment>
                      ),
                    }),
                  },
                }}
              />
              <TextField
                select
                size="small"
                label="Estado"
                value={filtroEstado}
                onChange={(e) => setFiltroEstado(e.target.value)}
                sx={{ minWidth: 140 }}
              >
                <MenuItem value="todos">Todos</MenuItem>
                <MenuItem value="confirmado">Confirmado</MenuItem>
              </TextField>
              <TextField
                select
                size="small"
                label="Vencimiento"
                value={filtroVencimiento}
                onChange={(e) => setFiltroVencimiento(e.target.value)}
                sx={{ minWidth: 150 }}
              >
                <MenuItem value="todos">Todos</MenuItem>
                <MenuItem value="vencido">Vencidos</MenuItem>
                <MenuItem value="por_vencer">Por vencer (3 días)</MenuItem>
                <MenuItem value="vigente">Vigentes</MenuItem>
                <MenuItem value="sin_fecha">Sin fecha</MenuItem>
              </TextField>
            </FiltersBar>

            {pedidosFiltrados.length === 0 ? (
              <EmptyState>
                <Icon icon="mdi:filter-off" width={40} />
                <Typography variant="body1" sx={{ mt: 1 }}>
                  No se encontraron pedidos con los filtros aplicados
                </Typography>
              </EmptyState>
            ) : (
              <PedidosList>
                {pedidosFiltrados.map((pedido) => {
                  const cliente = pedido.cliente;
                  const razonSocial =
                    cliente?.personas?.razon_social ||
                    cliente?.nombre_fantasia ||
                    "Sin nombre";
                  const ruc = cliente?.personas?.ruc || "";
                  const vendedor = pedido.vendedor;
                  const cantItems = pedido._count?.detalle || pedido.detalle?.length || 0;
                  const fechaConf = pedido.fecha_confirmacion
                    ? new Date(pedido.fecha_confirmacion).toLocaleDateString("es-PY", {
                        day: "2-digit",
                        month: "2-digit",
                        year: "2-digit",
                        hour: "2-digit",
                        minute: "2-digit",
                      })
                    : "";

                  const estadoVenc = getEstadoVencimiento(pedido.fecha_vencimiento);
                  const fechaVencFmt = pedido.fecha_vencimiento
                    ? new Date(pedido.fecha_vencimiento).toLocaleDateString("es-PY", {
                        day: "2-digit",
                        month: "2-digit",
                        year: "2-digit",
                      })
                    : null;

                  return (
                    <PedidoCard
                      key={pedido.id}
                      onClick={() => handleSelect(pedido)}
                      $vencido={estadoVenc === "vencido"}
                    >
                      <CardHeader>
                        <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
                          <PedidoNumero>{pedido.numero_pedido || "Borrador"}</PedidoNumero>
                          <Chip
                            label="Confirmado"
                            size="small"
                            color="success"
                            variant="outlined"
                          />
                          {estadoVenc === "vencido" && (
                            <Tooltip title={`Vencido el ${fechaVencFmt}`}>
                              <Chip
                                icon={<Icon icon="mdi:alert" width={14} />}
                                label="Vencido"
                                size="small"
                                color="error"
                                variant="filled"
                              />
                            </Tooltip>
                          )}
                          {estadoVenc === "por_vencer" && (
                            <Tooltip title={`Vence el ${fechaVencFmt}`}>
                              <Chip
                                icon={<Icon icon="mdi:clock-alert" width={14} />}
                                label="Por vencer"
                                size="small"
                                color="warning"
                                variant="filled"
                              />
                            </Tooltip>
                          )}
                        </Box>
                        <Box sx={{ display: "flex", flexDirection: "column", alignItems: "flex-end" }}>
                          <Typography variant="caption" color="text.secondary">
                            {fechaConf}
                          </Typography>
                          {fechaVencFmt && estadoVenc === "vigente" && (
                            <Typography variant="caption" color="text.secondary" sx={{ fontSize: "0.7rem" }}>
                              Vence: {fechaVencFmt}
                            </Typography>
                          )}
                        </Box>
                      </CardHeader>

                      <CardBody>
                        <ClienteInfo>
                          <Icon icon="mdi:account" width={16} />
                          <span className="nombre">{razonSocial}</span>
                          {ruc && <span className="ruc">RUC: {ruc}</span>}
                        </ClienteInfo>

                        <MetaRow>
                          {vendedor && (
                            <MetaItem>
                              <Icon icon="mdi:badge-account" width={14} />
                              {vendedor.nombre} {vendedor.apellido}
                            </MetaItem>
                          )}
                          <MetaItem>
                            <Icon icon="mdi:package-variant" width={14} />
                            {cantItems} {cantItems === 1 ? "item" : "items"}
                          </MetaItem>
                          {pedido.observaciones && (
                            <MetaItem title={pedido.observaciones}>
                              <Icon icon="mdi:note-text" width={14} />
                              {pedido.observaciones.substring(0, 40)}
                              {pedido.observaciones.length > 40 ? "..." : ""}
                            </MetaItem>
                          )}
                        </MetaRow>
                      </CardBody>

                      <CardFooter>
                        <TotalLabel>Total</TotalLabel>
                        <TotalValue>
                          {fmtMoneda(pedido.total, pedido.moneda_id)}
                        </TotalValue>
                      </CardFooter>
                    </PedidoCard>
                  );
                })}
              </PedidosList>
            )}
          </>
        )}
      </DialogContent>
    </Dialog>
  );
}

const EmptyState = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 48px 24px;
  color: ${({ theme }) => theme.textSecondary || "#999"};

  svg {
    opacity: 0.4;
  }
`;

const FiltersBar = styled.div`
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  padding: 8px 0 12px;
  position: sticky;
  top: 0;
  z-index: 1;
  background: inherit;
`;

const PedidosList = styled.div`
  display: flex;
  flex-direction: column;
  gap: 10px;
  padding: 8px 0;
`;

const PedidoCard = styled.div`
  border: 1px solid ${({ $vencido, theme }) =>
    $vencido ? "#d32f2f" : theme.color2 || "#333"};
  border-radius: 10px;
  padding: 14px 16px;
  cursor: pointer;
  transition: all 0.2s;
  background: ${({ $vencido, theme }) =>
    $vencido ? "rgba(211, 47, 47, 0.06)" : theme.bg2 || "#1e1e1e"};

  &:hover {
    border-color: ${({ theme }) => theme.primary || "#f88533"};
    background: ${({ theme }) => theme.bg3 || "#2a2a2a"};
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }
`;

const CardHeader = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
`;

const PedidoNumero = styled.span`
  font-weight: 700;
  font-size: 0.95rem;
  font-family: monospace;
`;

const CardBody = styled.div`
  display: flex;
  flex-direction: column;
  gap: 6px;
`;

const ClienteInfo = styled.div`
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 0.88rem;

  .nombre {
    font-weight: 600;
  }

  .ruc {
    color: ${({ theme }) => theme.textSecondary || "#999"};
    font-size: 0.8rem;
  }
`;

const MetaRow = styled.div`
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
`;

const MetaItem = styled.span`
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 0.78rem;
  color: ${({ theme }) => theme.textSecondary || "#999"};
`;

const CardFooter = styled.div`
  display: flex;
  justify-content: flex-end;
  align-items: baseline;
  gap: 8px;
  margin-top: 10px;
  padding-top: 8px;
  border-top: 1px solid ${({ theme }) => theme.color2 || "#333"};
`;

const TotalLabel = styled.span`
  font-size: 0.8rem;
  color: ${({ theme }) => theme.textSecondary || "#999"};
`;

const TotalValue = styled.span`
  font-size: 1.15rem;
  font-weight: 700;
  color: ${({ theme }) => theme.primary || "#f88533"};
`;
