
"use client";

import { useState, useEffect, useCallback } from "react";
import { Plus, Trash2, Loader2, Package, Cpu, UserCog } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { numeroDoTexto, textoDecimalValido, textoInteiroValido } from "@/components/ui/campo-decimal";
import { CustomSelect } from "@/components/ui/custom-select";
import { formatMoney } from "@/utils/formatters";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";

import { ListaDaComposicaoV2, ResumoDaComposicao, type ContextoDoProduto, type LinhaV2 } from "@/components/estoque/composicao-v2";
import { EtiquetaDaBaixa } from "@/components/estoque/primitivos";
import { resumoDaGrade, gradeValida } from "@/lib/estoque/regras";

import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";

interface ProductCompositionProps {
  productId?: string;
  onUpdateCost?: () => void;
  initialMaterials?: CompositionMaterial[];
  initialProcesses?: CompositionProcess[];
  onChangeMaterials?: (materials: CompositionMaterial[]) => void;
  onChangeProcesses?: (processes: CompositionProcess[]) => void;
  /* Empresa no estoque novo (v2): cada linha ganha "quando sai" e a etiqueta
     baixa / só custo, e o pé mostra o que sai numa venda. Fora do v2, a
     composição de sempre. */
  estoqueNovo?: boolean;
}

interface MaterialOption {
  id: string;
  name: string;
  unit?: string | null;
  cost_per_unit?: number | string | null;
  waste_pct_default?: number | string | null;
  purchase_format?: string | null;
  papel?: string | null;
  grade?: unknown;
  track_stock?: boolean | null;
}

interface MachineOption {
  id: string;
  name: string;
  hourly_cost?: number | string | null;
}

interface RoleOption {
  id: string;
  role_name: string;
  hourly_rate?: number | string | null;
}

export interface CompositionMaterial {
  id: string;
  material_id: string;
  consumption_qty: number;
  waste_pct: number;
  cost_total: number;
  /* Quantas peças saem de uma folha/chapa. Quando existe, o consumo é 1/N e a
     ficha de produção separa o teto de peças ÷ N. */
  pieces_per_unit?: number | null;
  materials?: MaterialOption;
}

export interface CompositionProcess {
  id: string;
  kind: "MACHINE" | "ROLE";
  minutes: number;
  setup_minutes: number;
  cost_total: number;
  machine_id?: string | null;
  role_id?: string | null;
  process_name?: string | null;
  machines?: MachineOption | null;
  labor_roles?: RoleOption | null;
}

interface CompositionResponse {
  materials?: CompositionMaterial[];
  processes?: CompositionProcess[];
}

interface ProcessPayload {
  kind: "MACHINE" | "ROLE";
  minutes: number;
  setup_minutes: number;
  cost_total: number;
  product_id?: string;
  machine_id?: string | null;
  role_id?: string | null;
  process_name?: string | null;
  machines?: MachineOption;
  labor_roles?: RoleOption;
}

