"use client";

import { useState, useEffect, useCallback, useMemo } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { getSupabaseClient } from "@/lib/supabase";
import { Loader2, History, Plus, Minus } from "lucide-react";
import { Aviso } from "@/components/ui/aviso";

interface InventoryMovement {
  id: string;
  created_at: string;
  quantity: number;
  type: 'purchase' | 'sale' | 'adjustment_in' | 'adjustment_out' | 'return' | 'loss' | 'production';
  reference_type: string | null;
  notes: string | null;
  user_email?: string;
}

interface OptionStockRow {
  option_id: string;
  attribute_name: string;
  option_label: string;
  stock: number;
}

interface OptionStockMovement {
  id: string;
  created_at: string;
  quantity: number;
  type: "sale" | "return" | "adjustment_in" | "adjustment_out";
  reference_type: string | null;
  notes: string | null;
  balance_after: number | null;
}

interface VariationStockRow {
  id: string;
  combination: Record<string, string> | null;
  stock: number;
}

interface VariationStockMovement {
  id: string;
  created_at: string;
  quantity: number;
  type: "sale" | "return" | "adjustment_in" | "adjustment_out";
  reference_type: string | null;
  notes: string | null;
  balance_after: number | null;
  combination: Record<string, string> | null;
}

interface InventoryHistoryModalProps {
  productId: string;
  productName: string;
  currentStock: number;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onStockUpdate: (newStock: number) => void;
  onOptionStockUpdate?: (optionId: string, newStock: number) => void;
  onVariationStockUpdate?: (variationId: string, newStock: number) => void;
}

const typeLabels: Record<string, string> = {
  purchase: "Compra",
  sale: "Venda",
  adjustment_in: "Ajuste (Entrada)",
  adjustment_out: "Ajuste (Saída)",
  return: "Devolução",
  loss: "Perda/Quebra",
  production: "Produção",
};

const typeColors: Record<string, string> = {
  purchase: "text-emerald-600 bg-emerald-50",
  sale: "text-blue-600 bg-blue-50",
  adjustment_in: "text-emerald-600 bg-emerald-50",
  adjustment_out: "text-amber-600 bg-amber-50",
  return: "text-emerald-600 bg-emerald-50",
  loss: "text-rose-600 bg-rose-50",
  production: "text-purple-600 bg-purple-50",
};

type MovementPeriod = "today" | "7d" | "30d";