export function ProductComposition({ 
  productId, 
  onUpdateCost, 
  initialMaterials = [], 
  initialProcesses = [],
  onChangeMaterials,
  onChangeProcesses,
  estoqueNovo = false,
}: ProductCompositionProps) {
  const toNumber = (value?: number | string | null) => Number(value ?? 0);

  const [loading, setLoading] = useState(true);
  const [materials, setMaterials] = useState<CompositionMaterial[]>(initialMaterials);
  const [processes, setProcesses] = useState<CompositionProcess[]>(initialProcesses);
  
  // Available options
  const [availableMaterials, setAvailableMaterials] = useState<MaterialOption[]>([]);
  const [availableMachines, setAvailableMachines] = useState<MachineOption[]>([]);
  const [availableRoles, setAvailableRoles] = useState<RoleOption[]>([]);

  // Form states
  const [selectedMaterialId, setSelectedMaterialId] = useState("");
  const [materialQty, setMaterialQty] = useState("1");
  /* "Peças por folha": a pergunta do jeito que a gráfica pensa. Preenchida,
     vence a quantidade — o consumo gravado vira 1/N. */
  const [piecesPerUnit, setPiecesPerUnit] = useState("");
  const [addingMaterial, setAddingMaterial] = useState(false);

  const [processType, setProcessType] = useState<"MACHINE" | "ROLE">("MACHINE");
  const [selectedProcessId, setSelectedProcessId] = useState(""); // machine_id or role_id
  const [processTime, setProcessTime] = useState("0"); // minutes
  const [setupTime, setSetupTime] = useState("0"); // minutes
  const [addingProcess, setAddingProcess] = useState(false);

  // Delete modal state
  const [deleteModalOpen, setDeleteModalOpen] = useState(false);
  const [itemToDelete, setItemToDelete] = useState<{ type: 'material' | 'process', id: string } | null>(null);
  const [deleting, setDeleting] = useState(false);
  /* Aviso na propria tela, no lugar do alert() do navegador. */
  const [aviso, setAviso] = useState<{ secao: "material" | "processo"; texto: string } | null>(null);

  /* Estoque novo: modo do produto, atributos e receitas das opções. */
  const [contexto, setContexto] = useState<ContextoDoProduto | null>(null);
  const [recarregarResumo, setRecarregarResumo] = useState(0);
  useEffect(() => {
    if (!estoqueNovo || !productId) return;
    let vivo = true;
    fetch(`/api/estoque/produto/${productId}`)
      .then((r) => (r.ok ? r.json() : null))
      .then((d) => {
        if (vivo && d?.produto) setContexto({ modo: d.produto.modo, atributos: d.atributos ?? [], receitas: d.receitas ?? [] });
      })
      .catch(() => undefined);
    return () => {
      vivo = false;
    };
  }, [estoqueNovo, productId, recarregarResumo]);

  const loadData = useCallback(async () => {
    setLoading(true);
    try {
      const promises: Promise<unknown>[] = [
        fetch('/api/production/materials?papel=insumo').then(r => r.json()),
        fetch('/api/production/operations?type=machines').then(r => r.json()),
        fetch('/api/production/operations?type=roles').then(r => r.json()),
      ];

      if (productId) {
        promises.unshift(
          fetch(`/api/production/composition?productId=${productId}`).then(async r => {
            if (!r.ok) {
              const text = await r.text();
              console.error("API Error composition:", r.status, text);
              throw new Error(`Failed to load composition: ${r.status} ${text}`);
            }
            return r.json();
          })
        );
      }

      const results = await Promise.all(promises);
      
      let compData: CompositionResponse | null = null;
      let matsData: unknown;
      let machinesData: unknown;
      let rolesData: unknown;

      if (productId) {
        const [composition, materialsData, machinesList, rolesList] =
          results as [CompositionResponse, unknown, unknown, unknown];
        compData = composition;
        matsData = materialsData;
        machinesData = machinesList;
        rolesData = rolesList;
      } else {
        const [materialsData, machinesList, rolesList] =
          results as [unknown, unknown, unknown];
        matsData = materialsData;
        machinesData = machinesList;
        rolesData = rolesList;
      }

      if (compData) {
        if (compData.materials) setMaterials(compData.materials);
        if (compData.processes) setProcesses(compData.processes);
      } else {
        // If no productId, ensure we keep initial/local state unless specifically told otherwise?
        // Actually, initialMaterials/initialProcesses are passed as props, so we used them in useState initializer.
      }

      if (Array.isArray(matsData)) setAvailableMaterials(matsData as MaterialOption[]);
      if (Array.isArray(machinesData)) setAvailableMachines(machinesData as MachineOption[]);
      if (Array.isArray(rolesData)) setAvailableRoles(rolesData as RoleOption[]);

    } catch (error) {
      console.error("Error loading composition:", error);
    } finally {
      setLoading(false);
    }
  }, [productId]);

  useEffect(() => {
    loadData();
  }, [loadData]);

  async function handleAddMaterial() {
    setAviso(null);
    if (!selectedMaterialId) {
      setAviso({ secao: "material", texto: "Selecione um material." });
      return;
    }
    if (!materialQty) {
      setAviso({ secao: "material", texto: "Informe a quantidade." });
      return;
    }
    setAddingMaterial(true);
    try {
      const material = availableMaterials.find(m => m.id === selectedMaterialId);
      if (!material) {
        setAviso({ secao: "material", texto: "Material não encontrado na lista. Tente recarregar a página." });
        return;
      }

      const rendimento = numeroDoTexto(piecesPerUnit);
      const temRendimento = Number.isFinite(rendimento) && rendimento > 0;
      const qty = temRendimento ? Math.round((1 / rendimento) * 10000) / 10000 : numeroDoTexto(materialQty);
      if (isNaN(qty) || qty <= 0) {
        setAviso({ secao: "material", texto: "Quantidade inválida." });
        return;
      }
      
      const unitCost = toNumber(material.cost_per_unit);
      const waste = toNumber(material.waste_pct_default);
      const costTotal = qty * unitCost * (1 + (waste / 100));

      if (productId) {
        const res = await fetch('/api/production/composition/materials', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            product_id: productId,
            material_id: selectedMaterialId,
            consumption_qty: qty,
            waste_pct: waste,
            cost_total: costTotal,
            pieces_per_unit: temRendimento ? rendimento : null,
            ...(estoqueNovo && gradeValida(material.grade).length ? { quando_sai: "pela_variacao" } : {}),
          })
        });

        if (!res.ok) {
          const err = await res.json();
          throw new Error(err.error || "Erro ao adicionar material");
        }
        await loadData();
        if (onUpdateCost) onUpdateCost();
        setRecarregarResumo((n) => n + 1);
      } else {
        // Local state update
        const newMaterial = {
          id: `temp_${Date.now()}`,
          material_id: selectedMaterialId,
          consumption_qty: qty,
          waste_pct: waste,
          cost_total: costTotal,
          pieces_per_unit: temRendimento ? rendimento : null,
          materials: material // Embed material details for display
        };
        const updated = [...materials, newMaterial];
        setMaterials(updated);
        if (onChangeMaterials) onChangeMaterials(updated);
      }
      
      setSelectedMaterialId("");
      setPiecesPerUnit("");
      setMaterialQty("1");
    } catch (error) {
      console.error(error);
      const message = error instanceof Error ? error.message : "Erro ao adicionar material";
      setAviso({ secao: "material", texto: message });
    } finally {
      setAddingMaterial(false);
    }
  }

  async function handleAddProcess() {
    setAviso(null);
    if (!selectedProcessId) {
      setAviso({ secao: "processo", texto: "Selecione uma máquina ou uma mão de obra." });
      return;
    }
    if (!processTime) {
      setAviso({ secao: "processo", texto: "Informe o tempo." });
      return;
    }
    setAddingProcess(true);
    try {
      const minutes = numeroDoTexto(processTime);
      const setup = numeroDoTexto(setupTime);
      
      if (isNaN(minutes) || minutes < 0) {
        setAviso({ secao: "processo", texto: "Tempo inválido." });
        return;
      }

      let costTotal = 0;
      const payload: ProcessPayload = {
        kind: processType,
        minutes: minutes,
        setup_minutes: setup,
        cost_total: 0,
      };

      if (productId) payload.product_id = productId;

      if (processType === "MACHINE") {
        const machine = availableMachines.find(m => m.id === selectedProcessId);
        if (!machine) {
          setAviso({ secao: "processo", texto: "Máquina não encontrada. Tente recarregar." });
          return;
        }
        // Cost = (Time + Setup) * (Hourly / 60)
        const hourly = toNumber(machine.hourly_cost);
        costTotal = (minutes + setup) * (hourly / 60);
        payload.machine_id = selectedProcessId;
        payload.process_name = machine.name; // Legacy support
        payload.machines = machine; // Embed for display
      } else {
        const role = availableRoles.find(r => r.id === selectedProcessId);
        if (!role) {
          setAviso({ secao: "processo", texto: "Mão de obra não encontrada. Tente recarregar." });
          return;
        }
        const hourly = toNumber(role.hourly_rate);
        costTotal = minutes * (hourly / 60);
        payload.role_id = selectedProcessId;
        payload.process_name = role.role_name; // Legacy support
        payload.labor_roles = role; // Embed for display
      }

      payload.cost_total = costTotal;

      if (productId) {
        const postPayload = { ...payload };
        if ("machines" in postPayload) delete postPayload.machines;
        if ("labor_roles" in postPayload) delete postPayload.labor_roles;
        const res = await fetch('/api/production/composition/processes', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(postPayload)
        });

        if (!res.ok) {
          const err = await res.json();
          throw new Error(err.error || "Erro ao adicionar processo");
        }
        await loadData();
        if (onUpdateCost) onUpdateCost();
      } else {
        // Local state update
        const newProcess = {
          id: `temp_${Date.now()}`,
          ...payload
        };
        const updated = [...processes, newProcess];
        setProcesses(updated);
        if (onChangeProcesses) onChangeProcesses(updated);
      }

      setSelectedProcessId("");
      setProcessTime("0");
      setSetupTime("0");
    } catch (error) {
      const err = error as Error;
      console.error(err);
      setAviso({ secao: "processo", texto: err.message || "Erro ao adicionar processo" });
    } finally {
      setAddingProcess(false);
    }
  }

  async function confirmDelete() {
    if (!itemToDelete) return;
    setDeleting(true);
    try {
      if (productId) {
        const endpoint = itemToDelete.type === 'material' 
          ? `/api/production/composition/materials?id=${itemToDelete.id}`
          : `/api/production/composition/processes?id=${itemToDelete.id}`;

        const res = await fetch(endpoint, { method: 'DELETE' });
        
        if (!res.ok) {
          const err = await res.json();
          throw new Error(err.error || "Erro ao remover item");
        }

        await loadData();
        if (onUpdateCost) onUpdateCost();
        setRecarregarResumo((n) => n + 1);
      } else {
        // Local state update
        if (itemToDelete.type === 'material') {
          const updated = materials.filter(m => m.id !== itemToDelete.id);
          setMaterials(updated);
          if (onChangeMaterials) onChangeMaterials(updated);
        } else {
          const updated = processes.filter(p => p.id !== itemToDelete.id);
          setProcesses(updated);
          if (onChangeProcesses) onChangeProcesses(updated);
        }
      }
      
      setDeleteModalOpen(false);
      setItemToDelete(null);
    } catch (error) {
      console.error(error);
      setAviso({ secao: itemToDelete?.type === "process" ? "processo" : "material", texto: "Erro ao remover o item." });
    } finally {
      setDeleting(false);
    }
  }

  async function handleDelete(e: React.MouseEvent, type: 'material' | 'process', id: string) {
    e.preventDefault();
    e.stopPropagation();
    setItemToDelete({ type, id });
    setDeleteModalOpen(true);
  }

  if (loading) return <div className="p-8 flex justify-center"><Loader2 className="animate-spin" /></div>;

  return (
    <div className="space-y-8">
      {/* Materials Section */}
      <div className="space-y-4">
        <h3 className="font-semibold text-lg flex items-center gap-2">
          <Package className="h-5 w-5 text-primary" />
          Materiais
        </h3>
        
        <div className="flex flex-wrap gap-2 items-end bg-slate-50 p-4 rounded-lg border">
          <div className="flex-1 min-w-[200px]">
            <label className="text-xs font-medium text-slate-500 mb-1 block">Insumo</label>
            <CustomSelect
              options={(estoqueNovo ? availableMaterials.filter((m) => m.papel !== "pronto") : availableMaterials).map(m => ({
                label: estoqueNovo && resumoDaGrade(m.grade) ? `${m.name} · grade ${resumoDaGrade(m.grade)}` : m.name,
                value: m.id,
              }))}
              value={selectedMaterialId}
              onChange={setSelectedMaterialId}
              placeholder="Selecione..."
            />
          </div>
          <div className="w-24">
             <label className="text-xs font-medium text-slate-500 mb-1 block">Qtd</label>
             <Input inputMode="decimal" value={materialQty} onChange={e => { if (textoDecimalValido(e.target.value)) setMaterialQty(e.target.value); }} disabled={piecesPerUnit.trim() !== ""} />
          </div>
          <div className="w-32">
             <label className="text-xs font-medium text-slate-500 mb-1 block" title="Folha, chapa, adesivo: quantas peças saem de uma unidade. Preenchido, o consumo vira 1/N e a produção separa folhas inteiras.">
               Peças por folha
             </label>
             <Input inputMode="numeric" placeholder="opcional" value={piecesPerUnit} onChange={e => { if (textoInteiroValido(e.target.value)) setPiecesPerUnit(e.target.value); }} />
          </div>
          <Button 
            type="button" 
            onClick={(e) => {
              e.preventDefault();
              e.stopPropagation();
              handleAddMaterial();
            }} 
            disabled={addingMaterial} 
            className="bg-primary text-white h-10 px-4 min-w-[3rem] flex items-center justify-center z-10 relative cursor-pointer"
          >
            {addingMaterial ? <Loader2 className="animate-spin h-4 w-4" /> : <Plus className="h-4 w-4 pointer-events-none" />}
          </Button>
        </div>

        {aviso?.secao === "material" && <p className="text-xs text-red-600">{aviso.texto}</p>}
        {estoqueNovo ? (
          <ListaDaComposicaoV2
            materiais={materials as unknown as LinhaV2[]}
            contexto={contexto}
            aoMudarLinha={(nova) => {
              setMaterials((atual) => atual.map((m) => (m.id === nova.id ? ({ ...m, ...nova } as unknown as CompositionMaterial) : m)));
              if (onUpdateCost) onUpdateCost();
              setRecarregarResumo((n) => n + 1);
            }}
            aoRemover={(e, id) => handleDelete(e, "material", id)}
          />
        ) : (
        <div className="border rounded-md overflow-hidden">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Material</TableHead>
                <TableHead className="w-24 text-right">Qtd</TableHead>
                <TableHead className="w-24 text-right">Perda</TableHead>
                <TableHead className="w-32 text-right">Custo Total</TableHead>
                <TableHead className="w-12"></TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {materials.map(m => (
                <TableRow key={m.id}>
                  <TableCell>{m.materials?.name}</TableCell>
                  <TableCell className="text-right">
                    {Number(m.pieces_per_unit) > 0
                      ? `${m.pieces_per_unit} por ${m.materials?.unit || "un"}`
                      : `${m.consumption_qty} ${m.materials?.unit || ""}`}
                  </TableCell>
                  <TableCell className="text-right">{m.waste_pct}%</TableCell>
                  <TableCell className="text-right">{formatMoney(m.cost_total)}</TableCell>
                  <TableCell>
                    <button 
                      type="button"
                      className="h-8 w-8 flex items-center justify-center rounded-full transition-colors text-red-500 hover:text-red-700 hover:bg-red-50 cursor-pointer"
                      onClick={(e) => handleDelete(e, 'material', m.id)}
                      title="Remover material"
                    >
                      <Trash2 className="h-4 w-4" />
                    </button>
                  </TableCell>
                </TableRow>
              ))}
              {materials.length === 0 && (
                <TableRow>
                  <TableCell colSpan={5} className="text-center text-slate-400 py-4">Nenhum material adicionado.</TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </div>
        )}
      </div>

      {/* Processes Section */}
      <div className="space-y-4">
        <h3 className="font-semibold text-lg flex items-center gap-2">
          <Cpu className="h-5 w-5 text-primary" />
          Processos e Mão de Obra
          {estoqueNovo ? <EtiquetaDaBaixa baixa={false} titulo="Processo e mão de obra entram no custo, nunca no estoque" /> : null}
        </h3>
        
        <div className="flex gap-2 items-end bg-slate-50 p-4 rounded-lg border flex-wrap">
          <div className="w-40">
            <label className="text-xs font-medium text-slate-500 mb-1 block">Tipo</label>
            <CustomSelect
              options={[{ label: 'Máquina', value: 'MACHINE' }, { label: 'Mão de Obra', value: 'ROLE' }]}
              value={processType}
              onChange={(val) => { setProcessType(val === "ROLE" ? "ROLE" : "MACHINE"); setSelectedProcessId(""); }}
              placeholder="Tipo"
            />
          </div>
          <div className="flex-1 min-w-[200px]">
            <label className="text-xs font-medium text-slate-500 mb-1 block">Recurso</label>
            <CustomSelect
              options={processType === 'MACHINE' 
                ? availableMachines.map(m => ({ label: m.name, value: m.id }))
                : availableRoles.map(r => ({ label: r.role_name, value: r.id }))
              }
              value={selectedProcessId}
              onChange={setSelectedProcessId}
              placeholder="Selecione..."
            />
          </div>
          <div className="w-24">
             <label className="text-xs font-medium text-slate-500 mb-1 block">Tempo (min)</label>
             <Input inputMode="decimal" value={processTime} onChange={e => { if (textoDecimalValido(e.target.value)) setProcessTime(e.target.value); }} />
          </div>
          {processType === 'MACHINE' && (
            <div className="w-24">
              <label className="text-xs font-medium text-slate-500 mb-1 block">Setup (min)</label>
              <Input inputMode="decimal" value={setupTime} onChange={e => { if (textoDecimalValido(e.target.value)) setSetupTime(e.target.value); }} />
            </div>
          )}
          <Button 
            type="button" 
            onClick={(e) => {
              e.preventDefault();
              e.stopPropagation();
              handleAddProcess();
            }} 
            disabled={addingProcess} 
            className="bg-primary text-white h-10 px-4 min-w-[3rem] flex items-center justify-center z-10 relative cursor-pointer"
          >
            {addingProcess ? <Loader2 className="animate-spin h-4 w-4" /> : <Plus className="h-4 w-4 pointer-events-none" />}
          </Button>
        </div>

        {aviso?.secao === "processo" && <p className="text-xs text-red-600">{aviso.texto}</p>}
        <div className="border rounded-md overflow-hidden">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Processo</TableHead>
                <TableHead className="w-24 text-right">Tempo</TableHead>
                <TableHead className="w-24 text-right">Setup</TableHead>
                <TableHead className="w-32 text-right">Custo Total</TableHead>
                <TableHead className="w-12"></TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {processes.map(p => (
                <TableRow key={p.id}>
                  <TableCell>
                    <div className="flex items-center gap-2">
                      {p.kind === 'MACHINE' ? <Cpu className="h-4 w-4 text-blue-500" /> : <UserCog className="h-4 w-4 text-green-500" />}
                      {p.machines?.name || p.labor_roles?.role_name || p.process_name}
                    </div>
                  </TableCell>
                  <TableCell className="text-right">{p.minutes} min</TableCell>
                  <TableCell className="text-right">{p.setup_minutes > 0 ? `${p.setup_minutes} min` : '-'}</TableCell>
                  <TableCell className="text-right">{formatMoney(p.cost_total)}</TableCell>
                  <TableCell>
                    <button 
                      type="button"
                      className="h-8 w-8 flex items-center justify-center rounded-full transition-colors text-red-500 hover:text-red-700 hover:bg-red-50 cursor-pointer"
                      onClick={(e) => handleDelete(e, 'process', p.id)}
                      title="Remover processo"
                    >
                      <Trash2 className="h-4 w-4" />
                    </button>
                  </TableCell>
                </TableRow>
              ))}
              {processes.length === 0 && (
                <TableRow>
                  <TableCell colSpan={5} className="text-center text-slate-400 py-4">Nenhum processo adicionado.</TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </div>
      </div>

      {estoqueNovo && productId && contexto ? (
        <ResumoDaComposicao produtoId={productId} contexto={contexto} recarregar={recarregarResumo} />
      ) : null}

      <Dialog open={deleteModalOpen} onOpenChange={setDeleteModalOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Confirmar exclusão</DialogTitle>
            <DialogDescription>
              Tem certeza que deseja remover este item? Esta ação não pode ser desfeita e afetará o custo total do produto.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setDeleteModalOpen(false)} disabled={deleting}>
              Cancelar
            </Button>
            <Button variant="destructive" onClick={confirmDelete} disabled={deleting}>
              {deleting ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : null}
              Remover
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}

// Force update