export function InventoryHistoryModal({
  productId,
  productName,
  currentStock,
  open,
  onOpenChange,
  onStockUpdate,
  onOptionStockUpdate,
  onVariationStockUpdate
}: InventoryHistoryModalProps) {
  /**
   * O saldo mostrado na janela.
   *
   * Ele vinha direto da prop `currentStock`, e a tela de estoque atualizava
   * outra fatia de estado ao receber `onStockUpdate`. Resultado: dar entrada
   * não mexia no número, e só fechar e abrir de novo mostrava o total certo.
   * Pior, o ajuste seguinte somava em cima do valor velho.
   *
   * Agora a janela guarda o próprio saldo e, depois de cada movimento, relê o
   * valor real do produto no banco (um gatilho mantém `products.stock` em dia).
   * Assim ela nunca faz conta em cima de um número que pode ter envelhecido.
   */
  const [saldo, setSaldo] = useState(() => Number(currentStock) || 0);
  const [saldoDeQualProduto, setSaldoDeQualProduto] = useState(productId);
  const [erroDoAjuste, setErroDoAjuste] = useState<string | null>(null);

  /* Trocar de produto (ou reabrir noutro) recarrega o saldo da prop. Ajuste de
     estado durante a renderização: efeito aqui dispararia render em cascata. */
  if (saldoDeQualProduto !== productId) {
    setSaldoDeQualProduto(productId);
    setSaldo(Number(currentStock) || 0);
  }

  const [movements, setMovements] = useState<InventoryMovement[]>([]);
  const [loading, setLoading] = useState(false);
  const [mode, setMode] = useState<"general" | "option">("general");
  const [adjusting, setAdjusting] = useState(false);
  const [adjustmentType, setAdjustmentType] = useState<'in' | 'out'>('in');
  const [adjustmentQty, setAdjustmentQty] = useState("");
  const [adjustmentNotes, setAdjustmentNotes] = useState("");
  const [optionStocks, setOptionStocks] = useState<OptionStockRow[]>([]);
  const [selectedOptionId, setSelectedOptionId] = useState("");
  const [optionMovements, setOptionMovements] = useState<OptionStockMovement[]>([]);
  const [loadingOptions, setLoadingOptions] = useState(false);
  const [loadingOptionMovements, setLoadingOptionMovements] = useState(false);
  const [optionAdjusting, setOptionAdjusting] = useState(false);
  const [optionAdjustmentType, setOptionAdjustmentType] = useState<'in' | 'out'>('in');
  const [optionAdjustmentQty, setOptionAdjustmentQty] = useState("");
  const [optionAdjustmentNotes, setOptionAdjustmentNotes] = useState("");
  const [inventoryScope, setInventoryScope] = useState<"product" | "option" | "variant">("product");
  const [variationStocks, setVariationStocks] = useState<VariationStockRow[]>([]);
  const [selectedVariationId, setSelectedVariationId] = useState("");
  const [variationMovements, setVariationMovements] = useState<VariationStockMovement[]>([]);
  const [loadingVariations, setLoadingVariations] = useState(false);
  const [loadingVariationMovements, setLoadingVariationMovements] = useState(false);
  const [variationAdjusting, setVariationAdjusting] = useState(false);
  const [variationAdjustmentType, setVariationAdjustmentType] = useState<'in' | 'out'>('in');
  const [variationAdjustmentQty, setVariationAdjustmentQty] = useState("");
  const [variationAdjustmentNotes, setVariationAdjustmentNotes] = useState("");
  const [movementPeriod, setMovementPeriod] = useState<MovementPeriod>("7d");

  const selectedOption = useMemo(
    () => optionStocks.find((row) => row.option_id === selectedOptionId) || null,
    [optionStocks, selectedOptionId]
  );
  const selectedOptionDisplayName = selectedOption
    ? `${selectedOption.attribute_name}: ${selectedOption.option_label}`
    : "Variação não identificada";
  const selectedVariation = useMemo(
    () => variationStocks.find((row) => row.id === selectedVariationId) || null,
    [selectedVariationId, variationStocks]
  );
  const selectedVariationDisplayName = useMemo(() => {
    if (!selectedVariation?.combination) return "Combinação não identificada";
    const parts = Object.entries(selectedVariation.combination)
      .map(([attribute, label]) => `${attribute}: ${label}`);
    return parts.length ? parts.join(" / ") : "Combinação não identificada";
  }, [selectedVariation]);
  const variationOverviewRows = useMemo(
    () =>
      variationStocks.map((row) => {
        const stock = Number(row.stock) || 0;
        const label = Object.entries(row.combination || {})
          .map(([attribute, optionLabel]) => `${attribute}: ${optionLabel}`)
          .join(" / ");
        const level =
          stock <= 0
            ? { tag: "Sem estoque", tagClass: "bg-rose-50 text-rose-700", stockClass: "text-rose-700" }
            : stock <= 5
              ? { tag: "Baixo", tagClass: "bg-amber-50 text-amber-700", stockClass: "text-amber-700" }
              : { tag: "OK", tagClass: "bg-emerald-50 text-emerald-700", stockClass: "text-emerald-700" };
        return {
          id: row.id,
          label: label || "Combinação não identificada",
          stock,
          ...level,
        };
      }),
    [variationStocks]
  );
  const allocatedStock = useMemo(
    () => optionStocks.reduce((acc, row) => acc + (Number.isFinite(Number(row.stock)) ? Number(row.stock) : 0), 0),
    [optionStocks]
  );
  const variationAllocatedStock = useMemo(
    () => variationStocks.reduce((acc, row) => acc + (Number.isFinite(Number(row.stock)) ? Number(row.stock) : 0), 0),
    [variationStocks]
  );
  const scopedAllocatedStock = inventoryScope === "variant" ? variationAllocatedStock : allocatedStock;
  const generalStock = saldo;
  const allocatedPct = generalStock > 0 ? (scopedAllocatedStock / generalStock) * 100 : 0;
  
  // Se a soma das variações for maior que o estoque geral (com pequena tolerância para float), é erro.
  // Se for igual (100%), é OK (tudo alocado corretamente).
  // Se for menor, é OK (parte do estoque geral ainda não foi alocada em variações, ou é produto misto).
  const allocationStatus: "ok" | "danger" =
    generalStock <= 0
      ? scopedAllocatedStock > 0
        ? "danger"
        : "ok"
      : allocatedPct > 100.01 // Margem de erro de float. > 100% é erro.
        ? "danger"
        : "ok";
  const allocationTone =
    allocationStatus === "danger"
      ? {
          card: "border-rose-200 bg-rose-50",
          label: "text-rose-600",
          value: "text-rose-700",
          hint: "text-rose-700",
          dot: "bg-rose-500",
        }
      : {
          card: "border-emerald-200 bg-emerald-50",
          label: "text-emerald-600",
          value: "text-emerald-700",
          hint: "text-emerald-600",
          dot: "bg-emerald-500",
        };
  const allocationHint =
    allocationStatus === "danger"
      ? "Alocação acima do limite do estoque geral."
      : "Alocação dentro do limite operacional.";
  const periodStartIso = useMemo(() => {
    const now = new Date();
    const start = new Date(now);
    if (movementPeriod === "today") {
      start.setHours(0, 0, 0, 0);
      return start.toISOString();
    }
    const days = movementPeriod === "7d" ? 7 : 30;
    start.setDate(start.getDate() - (days - 1));
    start.setHours(0, 0, 0, 0);
    return start.toISOString();
  }, [movementPeriod]);

  const fetchMovements = useCallback(async () => {
    setLoading(true);
    const supabase = getSupabaseClient();

    const { data, error } = await supabase
      .from('inventory_movements')
      .select('*')
      .eq('product_id', productId)
      .gte("created_at", periodStartIso)
      .order('created_at', { ascending: false })
      .limit(50);

    if (error) {
      console.error("Erro ao buscar histórico:", error);
    } else {
      setMovements(data || []);
    }
    setLoading(false);
  }, [periodStartIso, productId]);

  const fetchOptionStocks = useCallback(async () => {
    setLoadingOptions(true);
    const supabase = getSupabaseClient();
    const { data, error } = await supabase
      .from("product_option_stocks")
      .select("option_id,attribute_name,option_label,stock")
      .eq("product_id", productId)
      .eq("active", true)
      .order("attribute_name", { ascending: true })
      .order("option_label", { ascending: true });
    if (error) {
      console.error("Erro ao buscar variações de estoque:", error);
      setOptionStocks([]);
    } else {
      const rows = (data as OptionStockRow[] | null) || [];
      setOptionStocks(rows);
      if (!rows.some((row) => row.option_id === selectedOptionId)) {
        setSelectedOptionId(rows[0]?.option_id || "");
      }
    }
    setLoadingOptions(false);
  }, [productId, selectedOptionId]);

  const fetchOptionMovements = useCallback(async () => {
    if (!selectedOptionId) {
      setOptionMovements([]);
      return;
    }
    setLoadingOptionMovements(true);
    const supabase = getSupabaseClient();
    const { data, error } = await supabase
      .from("product_option_stock_movements")
      .select("id,created_at,quantity,type,reference_type,notes,balance_after")
      .eq("product_id", productId)
      .eq("option_id", selectedOptionId)
      .gte("created_at", periodStartIso)
      .order("created_at", { ascending: false })
      .limit(50);
    if (error) {
      console.error("Erro ao buscar histórico por variação:", error);
      setOptionMovements([]);
    } else {
      setOptionMovements((data as OptionStockMovement[] | null) || []);
    }
    setLoadingOptionMovements(false);
  }, [periodStartIso, productId, selectedOptionId]);

  const fetchInventoryScope = useCallback(async () => {
    const supabase = getSupabaseClient();
    const { data, error } = await supabase
      .from("products")
      .select("inventory_scope")
      .eq("id", productId)
      .single();
    if (error) {
      console.error("Erro ao buscar regra de estoque:", error);
      setInventoryScope("product");
      return;
    }
    const scope = data?.inventory_scope;
    if (scope === "option" || scope === "variant") {
      setInventoryScope(scope);
    } else {
      setInventoryScope("product");
    }
  }, [productId]);

  const fetchVariationStocks = useCallback(async () => {
    setLoadingVariations(true);
    const supabase = getSupabaseClient();
    const { data, error } = await supabase
      .from("product_variations")
      .select("id,combination,stock")
      .eq("product_id", productId)
      .eq("active", true)
      .order("created_at", { ascending: true });
    if (error) {
      console.error("Erro ao buscar combinações:", error);
      setVariationStocks([]);
    } else {
      const rows = (data as VariationStockRow[] | null) || [];
      setVariationStocks(rows);
      if (!rows.some((row) => row.id === selectedVariationId)) {
        setSelectedVariationId(rows[0]?.id || "");
      }
    }
    setLoadingVariations(false);
  }, [productId, selectedVariationId]);

  const fetchVariationMovements = useCallback(async () => {
    if (!selectedVariationId) {
      setVariationMovements([]);
      return;
    }
    setLoadingVariationMovements(true);
    const supabase = getSupabaseClient();
    const { data, error } = await supabase
      .from("product_variation_stock_movements")
      .select("id,created_at,quantity,type,reference_type,notes,balance_after,combination")
      .eq("product_id", productId)
      .eq("variation_id", selectedVariationId)
      .gte("created_at", periodStartIso)
      .order("created_at", { ascending: false })
      .limit(50);
    if (error) {
      console.error("Erro ao buscar histórico por combinação:", error);
      setVariationMovements([]);
    } else {
      setVariationMovements((data as VariationStockMovement[] | null) || []);
    }
    setLoadingVariationMovements(false);
  }, [periodStartIso, productId, selectedVariationId]);

  useEffect(() => {
    if (open && productId) {
      const handle = setTimeout(() => {
        fetchMovements();
        fetchInventoryScope();
        fetchOptionStocks();
        fetchVariationStocks();
      }, 0);
      return () => clearTimeout(handle);
    }
  }, [open, productId, fetchMovements, fetchOptionStocks, fetchInventoryScope, fetchVariationStocks]);

  useEffect(() => {
    if (!open || !productId) return;
    const handle = setTimeout(() => {
      fetchOptionMovements();
    }, 0);
    return () => clearTimeout(handle);
  }, [open, productId, fetchOptionMovements]);

  useEffect(() => {
    if (!open || !productId) return;
    const handle = setTimeout(() => {
      fetchVariationMovements();
    }, 0);
    return () => clearTimeout(handle);
  }, [open, productId, fetchVariationMovements]);

  async function handleGeneralAdjustment() {
    if (!adjustmentQty || parseFloat(adjustmentQty) <= 0) return;

    setAdjusting(true);
    const supabase = getSupabaseClient();
    const qty = parseFloat(adjustmentQty);
    const type = adjustmentType === 'in' ? 'adjustment_in' : 'adjustment_out';

    const { error } = await supabase
      .from('inventory_movements')
      .insert({
        product_id: productId,
        quantity: qty,
        type,
        reference_type: 'manual',
        notes: adjustmentNotes || 'Ajuste manual',
        user_id: (await supabase.auth.getUser()).data.user?.id
      });

    if (error) {
      setErroDoAjuste("Não foi possível registrar o ajuste: " + error.message);
    } else {
      /* O gatilho `tr_inventory_update_stock` já acertou `products.stock`.
         Reler é mais barato do que refazer a conta aqui, e é o único jeito de
         acertar quando alguém mexeu no mesmo produto em outra aba. */
      const { data: produto } = await supabase
        .from("products")
        .select("stock")
        .eq("id", productId)
        .maybeSingle();

      const novoSaldo =
        produto && produto.stock !== null && produto.stock !== undefined
          ? Number(produto.stock)
          : adjustmentType === "in"
            ? saldo + qty
            : saldo - qty;

      setSaldo(novoSaldo);
      onStockUpdate(novoSaldo);
      setErroDoAjuste(null);
      setAdjustmentQty("");
      setAdjustmentNotes("");
      fetchMovements();
    }
    setAdjusting(false);
  }

  async function handleOptionAdjustment() {
    if (!selectedOptionId) {
      setErroDoAjuste("Selecione uma variação.");
      return;
    }
    if (!optionAdjustmentQty || parseFloat(optionAdjustmentQty) <= 0) return;

    setOptionAdjusting(true);
    const supabase = getSupabaseClient();
    const qty = parseFloat(optionAdjustmentQty);
    const direction = optionAdjustmentType === "in" ? 1 : -1;
    const { data, error } = await supabase.rpc("adjust_product_option_stock", {
      p_option_id: selectedOptionId,
      p_quantity: qty,
      p_direction: direction,
      p_notes: optionAdjustmentNotes || null,
    });
    if (error) {
      setErroDoAjuste("Não foi possível ajustar a variação: " + error.message);
    } else {
      const newStock = Number(data || 0);
      setOptionStocks((prev) =>
        prev.map((row) => (row.option_id === selectedOptionId ? { ...row, stock: newStock } : row))
      );
      onOptionStockUpdate?.(selectedOptionId, newStock);
      setOptionAdjustmentQty("");
      setOptionAdjustmentNotes("");
      fetchOptionStocks();
      fetchOptionMovements();
    }
    setOptionAdjusting(false);
  }

  async function handleVariationAdjustment() {
    if (!selectedVariationId) {
      setErroDoAjuste("Selecione uma combinação.");
      return;
    }
    if (!variationAdjustmentQty || parseFloat(variationAdjustmentQty) <= 0) return;

    setVariationAdjusting(true);
    const supabase = getSupabaseClient();
    const qty = parseFloat(variationAdjustmentQty);
    const direction = variationAdjustmentType === "in" ? 1 : -1;
    const { data, error } = await supabase.rpc("adjust_product_variation_stock", {
      p_variation_id: selectedVariationId,
      p_quantity: qty,
      p_direction: direction,
      p_notes: variationAdjustmentNotes || null,
    });
    if (error) {
      setErroDoAjuste("Não foi possível ajustar a combinação: " + error.message);
    } else {
      const newStock = Number(data || 0);
      setVariationStocks((prev) =>
        prev.map((row) => (row.id === selectedVariationId ? { ...row, stock: newStock } : row))
      );
      onVariationStockUpdate?.(selectedVariationId, newStock);
      setVariationAdjustmentQty("");
      setVariationAdjustmentNotes("");
      fetchVariationStocks();
      fetchVariationMovements();
    }
    setVariationAdjusting(false);
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-3xl max-h-[85vh] flex flex-col">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <History className="w-5 h-5 text-slate-500" />
            Histórico de Estoque: {productName}
          </DialogTitle>
        </DialogHeader>

        <div className="flex-1 overflow-y-auto pr-2 space-y-6">
          <div className="flex flex-wrap items-center gap-3">
            <div className="ml-auto inline-flex rounded-xl border border-slate-200 bg-slate-50 p-1">
              <button
                type="button"
                onClick={() => setMode("general")}
                className={`px-4 py-1.5 rounded-lg text-sm font-medium transition-colors ${
                  mode === "general" ? "bg-white text-slate-800 shadow-sm" : "text-slate-500 hover:text-slate-700"
                }`}
              >
                Estoque Geral
              </button>
              <button
                type="button"
                onClick={() => setMode("option")}
                className={`px-4 py-1.5 rounded-lg text-sm font-medium transition-colors ${
                  mode === "option" ? "bg-white text-slate-800 shadow-sm" : "text-slate-500 hover:text-slate-700"
                }`}
              >
                Variações
              </button>
            </div>
            <div className="inline-flex rounded-xl border border-slate-200 bg-slate-50 p-1">
              <button
                type="button"
                onClick={() => setMovementPeriod("today")}
                className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${
                  movementPeriod === "today" ? "bg-white text-slate-800 shadow-sm" : "text-slate-500 hover:text-slate-700"
                }`}
              >
                Hoje
              </button>
              <button
                type="button"
                onClick={() => setMovementPeriod("7d")}
                className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${
                  movementPeriod === "7d" ? "bg-white text-slate-800 shadow-sm" : "text-slate-500 hover:text-slate-700"
                }`}
              >
                7 dias
              </button>
              <button
                type="button"
                onClick={() => setMovementPeriod("30d")}
                className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${
                  movementPeriod === "30d" ? "bg-white text-slate-800 shadow-sm" : "text-slate-500 hover:text-slate-700"
                }`}
              >
                30 dias
              </button>
            </div>
          </div>

          {mode === "general" ? (
            <>
              <div className="bg-slate-50 p-4 rounded-xl border border-slate-100 flex items-center justify-between">
                <div>
                  <span className="text-xs text-slate-500 uppercase tracking-wider font-medium">Saldo Atual</span>
                  <div className="text-3xl font-bold text-slate-800">{currentStock}</div>
                </div>
                {inventoryScope === "product" ? (
                  <div className="flex items-center gap-2">
                    <Button
                      size="sm"
                      variant={adjustmentType === 'in' ? "primary" : "outline"}
                      className={adjustmentType === 'in' ? "bg-emerald-600 hover:bg-emerald-700" : "text-emerald-600 border-emerald-200 hover:bg-emerald-50"}
                      onClick={() => setAdjustmentType('in')}
                    >
                      <Plus className="w-3 h-3 mr-1" /> Entrada
                    </Button>
                    <Button
                      size="sm"
                      variant={adjustmentType === 'out' ? "primary" : "outline"}
                      className={adjustmentType === 'out' ? "bg-rose-600 hover:bg-rose-700" : "text-rose-600 border-rose-200 hover:bg-rose-50"}
                      onClick={() => setAdjustmentType('out')}
                    >
                      <Minus className="w-3 h-3 mr-1" /> Saída
                    </Button>
                  </div>
                ) : (
                  <span className="text-xs text-slate-500 max-w-[220px] text-right">
                    Este total é a soma {inventoryScope === "option" ? "das opções" : "das combinações"}, calculada sozinha — ajuste pela aba Variações.
                  </span>
                )}
              </div>

              {erroDoAjuste ? (
                <Aviso tom="ruim" aoFechar={() => setErroDoAjuste(null)}>
                  {erroDoAjuste}
                </Aviso>
              ) : null}

              {inventoryScope === "product" && (
              <div className="p-4 rounded-xl border border-slate-200 bg-white shadow-sm space-y-3">
                <h4 className="text-sm font-medium text-slate-700 flex items-center gap-2">
                  {adjustmentType === 'in' ? <Plus className="w-4 h-4 text-emerald-500" /> : <Minus className="w-4 h-4 text-rose-500" />}
                  Novo Ajuste de {adjustmentType === 'in' ? 'Entrada' : 'Saída'}
                </h4>
                <div className="flex gap-3">
                  <div className="w-32">
                    <Input
                      type="number"
                      placeholder="Qtd"
                      value={adjustmentQty}
                      onChange={(e) => setAdjustmentQty(e.target.value)}
                      min="0"
                      step="0.01"
                    />
                  </div>
                  <div className="flex-1">
                    <Input
                      placeholder="Motivo (opcional)"
                      value={adjustmentNotes}
                      onChange={(e) => setAdjustmentNotes(e.target.value)}
                    />
                  </div>
                  <Button
                    onClick={handleGeneralAdjustment}
                    disabled={adjusting || !adjustmentQty}
                    className={adjustmentType === 'in' ? "bg-emerald-600 hover:bg-emerald-700" : "bg-rose-600 hover:bg-rose-700"}
                  >
                    {adjusting ? <Loader2 className="w-4 h-4 animate-spin" /> : "Confirmar"}
                  </Button>
                </div>
              </div>
              )}

              <div className="space-y-3">
                <h4 className="text-sm font-medium text-slate-500 uppercase tracking-wider">Últimas Movimentações</h4>
                {loading ? (
                  <div className="flex justify-center py-8">
                    <Loader2 className="w-6 h-6 animate-spin text-slate-300" />
                  </div>
                ) : movements.length === 0 ? (
                  <div className="text-center py-8 text-slate-400 bg-slate-50 rounded-xl border border-dashed border-slate-200">
                    Nenhuma movimentação registrada.
                  </div>
                ) : (
                  <div className="space-y-2">
                    {movements.map((move) => {
                      const isPositive = ['purchase', 'adjustment_in', 'return', 'production'].includes(move.type);
                      return (
                        <div key={move.id} className="flex items-center justify-between p-3 bg-white border border-slate-100 rounded-lg hover:border-slate-200 transition-colors">
                          <div className="flex items-center gap-3">
                            <div className={`w-8 h-8 rounded-full flex items-center justify-center ${typeColors[move.type]}`}>
                              {isPositive ? <Plus className="w-4 h-4" /> : <Minus className="w-4 h-4" />}
                            </div>
                            <div>
                              <div className="text-sm font-medium text-slate-700">
                                {typeLabels[move.type] || move.type}
                              </div>
                              <div className="text-xs text-slate-400">
                                {new Date(move.created_at).toLocaleString('pt-BR')}
                                {move.reference_type === 'order' && ' • Via Pedido'}
                              </div>
                            </div>
                          </div>
                          <div className="text-right">
                            <div className={`font-mono font-medium ${isPositive ? 'text-emerald-600' : 'text-rose-600'}`}>
                              {isPositive ? '+' : '-'}{move.quantity}
                            </div>
                            {move.notes && (
                              <div className="text-xs text-slate-400 max-w-[220px] truncate">
                                {move.notes}
                              </div>
                            )}
                          </div>
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>
            </>
          ) : (
            <>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
                <div className={`rounded-xl border p-3 ${allocationTone.card}`}>
                  <div className={`text-xs uppercase tracking-wider font-medium ${allocationTone.label}`}>Soma Alocada</div>
                  <div className={`text-2xl font-bold ${allocationTone.value}`}>{scopedAllocatedStock}</div>
                </div>
                <div className={`rounded-xl border p-3 ${allocationTone.card}`}>
                  <div className={`text-xs uppercase tracking-wider font-medium ${allocationTone.label}`}>Saldo Geral</div>
                  <div className={`text-2xl font-bold ${allocationTone.value}`}>{generalStock}</div>
                </div>
                <div className={`rounded-xl border p-3 ${allocationTone.card}`}>
                  <div className={`text-xs uppercase tracking-wider font-medium ${allocationTone.label}`}>Percentual Alocado</div>
                  <div className={`text-2xl font-bold ${allocationTone.value}`}>{allocatedPct.toFixed(1)}%</div>
                </div>
              </div>
              <div className={`flex items-center gap-2 text-sm font-medium ${allocationTone.hint}`}>
                <span className={`h-2.5 w-2.5 rounded-full ${allocationTone.dot}`} />
                <span>{allocationHint}</span>
                </div>

              {inventoryScope === "variant" ? (
                <>
                  <div className="p-4 rounded-xl border border-slate-200 bg-white shadow-sm space-y-3">
                    <div className="flex items-center justify-between">
                      <h4 className="text-sm font-medium text-slate-700">Visão rápida das combinações</h4>
                      <span className="text-xs text-slate-500">{variationOverviewRows.length} combinações</span>
                    </div>
                    <div className="max-h-56 overflow-y-auto space-y-2 pr-1">
                      {variationOverviewRows.length === 0 ? (
                        <div className="text-center py-6 text-xs text-slate-400 bg-slate-50 rounded-lg border border-dashed border-slate-200">
                          Nenhuma combinação ativa.
                        </div>
                      ) : (
                        variationOverviewRows.map((row) => (
                          <button
                            key={row.id}
                            type="button"
                            onClick={() => setSelectedVariationId(row.id)}
                            className={`w-full text-left rounded-lg border px-3 py-2 transition-colors ${
                              selectedVariationId === row.id
                                ? "border-[var(--ks-color-primary)] bg-[var(--ks-color-primary-soft)]"
                                : "border-slate-200 bg-white hover:border-slate-300"
                            }`}
                          >
                            <div className="flex items-center justify-between gap-3">
                              <div className="text-sm text-slate-700 truncate">{row.label}</div>
                              <div className="flex items-center gap-2">
                                <span className={`rounded-md px-2 py-0.5 text-[11px] font-medium ${row.tagClass}`}>{row.tag}</span>
                                <span className={`font-mono text-sm font-semibold ${row.stockClass}`}>{row.stock}</span>
                              </div>
                            </div>
                          </button>
                        ))
                      )}
                    </div>
                  </div>

                  <div className="p-4 rounded-xl border border-slate-200 bg-white shadow-sm space-y-3">
                    <div className="flex items-center gap-3">
                      <div className="min-w-56">
                        <label className="text-xs font-medium text-slate-500 uppercase tracking-wider">Combinação</label>
                        <select
                          value={selectedVariationId}
                          onChange={(e) => setSelectedVariationId(e.target.value)}
                          className="mt-1 w-full rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm text-slate-700"
                          disabled={loadingVariations || variationStocks.length === 0}
                        >
                          {variationStocks.length === 0 ? (
                            <option value="">Sem combinações ativas</option>
                          ) : (
                            variationStocks.map((row) => (
                              <option key={row.id} value={row.id}>
                                {Object.entries(row.combination || {}).map(([attribute, label]) => `${attribute}: ${label}`).join(" / ")}
                              </option>
                            ))
                          )}
                        </select>
                      </div>
                      <div className="ml-auto text-right">
                        <div className="text-xs text-slate-500 uppercase tracking-wider font-medium">Saldo da Combinação</div>
                        <div className="text-3xl font-bold text-slate-800">
                          {selectedVariation ? selectedVariation.stock : 0}
                        </div>
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      <Button
                        size="sm"
                        variant={variationAdjustmentType === 'in' ? "primary" : "outline"}
                        className={variationAdjustmentType === 'in' ? "bg-emerald-600 hover:bg-emerald-700" : "text-emerald-600 border-emerald-200 hover:bg-emerald-50"}
                        onClick={() => setVariationAdjustmentType('in')}
                      >
                        <Plus className="w-3 h-3 mr-1" /> Entrada
                      </Button>
                      <Button
                        size="sm"
                        variant={variationAdjustmentType === 'out' ? "primary" : "outline"}
                        className={variationAdjustmentType === 'out' ? "bg-rose-600 hover:bg-rose-700" : "text-rose-600 border-rose-200 hover:bg-rose-50"}
                        onClick={() => setVariationAdjustmentType('out')}
                      >
                        <Minus className="w-3 h-3 mr-1" /> Saída
                      </Button>
                    </div>
                    <div className="flex gap-3">
                      <div className="w-32">
                        <Input
                          type="number"
                          placeholder="Qtd"
                          value={variationAdjustmentQty}
                          onChange={(e) => setVariationAdjustmentQty(e.target.value)}
                          min="0"
                          step="0.01"
                        />
                      </div>
                      <div className="flex-1">
                        <Input
                          placeholder="Motivo (opcional)"
                          value={variationAdjustmentNotes}
                          onChange={(e) => setVariationAdjustmentNotes(e.target.value)}
                        />
                      </div>
                      <Button
                        onClick={handleVariationAdjustment}
                        disabled={variationAdjusting || !variationAdjustmentQty || !selectedVariationId}
                        className={variationAdjustmentType === 'in' ? "bg-emerald-600 hover:bg-emerald-700" : "bg-rose-600 hover:bg-rose-700"}
                      >
                        {variationAdjusting ? <Loader2 className="w-4 h-4 animate-spin" /> : "Confirmar"}
                      </Button>
                    </div>
                  </div>

                  <div className="space-y-3">
                    <h4 className="text-sm font-medium text-slate-500 uppercase tracking-wider">Movimentações da Combinação</h4>
                    {loadingVariationMovements || loadingVariations ? (
                      <div className="flex justify-center py-8">
                        <Loader2 className="w-6 h-6 animate-spin text-slate-300" />
                      </div>
                    ) : variationMovements.length === 0 ? (
                      <div className="text-center py-8 text-slate-400 bg-slate-50 rounded-xl border border-dashed border-slate-200">
                        Nenhuma movimentação da combinação registrada.
                      </div>
                    ) : (
                      <div className="space-y-2">
                        {variationMovements.map((move) => {
                          const isPositive = ['adjustment_in', 'return'].includes(move.type);
                          return (
                            <div key={move.id} className="flex items-center justify-between p-3 bg-white border border-slate-100 rounded-lg hover:border-slate-200 transition-colors">
                              <div className="flex items-center gap-3">
                                <div className={`w-8 h-8 rounded-full flex items-center justify-center ${typeColors[move.type]}`}>
                                  {isPositive ? <Plus className="w-4 h-4" /> : <Minus className="w-4 h-4" />}
                                </div>
                                <div>
                                  <div className="text-sm font-medium text-slate-700">
                                    {typeLabels[move.type] || move.type}
                                  </div>
                                  <div className="text-xs text-slate-500">
                                    {selectedVariationDisplayName}
                                  </div>
                                  <div className="text-xs text-slate-400">
                                    {new Date(move.created_at).toLocaleString('pt-BR')}
                                    {move.reference_type === 'order' && ' • Via Pedido'}
                                  </div>
                                </div>
                              </div>
                              <div className="text-right">
                                <div className={`font-mono font-medium ${isPositive ? 'text-emerald-600' : 'text-rose-600'}`}>
                                  {isPositive ? '+' : '-'}{move.quantity}
                                </div>
                                {typeof move.balance_after === "number" && (
                                  <div className="text-xs text-slate-500">
                                    Saldo: {move.balance_after}
                                  </div>
                                )}
                                {move.notes && (
                                  <div className="text-xs text-slate-400 max-w-[220px] truncate">
                                    {move.notes}
                                  </div>
                                )}
                              </div>
                            </div>
                          );
                        })}
                      </div>
                    )}
                  </div>
                </>
              ) : (
                <>
                  <div className="p-4 rounded-xl border border-slate-200 bg-white shadow-sm space-y-3">
                    <div className="flex items-center gap-3">
                      <div className="min-w-56">
                        <label className="text-xs font-medium text-slate-500 uppercase tracking-wider">Variação</label>
                        <select
                          value={selectedOptionId}
                          onChange={(e) => setSelectedOptionId(e.target.value)}
                          className="mt-1 w-full rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm text-slate-700"
                          disabled={loadingOptions || optionStocks.length === 0}
                        >
                          {optionStocks.length === 0 ? (
                            <option value="">Sem variações controladas</option>
                          ) : (
                            optionStocks.map((row) => (
                              <option key={row.option_id} value={row.option_id}>
                                {row.attribute_name}: {row.option_label}
                              </option>
                            ))
                          )}
                        </select>
                      </div>
                      <div className="ml-auto text-right">
                        <div className="text-xs text-slate-500 uppercase tracking-wider font-medium">Saldo da Variação</div>
                        <div className="text-3xl font-bold text-slate-800">
                          {selectedOption ? selectedOption.stock : 0}
                        </div>
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      <Button
                        size="sm"
                        variant={optionAdjustmentType === 'in' ? "primary" : "outline"}
                        className={optionAdjustmentType === 'in' ? "bg-emerald-600 hover:bg-emerald-700" : "text-emerald-600 border-emerald-200 hover:bg-emerald-50"}
                        onClick={() => setOptionAdjustmentType('in')}
                      >
                        <Plus className="w-3 h-3 mr-1" /> Entrada
                      </Button>
                      <Button
                        size="sm"
                        variant={optionAdjustmentType === 'out' ? "primary" : "outline"}
                        className={optionAdjustmentType === 'out' ? "bg-rose-600 hover:bg-rose-700" : "text-rose-600 border-rose-200 hover:bg-rose-50"}
                        onClick={() => setOptionAdjustmentType('out')}
                      >
                        <Minus className="w-3 h-3 mr-1" /> Saída
                      </Button>
                    </div>
                    <div className="flex gap-3">
                      <div className="w-32">
                        <Input
                          type="number"
                          placeholder="Qtd"
                          value={optionAdjustmentQty}
                          onChange={(e) => setOptionAdjustmentQty(e.target.value)}
                          min="0"
                          step="0.01"
                        />
                      </div>
                      <div className="flex-1">
                        <Input
                          placeholder="Motivo (opcional)"
                          value={optionAdjustmentNotes}
                          onChange={(e) => setOptionAdjustmentNotes(e.target.value)}
                        />
                      </div>
                      <Button
                        onClick={handleOptionAdjustment}
                        disabled={optionAdjusting || !optionAdjustmentQty || !selectedOptionId}
                        className={optionAdjustmentType === 'in' ? "bg-emerald-600 hover:bg-emerald-700" : "bg-rose-600 hover:bg-rose-700"}
                      >
                        {optionAdjusting ? <Loader2 className="w-4 h-4 animate-spin" /> : "Confirmar"}
                      </Button>
                    </div>
                  </div>

                  <div className="space-y-3">
                    <h4 className="text-sm font-medium text-slate-500 uppercase tracking-wider">Movimentações da Variação</h4>
                    {loadingOptionMovements || loadingOptions ? (
                      <div className="flex justify-center py-8">
                        <Loader2 className="w-6 h-6 animate-spin text-slate-300" />
                      </div>
                    ) : optionMovements.length === 0 ? (
                      <div className="text-center py-8 text-slate-400 bg-slate-50 rounded-xl border border-dashed border-slate-200">
                        Nenhuma movimentação da variação registrada.
                      </div>
                    ) : (
                      <div className="space-y-2">
                        {optionMovements.map((move) => {
                          const isPositive = ['adjustment_in', 'return'].includes(move.type);
                          return (
                            <div key={move.id} className="flex items-center justify-between p-3 bg-white border border-slate-100 rounded-lg hover:border-slate-200 transition-colors">
                              <div className="flex items-center gap-3">
                                <div className={`w-8 h-8 rounded-full flex items-center justify-center ${typeColors[move.type]}`}>
                                  {isPositive ? <Plus className="w-4 h-4" /> : <Minus className="w-4 h-4" />}
                                </div>
                                <div>
                                  <div className="text-sm font-medium text-slate-700">
                                    {typeLabels[move.type] || move.type}
                                  </div>
                                  <div className="text-xs text-slate-500">
                                    {selectedOptionDisplayName}
                                  </div>
                                  <div className="text-xs text-slate-400">
                                    {new Date(move.created_at).toLocaleString('pt-BR')}
                                    {move.reference_type === 'order' && ' • Via Pedido'}
                                  </div>
                                </div>
                              </div>
                              <div className="text-right">
                                <div className={`font-mono font-medium ${isPositive ? 'text-emerald-600' : 'text-rose-600'}`}>
                                  {isPositive ? '+' : '-'}{move.quantity}
                                </div>
                                {typeof move.balance_after === "number" && (
                                  <div className="text-xs text-slate-500">
                                    Saldo: {move.balance_after}
                                  </div>
                                )}
                                {move.notes && (
                                  <div className="text-xs text-slate-400 max-w-[220px] truncate">
                                    {move.notes}
                                  </div>
                                )}
                              </div>
                            </div>
                          );
                        })}
                      </div>
                    )}
                  </div>
                </>
              )}
            </>
          )}
        </div>
      </DialogContent>
    </Dialog>
  );
}
