import React, { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Badge } from "@/components/ui/badge";
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet";
import { Textarea } from "@/components/ui/textarea";
import { Factory, Plus, Save, PackageCheck, Boxes, ClipboardList, Users, Wrench, Network, Pencil, Eye, Trash2 } from "lucide-react";
import { toast } from "sonner";

import { useProduction } from "@/hooks/useProduction";
import { createPanelPageUrl } from "@/utils";

const getStatusBadge = (status) => {
  const normalized = String(status || "").toLowerCase();
  const map = {
    draft: "bg-gray-100 text-gray-800",
    in_progress: "bg-blue-100 text-blue-800",
    pending_consolidation: "bg-yellow-100 text-yellow-800",
    completed: "bg-emerald-100 text-emerald-800",
  };
  return map[normalized] || map.draft;
};

const parseNumericInput = (value) => (value === "" ? "" : Number(value));

const getInitialFormulaMaterialItem = () => ({
  id: "",
  idproduct: "",
  name: "",
  unit: "unit",
  quantity: 0,
  margin_percent: 0,
});
const getInitialFormulaCostItem = () => ({
  id: "",
  idproduction_cost: "",
  name: "",
  line_type: "operational",
  cost_type: "",
  unit_cost: 0,
  quantity_use: 0,
  amount: 0,
});
const getInitialConsumptionMaterial = () => ({ raw_material_id: "", lot_id: "", quantity_used: 0 });
const getInitialOutput = () => ({ warehouse_id: "", quantity: 0 });
const getInitialRawMaterialForm = () => ({
  idcategory: "",
  sku: "",
  name: "",
  description: "",
  unit: "unit",
  stock: 0,
  min_stock: 0,
  cost: 0,
});
const getInitialLineForm = () => ({ name: "", description: "" });
const getInitialOperatorForm = () => ({ idproduction_line: "", full_name: "", rut: "" });
const getInitialDirectCostForm = () => ({
  idproduction_line: "",
  name: "",
  description: "",
  unit_of_measure: "unit",
  quantity: 1,
  cost: 0,
});
const getInitialLaborForm = () => ({
  idproduction_line: "",
  role_name: "",
  cost: 0,
  cost_type: "daily",
  quantity: 1,
});
const getInitialFormulaHeader = () => ({
  code: "",
  name: "",
  description: "",
  idproduct: "",
  idproduction_line: "",
  yield_quantity: 1,
  idsupervisor: "",
});

export default function ProductionPage({ formulaView = "all" }) {
  const {
    selectedCompany,
    rawMaterials,
    costs,
    productionLines,
    productionOperators,
    productCategories,
    products,
    supervisors,
    warehouses,
    formulas,
    formulasById,
    orders,
    selectedOrderId,
    selectedOrderConsumption,
    isLoading,
    isCreatingCost,
    isCreatingRawMaterial,
    isCreatingProductionLine,
    isCreatingProductionOperator,
    isCreatingFormula,
    isUpdatingFormula,
    isDeletingFormula,
    isCreatingOrder,
    isRegisteringConsumption,
    isConsolidating,
    isExecutingInventory,
    setSelectedOrderId,
    createCost,
    createRawMaterial,
    createProductionLine,
    createProductionOperator,
    createFormula,
    updateFormula,
    deleteFormula,
    createOrder,
    registerConsumption,
    consolidateOrder,
    executeInventory,
  } = useProduction();

  const [rawMaterialForm, setRawMaterialForm] = useState(getInitialRawMaterialForm());
  const [directCostForm, setDirectCostForm] = useState(getInitialDirectCostForm());
  const [formulaTab, setFormulaTab] = useState("materials");
  const [formulaHeader, setFormulaHeader] = useState(getInitialFormulaHeader());
  const [formulaMaterialDraft, setFormulaMaterialDraft] = useState(getInitialFormulaMaterialItem());
  const [formulaDirectCostDraft, setFormulaDirectCostDraft] = useState(getInitialFormulaCostItem());
  const [formulaLaborDraft, setFormulaLaborDraft] = useState({
    ...getInitialFormulaCostItem(),
    line_type: "labor",
  });
  const [formulaMaterials, setFormulaMaterials] = useState([]);
  const [formulaDirectCosts, setFormulaDirectCosts] = useState([]);
  const [formulaLaborCosts, setFormulaLaborCosts] = useState([]);
  const [orderForm, setOrderForm] = useState({
    formula_id: "",
    planned_quantity: 0,
    production_date: new Date().toISOString().slice(0, 10),
  });
  const [consumptionForm, setConsumptionForm] = useState({
    materials: [getInitialConsumptionMaterial()],
    labor_cost: 0,
    operational_cost: 0,
  });
  const [consolidationForm, setConsolidationForm] = useState({
    outputs: [getInitialOutput()],
  });
  const [lineForm, setLineForm] = useState(getInitialLineForm());
  const [operatorForm, setOperatorForm] = useState(getInitialOperatorForm());
  const [laborForm, setLaborForm] = useState(getInitialLaborForm());
  const [mainTab, setMainTab] = useState(
    formulaView === "create" || formulaView === "list" ? "formulas" : "masters",
  );
  const [formulaSearch, setFormulaSearch] = useState("");
  const [selectedFormulaDetail, setSelectedFormulaDetail] = useState(null);
  const [isFormulaDetailOpen, setIsFormulaDetailOpen] = useState(false);
  const [loadedFormulaId, setLoadedFormulaId] = useState("");
  const searchParams = useSearchParams();
  const editingFormulaId =
    formulaView === "create" ? String(searchParams?.get("formula_id") || "").trim() : "";
  const isEditingFormula = Boolean(editingFormulaId);

  const selectedOrder = useMemo(
    () => orders.find((order) => String(order.id || "") === String(selectedOrderId || "")) || null,
    [orders, selectedOrderId],
  );

  const selectedOrderFormula = selectedOrder?.formula_id
    ? formulasById[String(selectedOrder.formula_id)]
    : null;

  const filteredFormulas = useMemo(() => {
    const term = String(formulaSearch || "").trim().toLowerCase();
    if (!term) return formulas;
    return formulas.filter((item) => {
      const code = String(item.code || "").toLowerCase();
      const name = String(item.name || "").toLowerCase();
      const productName = String(item.product?.name || "").toLowerCase();
      const lineName = String(item.line?.name || "").toLowerCase();
      return (
        code.includes(term) ||
        name.includes(term) ||
        productName.includes(term) ||
        lineName.includes(term)
      );
    });
  }, [formulas, formulaSearch]);

  const selectedFormulaMaterials = useMemo(() => {
    const rows = Array.isArray(selectedFormulaDetail?.materials) ? selectedFormulaDetail.materials : [];
    return rows.map((item) => {
      const rawMaterialId = String(item.idproduct || item.raw_material_id || "");
      const material = rawMaterials.find((row) => String(row.id) === rawMaterialId);
      return {
        id: rawMaterialId || crypto.randomUUID(),
        code: String(material?.sku || item.code || rawMaterialId || "-"),
        name: String(material?.name || item.name || "Materia prima"),
        unit: String(material?.unit || item.unit || "unit"),
        quantity: Number(item.quantity || 0),
      };
    });
  }, [selectedFormulaDetail, rawMaterials]);

  const selectedFormulaCostLines = useMemo(() => {
    const rows = Array.isArray(selectedFormulaDetail?.costs) ? selectedFormulaDetail.costs : [];
    return rows.map((item, index) => {
      const costId = String(item.idproduction_cost || item.cost_id || "");
      const costRecord = costs.find((row) => String(row.id) === costId);
      const lineType = String(item.line_type || costRecord?.type || "operational").toLowerCase();
      return {
        id: `${costId}-${index}`,
        name: String(costRecord?.name || item.name || "Costo"),
        type: lineType === "labor" ? "Mano de obra" : "Costo directo",
        costType: String(item.cost_type || costRecord?.cost_type || "-"),
        amount: Number(item.amount || 0),
      };
    });
  }, [selectedFormulaDetail, costs]);

  const operationalCosts = useMemo(
    () => costs.filter((item) => String(item.type) === "operational"),
    [costs],
  );

  const laborCosts = useMemo(
    () => costs.filter((item) => String(item.type) === "labor"),
    [costs],
  );

  const finishedProducts = useMemo(() => {
    const rawMaterialIds = new Set(rawMaterials.map((item) => String(item.id || "")));
    return products.filter((product) => {
      const productId = String(product.id || "");
      if (rawMaterialIds.has(productId)) return false;

      const normalizedType = String(product.type || product.product_type || "").toLowerCase();
      if (!normalizedType) return true;
      return normalizedType === "finished_product" || normalizedType === "finished";
    });
  }, [products, rawMaterials]);

  const getCostById = (id) => costs.find((item) => String(item.id) === String(id || ""));

  const recalculateCostLine = (line, quantityUseValue) => {
    const unitCost = Number(line.unit_cost || 0);
    const quantityUse = quantityUseValue === "" ? "" : Number(quantityUseValue || 0);
    const numericQuantityUse = Number(quantityUse || 0);
    return {
      ...line,
      quantity_use: quantityUse,
      amount: Number((unitCost * numericQuantityUse).toFixed(2)),
    };
  };

  useEffect(() => {
    if (formulaView !== "create") return;

    if (!isEditingFormula) {
      if (loadedFormulaId) {
        resetFormulaForm();
        setLoadedFormulaId("");
      }
      return;
    }

    const formula = formulasById[String(editingFormulaId)];
    if (!formula || loadedFormulaId === editingFormulaId) return;

    setFormulaHeader({
      code: String(formula.code || ""),
      name: String(formula.name || ""),
      description: String(formula.description || ""),
      idproduct: String(formula.idproduct || formula.product_id || ""),
      idproduction_line: String(formula.idproduction_line || ""),
      yield_quantity: Number(formula.yield_quantity || 1),
      idsupervisor: String(formula.idsupervisor || formula.supervisor_id || ""),
    });

    setFormulaMaterials(
      (Array.isArray(formula.materials) ? formula.materials : []).map((item) => {
        const rawMaterialId = String(item.idproduct || item.raw_material_id || "");
        const material = rawMaterials.find((row) => String(row.id) === rawMaterialId);
        return {
          id: crypto.randomUUID(),
          idproduct: rawMaterialId,
          name: String(material?.name || item.name || ""),
          unit: String(material?.unit || item.unit || "unit"),
          quantity: Number(item.quantity || 0),
          margin_percent: Number(item.margin_percent || 0),
        };
      }),
    );

    const directCosts = [];
    const laborCosts = [];
    (Array.isArray(formula.costs) ? formula.costs : []).forEach((item) => {
      const costId = String(item.idproduction_cost || item.cost_id || "");
      const costRecord = costs.find((row) => String(row.id) === costId);
      const type =
        String(item.line_type || "").toLowerCase() ||
        (String(costRecord?.type || "").toLowerCase() === "labor" ? "labor" : "operational");
      const unitCost = Number(costRecord?.cost || 0);
      const rawQuantityUse = Number(item.quantity_use || 0);
      const quantityUse =
        rawQuantityUse > 0
          ? rawQuantityUse
          : unitCost > 0
            ? Number((Number(item.amount || 0) / unitCost).toFixed(4))
            : 1;

      const row = {
        id: crypto.randomUUID(),
        idproduction_cost: costId,
        name: String(costRecord?.name || ""),
        line_type: type === "labor" ? "labor" : "operational",
        cost_type: String(item.cost_type || costRecord?.cost_type || ""),
        unit_cost: unitCost,
        quantity_use: quantityUse,
        amount: Number(item.amount || 0),
      };

      if (type === "labor") {
        laborCosts.push(row);
      } else {
        directCosts.push(row);
      }
    });

    setFormulaDirectCosts(directCosts);
    setFormulaLaborCosts(laborCosts);
    setFormulaTab("materials");
    setLoadedFormulaId(editingFormulaId);
  }, [
    formulaView,
    isEditingFormula,
    loadedFormulaId,
    editingFormulaId,
    formulasById,
    rawMaterials,
    costs,
  ]);

  const addMaterialToFormula = () => {
    if (!formulaMaterialDraft.idproduct) {
      toast.error("Selecciona una materia prima.");
      return;
    }
    if (Number(formulaMaterialDraft.quantity || 0) <= 0) {
      toast.error("La cantidad debe ser mayor a cero.");
      return;
    }
    const baseQty = Number(formulaMaterialDraft.quantity || 0);
    const margin = Number(formulaMaterialDraft.margin_percent || 0);
    const finalQty = Number((baseQty * (1 + margin / 100)).toFixed(4));
    setFormulaMaterials((prev) => [
      ...prev,
      {
        ...formulaMaterialDraft,
        id: crypto.randomUUID(),
        quantity: finalQty,
      },
    ]);
    setFormulaMaterialDraft(getInitialFormulaMaterialItem());
  };

  const addCostToFormula = (type) => {
    const draft = type === "labor" ? formulaLaborDraft : formulaDirectCostDraft;
    if (!draft.idproduction_cost) {
      toast.error("Selecciona un costo.");
      return;
    }
    if (Number(draft.quantity_use || 0) <= 0) {
      toast.error("La cantidad de uso debe ser mayor a cero.");
      return;
    }
    const row = {
      ...recalculateCostLine(draft, draft.quantity_use),
      id: crypto.randomUUID(),
      line_type: type,
    };
    if (type === "labor") {
      setFormulaLaborCosts((prev) => [...prev, row]);
      setFormulaLaborDraft({
        ...getInitialFormulaCostItem(),
        line_type: "labor",
      });
      return;
    }
    setFormulaDirectCosts((prev) => [...prev, row]);
    setFormulaDirectCostDraft(getInitialFormulaCostItem());
  };

  const removeFormulaRow = (type, rowId) => {
    if (type === "materials") {
      setFormulaMaterials((prev) => prev.filter((row) => row.id !== rowId));
      return;
    }
    if (type === "direct-costs") {
      setFormulaDirectCosts((prev) => prev.filter((row) => row.id !== rowId));
      return;
    }
    setFormulaLaborCosts((prev) => prev.filter((row) => row.id !== rowId));
  };

  const resetFormulaForm = () => {
    setFormulaHeader(getInitialFormulaHeader());
    setFormulaMaterialDraft(getInitialFormulaMaterialItem());
    setFormulaDirectCostDraft(getInitialFormulaCostItem());
    setFormulaLaborDraft({
      ...getInitialFormulaCostItem(),
      line_type: "labor",
    });
    setFormulaMaterials([]);
    setFormulaDirectCosts([]);
    setFormulaLaborCosts([]);
    setFormulaTab("materials");
  };

  const handleCreateRawMaterial = async () => {
    if (!rawMaterialForm.idcategory || !rawMaterialForm.sku.trim() || !rawMaterialForm.name.trim()) {
      toast.error("Completa categoría, SKU y nombre de la materia prima.");
      return;
    }
    try {
      await createRawMaterial({
        idcategory: rawMaterialForm.idcategory,
        sku: rawMaterialForm.sku.trim(),
        name: rawMaterialForm.name.trim(),
        description: rawMaterialForm.description?.trim() || undefined,
        unit: rawMaterialForm.unit?.trim() || "unit",
        stock: Number(rawMaterialForm.stock || 0),
        min_stock: Number(rawMaterialForm.min_stock || 0),
        cost: Number(rawMaterialForm.cost || 0),
      });
      toast.success("Materia prima creada correctamente.");
      setRawMaterialForm(getInitialRawMaterialForm());
    } catch (error) {
      toast.error(error?.message || "No se pudo crear la materia prima.");
    }
  };

  const handleCreateProductionLine = async () => {
    if (!lineForm.name.trim()) {
      toast.error("Debes ingresar el nombre de la línea.");
      return;
    }
    try {
      await createProductionLine({
        name: lineForm.name.trim(),
        description: lineForm.description?.trim() || undefined,
      });
      toast.success("Línea de producción creada.");
      setLineForm(getInitialLineForm());
    } catch (error) {
      toast.error(error?.message || "No se pudo crear la línea de producción.");
    }
  };

  const handleCreateProductionOperator = async () => {
    if (!operatorForm.rut.trim() || !operatorForm.full_name.trim() || !operatorForm.idproduction_line) {
      toast.error("Completa RUT, nombre y línea de producción del operario.");
      return;
    }
    try {
      await createProductionOperator({
        rut: operatorForm.rut.trim(),
        full_name: operatorForm.full_name.trim(),
        idproduction_line: String(operatorForm.idproduction_line),
      });
      toast.success("Operario creado correctamente.");
      setOperatorForm(getInitialOperatorForm());
    } catch (error) {
      toast.error(error?.message || "No se pudo crear el operario.");
    }
  };

  const handleCreateDirectCost = async () => {
    if (!directCostForm.name.trim()) {
      toast.error("Debes ingresar el nombre del costo.");
      return;
    }
    if (Number(directCostForm.cost || 0) <= 0) {
      toast.error("El costo debe ser mayor a cero.");
      return;
    }
    try {
      await createCost({
        type: "operational",
        idproduction_line: directCostForm.idproduction_line || undefined,
        name: directCostForm.name.trim(),
        description: directCostForm.description?.trim() || undefined,
        unit_of_measure: directCostForm.unit_of_measure || undefined,
        quantity: Number(directCostForm.quantity || 0),
        cost: Number(directCostForm.cost),
      });
      toast.success("Costo de producción registrado.");
      setDirectCostForm(getInitialDirectCostForm());
    } catch (error) {
      toast.error(error?.message || "No se pudo registrar el costo.");
    }
  };

  const handleCreateLabor = async () => {
    if (!laborForm.role_name.trim()) {
      toast.error("Debes ingresar el cargo.");
      return;
    }
    if (Number(laborForm.cost || 0) <= 0) {
      toast.error("El costo estándar debe ser mayor a cero.");
      return;
    }
    try {
      await createCost({
        type: "labor",
        idproduction_line: laborForm.idproduction_line || undefined,
        name: laborForm.role_name.trim(),
        cost_type: laborForm.cost_type,
        quantity: Number(laborForm.quantity || 1),
        cost: Number(laborForm.cost),
      });
      toast.success("Costo de mano de obra registrado.");
      setLaborForm(getInitialLaborForm());
    } catch (error) {
      toast.error(error?.message || "No se pudo registrar mano de obra.");
    }
  };

  const handleSaveFormula = async () => {
    if (!formulaHeader.idproduct || !formulaHeader.name.trim()) {
      toast.error("Completa código/nombre y producto terminado.");
      return;
    }
    const validMaterials = formulaMaterials
      .filter((item) => item.idproduct && Number(item.quantity || 0) > 0)
      .map((item) => ({
        idproduct: String(item.idproduct),
        quantity: Number(item.quantity),
      }));
    if (!validMaterials.length) {
      toast.error("Debes agregar al menos una materia prima.");
      return;
    }
    const mergedCosts = [...formulaDirectCosts, ...formulaLaborCosts];
    const validCosts = mergedCosts
      .filter((item) => item.idproduction_cost && Number(item.amount || 0) > 0)
      .map((item) => ({
        idproduction_cost: String(item.idproduction_cost),
        amount: Number(item.amount || 0),
      }));
    try {
      const payload = {
        code: formulaHeader.code?.trim() || undefined,
        name: formulaHeader.name.trim(),
        description: formulaHeader.description?.trim() || undefined,
        idproduct: formulaHeader.idproduct,
        idproduction_line: formulaHeader.idproduction_line || undefined,
        yield_quantity: Number(formulaHeader.yield_quantity || 1),
        idsupervisor: formulaHeader.idsupervisor || undefined,
        materials: validMaterials,
        costs: validCosts,
      };
      if (isEditingFormula) {
        await updateFormula(editingFormulaId, payload);
        toast.success("Fórmula actualizada correctamente.");
        setLoadedFormulaId("");
        return;
      }
      await createFormula(payload);
      toast.success("Fórmula creada correctamente.");
      resetFormulaForm();
    } catch (error) {
      toast.error(error?.message || "No se pudo guardar la fórmula.");
    }
  };

  const handleOpenFormulaDetail = (formula) => {
    setSelectedFormulaDetail(formula);
    setIsFormulaDetailOpen(true);
  };

  const handleDeleteFormula = async (formula) => {
    const formulaName = String(formula?.name || formula?.code || "");
    const confirmed = confirm(`¿Eliminar la fórmula "${formulaName}"?`);
    if (!confirmed) return;
    try {
      await deleteFormula(String(formula.id || ""));
      if (String(selectedFormulaDetail?.id || "") === String(formula.id || "")) {
        setIsFormulaDetailOpen(false);
        setSelectedFormulaDetail(null);
      }
      toast.success("Fórmula eliminada correctamente.");
    } catch (error) {
      toast.error(error?.message || "No se pudo eliminar la fórmula.");
    }
  };

  const handleCreateOrder = async () => {
    if (!orderForm.formula_id || Number(orderForm.planned_quantity || 0) <= 0 || !orderForm.production_date) {
      toast.error("Completa fórmula, cantidad estimada y fecha.");
      return;
    }
    try {
      await createOrder({
        formula_id: orderForm.formula_id,
        planned_quantity: Number(orderForm.planned_quantity),
        production_date: orderForm.production_date,
      });
      toast.success("Orden de producción creada.");
      setOrderForm({
        formula_id: "",
        planned_quantity: 0,
        production_date: new Date().toISOString().slice(0, 10),
      });
    } catch (error) {
      toast.error(error?.message || "No se pudo crear la orden.");
    }
  };

  const handleRegisterConsumption = async () => {
    if (!selectedOrderId) {
      toast.error("Selecciona una orden para registrar consumo.");
      return;
    }
    const validMaterials = consumptionForm.materials
      .filter((item) => item.raw_material_id && Number(item.quantity_used || 0) > 0)
      .map((item) => ({
        raw_material_id: String(item.raw_material_id),
        lot_id: item.lot_id ? String(item.lot_id) : undefined,
        quantity_used: Number(item.quantity_used),
      }));
    if (!validMaterials.length) {
      toast.error("Debes registrar al menos un consumo real.");
      return;
    }
    try {
      await registerConsumption(selectedOrderId, {
        materials: validMaterials,
        labor_cost: Number(consumptionForm.labor_cost || 0),
        operational_cost: Number(consumptionForm.operational_cost || 0),
      });
      toast.success("Consumo real registrado.");
    } catch (error) {
      toast.error(error?.message || "No se pudo registrar el consumo.");
    }
  };

  const handleConsolidate = async () => {
    if (!selectedOrderId) {
      toast.error("Selecciona una orden para consolidar.");
      return;
    }
    const validOutputs = consolidationForm.outputs
      .filter((item) => item.warehouse_id && Number(item.quantity || 0) > 0)
      .map((item) => ({
        warehouse_id: String(item.warehouse_id),
        quantity: Number(item.quantity),
      }));
    if (!validOutputs.length) {
      toast.error("Debes agregar al menos una bodega destino.");
      return;
    }
    try {
      await consolidateOrder(selectedOrderId, validOutputs);
      toast.success("Orden consolidada correctamente.");
    } catch (error) {
      toast.error(error?.message || "No se pudo consolidar la orden.");
    }
  };

  const handleInventoryEntry = async () => {
    if (!selectedOrderId) {
      toast.error("Selecciona una orden.");
      return;
    }
    try {
      await executeInventory(selectedOrderId);
      toast.success("Ingreso a inventario ejecutado.");
    } catch (error) {
      toast.error(error?.message || "No se pudo ejecutar el ingreso a inventario.");
    }
  };

  if (isLoading) {
    return (
      <div className="p-8">
        <div className="animate-pulse space-y-4">
          <div className="h-8 w-64 rounded bg-gray-200" />
          <div className="h-40 rounded bg-gray-200" />
          <div className="h-40 rounded bg-gray-200" />
        </div>
      </div>
    );
  }

  if (formulaView === "list") {
    return (
      <div className="p-4 lg:p-8 space-y-6">
        <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-3">
          <div>
            <h1 className="text-3xl font-bold text-gradient">Listado de Fórmulas</h1>
            <p className="text-gray-600 mt-1">{selectedCompany?.name}</p>
          </div>
          <Button asChild>
            <Link href={createPanelPageUrl("production/formulas/create")}>
              <Plus className="w-4 h-4 mr-2" />
              Crear Fórmula
            </Link>
          </Button>
        </div>

        <Card>
          <CardContent className="pt-6">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
              <div className="md:col-span-2">
                <Label>Buscar fórmula</Label>
                <Input
                  value={formulaSearch}
                  onChange={(e) => setFormulaSearch(e.target.value)}
                  placeholder="Código, nombre, producto o línea"
                />
              </div>
              <div>
                <Label>Resultados</Label>
                <Input value={filteredFormulas.length} readOnly className="bg-gray-50" />
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Fórmulas registradas</CardTitle>
          </CardHeader>
          <CardContent className="space-y-3">
            {filteredFormulas.length === 0 ? (
              <div className="rounded border border-dashed p-6 text-center">
                <p className="text-sm text-gray-500">No hay fórmulas para los filtros aplicados.</p>
              </div>
            ) : (
              filteredFormulas.map((formula) => {
                const materialCount = Array.isArray(formula.materials) ? formula.materials.length : 0;
                const costLines = Array.isArray(formula.costs) ? formula.costs : [];
                const totalCost = costLines.reduce((acc, line) => acc + Number(line.amount || 0), 0);
                return (
                  <div key={String(formula.id)} className="rounded border p-4">
                    <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-2">
                      <div>
                        <p className="font-semibold">
                          {formula.code ? `${formula.code} - ` : ""}
                          {formula.name || "Fórmula sin nombre"}
                        </p>
                        <p className="text-sm text-gray-500">
                          Producto: {formula.product?.name || "-"} | Línea: {formula.line?.name || "-"}
                        </p>
                      </div>
                      <div className="flex items-center gap-2">
                        <Badge className="bg-blue-100 text-blue-800 w-fit">
                          Batch: {Number(formula.yield_quantity || 0).toLocaleString("es-CL")}
                        </Badge>
                        <Button size="sm" variant="outline" onClick={() => handleOpenFormulaDetail(formula)}>
                          <Eye className="w-3 h-3 mr-1" />
                          Detalle
                        </Button>
                        <Button asChild size="sm" variant="outline">
                          <Link href={createPanelPageUrl(`production/formulas/create?formula_id=${formula.id}`)}>
                            <Pencil className="w-3 h-3 mr-1" />
                            Editar
                          </Link>
                        </Button>
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => void handleDeleteFormula(formula)}
                          disabled={isDeletingFormula}
                        >
                          <Trash2 className="w-3 h-3 mr-1 text-red-500" />
                          Eliminar
                        </Button>
                      </div>
                    </div>
                    <div className="grid grid-cols-2 md:grid-cols-4 gap-2 mt-3 text-sm">
                      <div className="rounded bg-gray-50 p-2">
                        <p className="text-gray-500">Materias primas</p>
                        <p className="font-semibold">{materialCount}</p>
                      </div>
                      <div className="rounded bg-gray-50 p-2">
                        <p className="text-gray-500">Líneas de costo</p>
                        <p className="font-semibold">{costLines.length}</p>
                      </div>
                      <div className="rounded bg-gray-50 p-2">
                        <p className="text-gray-500">Costo total</p>
                        <p className="font-semibold">${Number(totalCost).toLocaleString("es-CL")}</p>
                      </div>
                      <div className="rounded bg-gray-50 p-2">
                        <p className="text-gray-500">Supervisor</p>
                        <p className="font-semibold">{formula.supervisor?.name || formula.supervisor?.user_name || "-"}</p>
                      </div>
                    </div>
                  </div>
                );
              })
            )}
          </CardContent>
        </Card>

        <Sheet
          open={isFormulaDetailOpen}
          onOpenChange={(open) => {
            setIsFormulaDetailOpen(open);
            if (!open) setSelectedFormulaDetail(null);
          }}
        >
          <SheetContent side="right" className="w-full sm:max-w-5xl overflow-y-auto">
            <SheetHeader>
              <SheetTitle>Detalle de Fórmula de Producción</SheetTitle>
              <SheetDescription>
                Información completa de cabecera, materias primas y costos asociados.
              </SheetDescription>
            </SheetHeader>

            {selectedFormulaDetail ? (
              <div className="space-y-4 mt-4">
                <Card>
                  <CardHeader>
                    <CardTitle>Cabecera</CardTitle>
                  </CardHeader>
                  <CardContent className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3 text-sm">
                    <div className="rounded bg-gray-50 p-3">
                      <p className="text-gray-500">Código</p>
                      <p className="font-semibold">{selectedFormulaDetail.code || "-"}</p>
                    </div>
                    <div className="rounded bg-gray-50 p-3">
                      <p className="text-gray-500">Nombre</p>
                      <p className="font-semibold">{selectedFormulaDetail.name || "-"}</p>
                    </div>
                    <div className="rounded bg-gray-50 p-3">
                      <p className="text-gray-500">Batch</p>
                      <p className="font-semibold">
                        {Number(selectedFormulaDetail.yield_quantity || 0).toLocaleString("es-CL")}
                      </p>
                    </div>
                    <div className="rounded bg-gray-50 p-3">
                      <p className="text-gray-500">Producto terminado</p>
                      <p className="font-semibold">{selectedFormulaDetail.product?.name || "-"}</p>
                    </div>
                    <div className="rounded bg-gray-50 p-3">
                      <p className="text-gray-500">Línea de producción</p>
                      <p className="font-semibold">{selectedFormulaDetail.line?.name || "-"}</p>
                    </div>
                    <div className="rounded bg-gray-50 p-3">
                      <p className="text-gray-500">Supervisor</p>
                      <p className="font-semibold">
                        {selectedFormulaDetail.supervisor?.name || selectedFormulaDetail.supervisor?.user_name || "-"}
                      </p>
                    </div>
                    <div className="rounded bg-gray-50 p-3 md:col-span-2 lg:col-span-3">
                      <p className="text-gray-500">Descripción</p>
                      <p className="font-semibold">{selectedFormulaDetail.description || "-"}</p>
                    </div>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader>
                    <CardTitle>Materias Primas</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-2">
                    {selectedFormulaMaterials.length === 0 ? (
                      <p className="text-sm text-gray-500">No hay materias primas asociadas.</p>
                    ) : (
                      <div className="overflow-x-auto">
                        <table className="min-w-full text-sm">
                          <thead>
                            <tr className="border-b text-left">
                              <th className="py-2 pr-3">Código</th>
                              <th className="py-2 pr-3">Descripción</th>
                              <th className="py-2 pr-3">Unidad</th>
                              <th className="py-2 pr-3">Cantidad</th>
                            </tr>
                          </thead>
                          <tbody>
                            {selectedFormulaMaterials.map((item) => (
                              <tr key={item.id} className="border-b last:border-b-0">
                                <td className="py-2 pr-3">{item.code}</td>
                                <td className="py-2 pr-3">{item.name}</td>
                                <td className="py-2 pr-3">{item.unit}</td>
                                <td className="py-2 pr-3">{Number(item.quantity || 0).toLocaleString("es-CL")}</td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                    )}
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader>
                    <CardTitle>Costos</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-2">
                    {selectedFormulaCostLines.length === 0 ? (
                      <p className="text-sm text-gray-500">No hay costos asociados.</p>
                    ) : (
                      <div className="overflow-x-auto">
                        <table className="min-w-full text-sm">
                          <thead>
                            <tr className="border-b text-left">
                              <th className="py-2 pr-3">Tipo</th>
                              <th className="py-2 pr-3">Detalle</th>
                              <th className="py-2 pr-3">Condición</th>
                              <th className="py-2 pr-3">Monto</th>
                            </tr>
                          </thead>
                          <tbody>
                            {selectedFormulaCostLines.map((item) => (
                              <tr key={item.id} className="border-b last:border-b-0">
                                <td className="py-2 pr-3">{item.type}</td>
                                <td className="py-2 pr-3">{item.name}</td>
                                <td className="py-2 pr-3">{item.costType}</td>
                                <td className="py-2 pr-3">${Number(item.amount || 0).toLocaleString("es-CL")}</td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                    )}
                  </CardContent>
                </Card>
              </div>
            ) : null}
          </SheetContent>
        </Sheet>
      </div>
    );
  }

  if (formulaView === "create") {
    return (
      <div className="p-4 lg:p-8 space-y-6">
        <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-3">
          <div>
            <h1 className="text-3xl font-bold text-gradient">
              {isEditingFormula ? "Editar Fórmula de Producción" : "Crear Fórmula de Producción"}
            </h1>
            <p className="text-gray-600 mt-1">{selectedCompany?.name}</p>
          </div>
          <Button asChild variant="outline">
            <Link href={createPanelPageUrl("production/formulas/list")}>Ir a listado</Link>
          </Button>
        </div>

        <Card>
          <CardHeader>
            <CardTitle>Datos de cabecera</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
              <div>
                <Label>Código de fórmula</Label>
                <Input
                  value={formulaHeader.code}
                  onChange={(e) => setFormulaHeader((prev) => ({ ...prev, code: e.target.value }))}
                  placeholder="F-GEN-0001"
                />
              </div>
              <div>
                <Label>Nombre fórmula</Label>
                <Input
                  value={formulaHeader.name}
                  onChange={(e) => setFormulaHeader((prev) => ({ ...prev, name: e.target.value }))}
                  placeholder="Ej: Receta Shampoo 250ml"
                />
              </div>
              <div>
                <Label>Descripción</Label>
                <Input
                  value={formulaHeader.description}
                  onChange={(e) => setFormulaHeader((prev) => ({ ...prev, description: e.target.value }))}
                  placeholder="Descripción"
                />
              </div>
              <div>
                <Label>Producto terminado</Label>
                <Select
                  value={formulaHeader.idproduct}
                  onValueChange={(value) => setFormulaHeader((prev) => ({ ...prev, idproduct: value }))}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Seleccionar producto" />
                  </SelectTrigger>
                  <SelectContent>
                    {finishedProducts.map((product) => (
                      <SelectItem key={String(product.id)} value={String(product.id)}>
                        {product.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label>Cantidad óptima (batch)</Label>
                <Input
                  type="number"
                  min="0.0001"
                  step="0.0001"
                  value={formulaHeader.yield_quantity}
                  onChange={(e) =>
                    setFormulaHeader((prev) => ({ ...prev, yield_quantity: parseNumericInput(e.target.value) }))
                  }
                  placeholder="Cantidad óptima"
                />
              </div>
              <div>
                <Label>Línea de producción</Label>
                <Select
                  value={formulaHeader.idproduction_line}
                  onValueChange={(value) =>
                    setFormulaHeader((prev) => ({ ...prev, idproduction_line: value }))
                  }
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Seleccionar línea (opcional)" />
                  </SelectTrigger>
                  <SelectContent>
                    {productionLines.map((line) => (
                      <SelectItem key={String(line.id)} value={String(line.id)}>
                        {line.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label>Supervisor</Label>
                <Select
                  value={formulaHeader.idsupervisor}
                  onValueChange={(value) => setFormulaHeader((prev) => ({ ...prev, idsupervisor: value }))}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Seleccionar supervisor" />
                  </SelectTrigger>
                  <SelectContent>
                    {supervisors.map((supervisor) => (
                      <SelectItem key={String(supervisor.id)} value={String(supervisor.id)}>
                        {supervisor.user_name || supervisor.name || supervisor.email || `Usuario ${supervisor.id}`}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>

            <Tabs value={formulaTab} onValueChange={setFormulaTab} className="w-full">
              <TabsList className="grid w-full grid-cols-3">
                <TabsTrigger value="materials">Materias Primas</TabsTrigger>
                <TabsTrigger value="direct-costs">Costos Directos</TabsTrigger>
                <TabsTrigger value="labor">Mano de Obra</TabsTrigger>
              </TabsList>

              <TabsContent value="materials" className="mt-4 space-y-3">
                <div className="grid grid-cols-1 md:grid-cols-5 gap-3">
                  <div className="md:col-span-2">
                    <Label>Materia prima</Label>
                    <Select
                      value={formulaMaterialDraft.idproduct}
                      onValueChange={(value) => {
                        const material = rawMaterials.find((item) => String(item.id) === String(value));
                        setFormulaMaterialDraft((prev) => ({
                          ...prev,
                          idproduct: value,
                          name: material?.name || "",
                          unit: material?.unit || "unit",
                        }));
                      }}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Seleccionar materia prima" />
                      </SelectTrigger>
                      <SelectContent>
                        {rawMaterials.map((material) => (
                          <SelectItem key={String(material.id)} value={String(material.id)}>
                            {material.name}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                  <div>
                    <Label>Unidad</Label>
                    <Input value={formulaMaterialDraft.unit} readOnly className="bg-gray-50" />
                  </div>
                  <div>
                    <Label>Cantidad</Label>
                    <Input
                      type="number"
                      min="0"
                      step="0.0001"
                      value={formulaMaterialDraft.quantity}
                      onChange={(e) =>
                        setFormulaMaterialDraft((prev) => ({ ...prev, quantity: parseNumericInput(e.target.value) }))
                      }
                    />
                  </div>
                  <div>
                    <Label>Margen (%)</Label>
                    <Input
                      type="number"
                      value={formulaMaterialDraft.margin_percent}
                      onChange={(e) =>
                        setFormulaMaterialDraft((prev) => ({
                          ...prev,
                          margin_percent: parseNumericInput(e.target.value),
                        }))
                      }
                    />
                  </div>
                </div>
                <Button type="button" onClick={addMaterialToFormula}>
                  <Plus className="w-4 h-4 mr-2" />
                  Agregar
                </Button>
                <div className="space-y-2">
                  {formulaMaterials.length === 0 ? (
                    <p className="text-sm text-gray-500">Sin materias primas agregadas.</p>
                  ) : (
                    formulaMaterials.map((row) => (
                      <div key={row.id} className="rounded border p-2 text-sm flex items-center justify-between">
                        <span>
                          {row.name} | {row.quantity} {row.unit}
                        </span>
                        <Button variant="outline" size="sm" onClick={() => removeFormulaRow("materials", row.id)}>
                          Eliminar
                        </Button>
                      </div>
                    ))
                  )}
                </div>
              </TabsContent>

              <TabsContent value="direct-costs" className="mt-4 space-y-3">
                <div className="grid grid-cols-1 md:grid-cols-4 gap-3">
                  <div className="md:col-span-2">
                    <Label>Costo directo</Label>
                    <Select
                      value={formulaDirectCostDraft.idproduction_cost}
                      onValueChange={(value) => {
                        const selected = getCostById(value);
                        setFormulaDirectCostDraft((prev) => ({
                          ...prev,
                          idproduction_cost: value,
                          name: selected?.name || "",
                          unit_cost: Number(selected?.cost || 0),
                          quantity_use: 1,
                          amount: Number(selected?.cost || 0),
                          cost_type: selected?.cost_type || "",
                          line_type: "operational",
                        }));
                      }}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Seleccionar costo directo" />
                      </SelectTrigger>
                      <SelectContent>
                        {operationalCosts.map((cost) => (
                          <SelectItem key={String(cost.id)} value={String(cost.id)}>
                            {cost.name}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                  <div>
                    <Label>Costo unitario</Label>
                    <Input value={formulaDirectCostDraft.unit_cost} readOnly className="bg-gray-50" />
                  </div>
                  <div>
                    <Label>Cantidad de uso</Label>
                    <Input
                      type="number"
                      min="0"
                      step="0.0001"
                      value={formulaDirectCostDraft.quantity_use}
                      onChange={(e) =>
                        setFormulaDirectCostDraft((prev) =>
                          recalculateCostLine(prev, e.target.value),
                        )
                      }
                    />
                  </div>
                  <div>
                    <Label>Costo total</Label>
                    <Input value={formulaDirectCostDraft.amount} readOnly className="bg-gray-50" />
                  </div>
                </div>
                <Button type="button" onClick={() => addCostToFormula("operational")}>
                  <Plus className="w-4 h-4 mr-2" />
                  Agregar
                </Button>
                <div className="space-y-2">
                  {formulaDirectCosts.length === 0 ? (
                    <p className="text-sm text-gray-500">Sin costos directos agregados.</p>
                  ) : (
                    formulaDirectCosts.map((row) => (
                      <div key={row.id} className="rounded border p-2 text-sm flex items-center justify-between">
                        <span>
                          {row.name} | Cant: {row.quantity_use} | Total: $
                          {Number(row.amount || 0).toLocaleString("es-CL")}
                        </span>
                        <Button variant="outline" size="sm" onClick={() => removeFormulaRow("direct-costs", row.id)}>
                          Eliminar
                        </Button>
                      </div>
                    ))
                  )}
                </div>
              </TabsContent>

              <TabsContent value="labor" className="mt-4 space-y-3">
                <div className="grid grid-cols-1 md:grid-cols-4 gap-3">
                  <div className="md:col-span-2">
                    <Label>Cargo</Label>
                    <Select
                      value={formulaLaborDraft.idproduction_cost}
                      onValueChange={(value) => {
                        const selected = getCostById(value);
                        setFormulaLaborDraft((prev) => ({
                          ...prev,
                          idproduction_cost: value,
                          name: selected?.name || "",
                          unit_cost: Number(selected?.cost || 0),
                          quantity_use: Number(selected?.quantity || 1),
                          amount: Number((Number(selected?.cost || 0) * Number(selected?.quantity || 1)).toFixed(2)),
                          cost_type: selected?.cost_type || "",
                          line_type: "labor",
                        }));
                      }}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Seleccionar cargo" />
                      </SelectTrigger>
                      <SelectContent>
                        {laborCosts.map((cost) => (
                          <SelectItem key={String(cost.id)} value={String(cost.id)}>
                            {cost.name}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                  <div>
                    <Label>Tipo costo</Label>
                    <Input value={formulaLaborDraft.cost_type || "-"} readOnly className="bg-gray-50" />
                  </div>
                  <div>
                    <Label>Costo estándar</Label>
                    <Input value={formulaLaborDraft.unit_cost} readOnly className="bg-gray-50" />
                  </div>
                  <div>
                    <Label>Cantidad</Label>
                    <Input
                      type="number"
                      min="0"
                      step="0.0001"
                      value={formulaLaborDraft.quantity_use}
                      onChange={(e) =>
                        setFormulaLaborDraft((prev) => recalculateCostLine(prev, e.target.value))
                      }
                    />
                  </div>
                  <div>
                    <Label>Subtotal</Label>
                    <Input value={formulaLaborDraft.amount} readOnly className="bg-gray-50" />
                  </div>
                </div>
                <Button type="button" onClick={() => addCostToFormula("labor")}>
                  <Plus className="w-4 h-4 mr-2" />
                  Agregar
                </Button>
                <div className="space-y-2">
                  {formulaLaborCosts.length === 0 ? (
                    <p className="text-sm text-gray-500">Sin mano de obra agregada.</p>
                  ) : (
                    formulaLaborCosts.map((row) => (
                      <div key={row.id} className="rounded border p-2 text-sm flex items-center justify-between">
                        <span>
                          {row.name} | {row.cost_type || "-"} | Cant: {row.quantity_use} | Subtotal: $
                          {Number(row.amount || 0).toLocaleString("es-CL")}
                        </span>
                        <Button variant="outline" size="sm" onClick={() => removeFormulaRow("labor", row.id)}>
                          Eliminar
                        </Button>
                      </div>
                    ))
                  )}
                </div>
              </TabsContent>
            </Tabs>

            <Button onClick={handleSaveFormula} disabled={isCreatingFormula || isUpdatingFormula}>
              <Save className="w-4 h-4 mr-2" />
              {isCreatingFormula || isUpdatingFormula
                ? "Guardando..."
                : isEditingFormula
                  ? "Actualizar fórmula"
                  : "Guardar fórmula"}
            </Button>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="p-4 lg:p-8 space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-gradient flex items-center gap-2">
            <Factory className="w-8 h-8" />
            Producción
          </h1>
          <p className="text-gray-600 mt-1">{selectedCompany?.name}</p>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card>
          <CardContent className="pt-6">
            <p className="text-sm text-gray-500">Materias primas</p>
            <p className="text-2xl font-bold">{rawMaterials.length}</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="pt-6">
            <p className="text-sm text-gray-500">Fórmulas</p>
            <p className="text-2xl font-bold">{formulas.length}</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="pt-6">
            <p className="text-sm text-gray-500">Órdenes</p>
            <p className="text-2xl font-bold">{orders.length}</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="pt-6">
            <p className="text-sm text-gray-500">Costos configurados</p>
            <p className="text-2xl font-bold">{costs.length}</p>
          </CardContent>
        </Card>
      </div>

      <Tabs value={mainTab} onValueChange={setMainTab} className="w-full">
        <TabsList className="grid w-full grid-cols-4">
          <TabsTrigger value="masters">Maestros</TabsTrigger>
          <TabsTrigger value="formulas">Fórmulas</TabsTrigger>
          <TabsTrigger value="orders">Órdenes</TabsTrigger>
          <TabsTrigger value="execution">Consumo y Consolidación</TabsTrigger>
        </TabsList>

        <TabsContent value="masters" className="space-y-4 mt-4">
          <Tabs defaultValue="raw-materials" className="w-full">
            <TabsList className="grid w-full grid-cols-5">
              <TabsTrigger value="raw-materials">Materias Primas</TabsTrigger>
              <TabsTrigger value="production-lines">Líneas de Producción</TabsTrigger>
              <TabsTrigger value="direct-costs">Costos Directos</TabsTrigger>
              <TabsTrigger value="labor">Mano de Obra</TabsTrigger>
              <TabsTrigger value="operators">Operarios</TabsTrigger>
            </TabsList>

            <TabsContent value="raw-materials" className="mt-4">
              <Card>
                <CardHeader>
                  <CardTitle>Crear materia prima</CardTitle>
                </CardHeader>
                <CardContent className="space-y-3">
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
                    <div>
                      <Label>Categoría</Label>
                      <Select
                        value={rawMaterialForm.idcategory}
                        onValueChange={(value) =>
                          setRawMaterialForm((prev) => ({ ...prev, idcategory: value }))
                        }
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="Seleccionar categoría" />
                        </SelectTrigger>
                        <SelectContent>
                          {productCategories.map((category) => (
                            <SelectItem key={String(category.id)} value={String(category.id)}>
                              {category.name}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                    <div>
                      <Label>SKU</Label>
                      <Input
                        value={rawMaterialForm.sku}
                        onChange={(e) =>
                          setRawMaterialForm((prev) => ({ ...prev, sku: e.target.value }))
                        }
                        placeholder="Código/SKU"
                      />
                    </div>
                    <div>
                      <Label>Nombre</Label>
                      <Input
                        value={rawMaterialForm.name}
                        onChange={(e) =>
                          setRawMaterialForm((prev) => ({ ...prev, name: e.target.value }))
                        }
                        placeholder="Nombre materia prima"
                      />
                    </div>
                    <div className="md:col-span-2">
                      <Label>Descripción</Label>
                      <Input
                        value={rawMaterialForm.description}
                        onChange={(e) =>
                          setRawMaterialForm((prev) => ({ ...prev, description: e.target.value }))
                        }
                        placeholder="Descripción"
                      />
                    </div>
                    <div>
                      <Label>Unidad</Label>
                      <Input
                        value={rawMaterialForm.unit}
                        onChange={(e) =>
                          setRawMaterialForm((prev) => ({ ...prev, unit: e.target.value }))
                        }
                        placeholder="kg, lt, unidad"
                      />
                    </div>
                    <div>
                      <Label>Stock inicial</Label>
                      <Input
                        type="number"
                        min="0"
                        value={rawMaterialForm.stock}
                        onChange={(e) =>
                          setRawMaterialForm((prev) => ({
                            ...prev,
                            stock: parseNumericInput(e.target.value),
                          }))
                        }
                      />
                    </div>
                    <div>
                      <Label>Stock mínimo</Label>
                      <Input
                        type="number"
                        min="0"
                        value={rawMaterialForm.min_stock}
                        onChange={(e) =>
                          setRawMaterialForm((prev) => ({
                            ...prev,
                            min_stock: parseNumericInput(e.target.value),
                          }))
                        }
                      />
                    </div>
                    <div>
                      <Label>Costo</Label>
                      <Input
                        type="number"
                        min="0"
                        step="0.01"
                        value={rawMaterialForm.cost}
                        onChange={(e) =>
                          setRawMaterialForm((prev) => ({
                            ...prev,
                            cost: parseNumericInput(e.target.value),
                          }))
                        }
                      />
                    </div>
                  </div>
                  <Button onClick={handleCreateRawMaterial} disabled={isCreatingRawMaterial}>
                    <Plus className="w-4 h-4 mr-2" />
                    {isCreatingRawMaterial ? "Guardando..." : "Agregar materia prima"}
                  </Button>
                </CardContent>
              </Card>

              <Card className="mt-4">
                <CardHeader>
                  <CardTitle>Materias primas disponibles</CardTitle>
                </CardHeader>
                <CardContent className="space-y-2">
                  {rawMaterials.length === 0 ? (
                    <p className="text-sm text-gray-500">No hay materias primas disponibles.</p>
                  ) : (
                    rawMaterials.map((material) => (
                      <div key={String(material.id)} className="flex justify-between p-2 rounded bg-gray-50 text-sm">
                        <span>{material.name}</span>
                        <span className="font-semibold">
                          {Number(material.stock || 0).toLocaleString("es-CL")} {material.unit || ""}
                        </span>
                      </div>
                    ))
                  )}
                </CardContent>
              </Card>
            </TabsContent>

            <TabsContent value="production-lines" className="mt-4">
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Network className="w-5 h-5" />
                    Líneas de Producción
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-3">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                    <div>
                      <Label>Nombre</Label>
                      <Input
                        value={lineForm.name}
                        onChange={(e) => setLineForm((prev) => ({ ...prev, name: e.target.value }))}
                        placeholder="Ej: Línea Envasado"
                      />
                    </div>
                    <div>
                      <Label>Descripción</Label>
                      <Input
                        value={lineForm.description}
                        onChange={(e) => setLineForm((prev) => ({ ...prev, description: e.target.value }))}
                        placeholder="Descripción"
                      />
                    </div>
                  </div>
                  <Button
                    variant="outline"
                    onClick={handleCreateProductionLine}
                    disabled={isCreatingProductionLine}
                  >
                    <Plus className="w-4 h-4 mr-2" />
                    {isCreatingProductionLine ? "Guardando..." : "Agregar línea"}
                  </Button>
                  <div className="space-y-2 pt-2">
                    {productionLines.length === 0 ? (
                      <p className="text-sm text-gray-500">No hay líneas registradas.</p>
                    ) : (
                      productionLines.map((line) => (
                        <div
                          key={String(line.id)}
                          className="rounded bg-gray-50 px-3 py-2 text-sm flex justify-between"
                        >
                          <span>{line.name}</span>
                          <span className="text-gray-500">{line.description || "-"}</span>
                        </div>
                      ))
                    )}
                  </div>
                </CardContent>
              </Card>
            </TabsContent>

            <TabsContent value="direct-costs" className="mt-4">
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Wrench className="w-5 h-5" />
                    Costos Directos
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-3">
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
                    <div>
                      <Label>Línea de producción</Label>
                      <Select
                        value={directCostForm.idproduction_line}
                        onValueChange={(value) =>
                          setDirectCostForm((prev) => ({ ...prev, idproduction_line: value }))
                        }
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="Seleccionar línea (opcional)" />
                        </SelectTrigger>
                        <SelectContent>
                          {productionLines.map((line) => (
                            <SelectItem key={String(line.id)} value={String(line.id)}>
                              {line.name}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                    <div className="md:col-span-2">
                      <Label>Nombre</Label>
                      <Input
                        value={directCostForm.name}
                        onChange={(e) =>
                          setDirectCostForm((prev) => ({ ...prev, name: e.target.value }))
                        }
                        placeholder="Ej: Energía eléctrica"
                      />
                    </div>
                    <div>
                      <Label>Descripción</Label>
                      <Input
                        value={directCostForm.description}
                        onChange={(e) =>
                          setDirectCostForm((prev) => ({ ...prev, description: e.target.value }))
                        }
                        placeholder="Detalle del costo"
                      />
                    </div>
                    <div>
                      <Label>Unidad medida</Label>
                      <Input
                        value={directCostForm.unit_of_measure}
                        onChange={(e) =>
                          setDirectCostForm((prev) => ({ ...prev, unit_of_measure: e.target.value }))
                        }
                        placeholder="unit"
                      />
                    </div>
                    <div>
                      <Label>Cantidad estándar</Label>
                      <Input
                        type="number"
                        min="0"
                        value={directCostForm.quantity}
                        onChange={(e) =>
                          setDirectCostForm((prev) => ({
                            ...prev,
                            quantity: parseNumericInput(e.target.value),
                          }))
                        }
                      />
                    </div>
                    <div>
                      <Label>Costo</Label>
                      <Input
                        type="number"
                        min="0"
                        value={directCostForm.cost}
                        onChange={(e) =>
                          setDirectCostForm((prev) => ({ ...prev, cost: parseNumericInput(e.target.value) }))
                        }
                      />
                    </div>
                  </div>
                  <Button
                    onClick={handleCreateDirectCost}
                    disabled={isCreatingCost}
                  >
                    <Save className="w-4 h-4 mr-2" />
                    {isCreatingCost ? "Guardando..." : "Guardar costo directo"}
                  </Button>
                  <div className="space-y-2 pt-2">
                    {costs.filter((item) => String(item.type) === "operational").length === 0 ? (
                      <p className="text-sm text-gray-500">No hay costos directos registrados.</p>
                    ) : (
                      costs
                        .filter((item) => String(item.type) === "operational")
                        .map((cost) => (
                          <div key={String(cost.id)} className="rounded bg-gray-50 p-2 text-sm">
                            {cost.name} - ${Number(cost.cost || 0).toLocaleString("es-CL")}
                          </div>
                        ))
                    )}
                  </div>
                </CardContent>
              </Card>
            </TabsContent>

            <TabsContent value="labor" className="mt-4">
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Factory className="w-5 h-5" />
                    Mano de Obra
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-3">
                  <div className="grid grid-cols-1 md:grid-cols-4 gap-3">
                    <div>
                      <Label>Línea de producción</Label>
                      <Select
                        value={laborForm.idproduction_line}
                        onValueChange={(value) =>
                          setLaborForm((prev) => ({ ...prev, idproduction_line: value }))
                        }
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="Seleccionar línea (opcional)" />
                        </SelectTrigger>
                        <SelectContent>
                          {productionLines.map((line) => (
                            <SelectItem key={String(line.id)} value={String(line.id)}>
                              {line.name}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                    <div className="md:col-span-2">
                      <Label>Cargo</Label>
                      <Input
                        value={laborForm.role_name}
                        onChange={(e) =>
                          setLaborForm((prev) => ({ ...prev, role_name: e.target.value }))
                        }
                        placeholder="Ej: Operario producción"
                      />
                    </div>
                    <div>
                      <Label>Tipo costo</Label>
                      <Select
                        value={laborForm.cost_type}
                        onValueChange={(value) =>
                          setLaborForm((prev) => ({ ...prev, cost_type: value }))
                        }
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="daily">Día</SelectItem>
                          <SelectItem value="hourly">Hora</SelectItem>
                          <SelectItem value="monthly">Mensual</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                    <div>
                      <Label>Cantidad estándar</Label>
                      <Input
                        type="number"
                        min="0"
                        value={laborForm.quantity}
                        onChange={(e) =>
                          setLaborForm((prev) => ({ ...prev, quantity: parseNumericInput(e.target.value) }))
                        }
                      />
                    </div>
                    <div>
                      <Label>Costo estándar</Label>
                      <Input
                        type="number"
                        min="0"
                        value={laborForm.cost}
                        onChange={(e) =>
                          setLaborForm((prev) => ({ ...prev, cost: parseNumericInput(e.target.value) }))
                        }
                      />
                    </div>
                  </div>
                  <Button onClick={handleCreateLabor} disabled={isCreatingCost}>
                    <Save className="w-4 h-4 mr-2" />
                    {isCreatingCost ? "Guardando..." : "Guardar mano de obra"}
                  </Button>
                  <div className="space-y-2 pt-2">
                    {costs.filter((item) => String(item.type) === "labor").length === 0 ? (
                      <p className="text-sm text-gray-500">No hay costos de mano de obra registrados.</p>
                    ) : (
                      costs
                        .filter((item) => String(item.type) === "labor")
                        .map((cost) => (
                          <div key={String(cost.id)} className="rounded bg-gray-50 p-2 text-sm">
                            {cost.name} - ${Number(cost.cost || 0).toLocaleString("es-CL")}
                          </div>
                        ))
                    )}
                  </div>
                </CardContent>
              </Card>
            </TabsContent>

            <TabsContent value="operators" className="mt-4">
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Users className="w-5 h-5" />
                    Operarios
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-3">
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
                    <div>
                      <Label>RUT</Label>
                      <Input
                        value={operatorForm.rut}
                        onChange={(e) => setOperatorForm((prev) => ({ ...prev, rut: e.target.value }))}
                        placeholder="RUT trabajador"
                      />
                    </div>
                    <div>
                      <Label>Apellidos y nombres</Label>
                      <Input
                        value={operatorForm.full_name}
                        onChange={(e) =>
                          setOperatorForm((prev) => ({ ...prev, full_name: e.target.value }))
                        }
                        placeholder="Nombre completo"
                      />
                    </div>
                    <div>
                      <Label>Línea de producción</Label>
                      <Select
                        value={operatorForm.idproduction_line}
                        onValueChange={(value) =>
                          setOperatorForm((prev) => ({ ...prev, idproduction_line: value }))
                        }
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="Seleccionar línea" />
                        </SelectTrigger>
                        <SelectContent>
                          {productionLines.map((line) => (
                            <SelectItem key={String(line.id)} value={String(line.id)}>
                              {line.name}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                  <Button variant="outline" onClick={handleCreateProductionOperator} disabled={isCreatingProductionOperator}>
                    <Plus className="w-4 h-4 mr-2" />
                    {isCreatingProductionOperator ? "Guardando..." : "Agregar operario"}
                  </Button>
                  <div className="space-y-2 pt-2">
                    {productionOperators.length === 0 ? (
                      <p className="text-sm text-gray-500">No hay operarios registrados.</p>
                    ) : (
                      productionOperators.map((operator) => (
                        <div
                          key={String(operator.id)}
                          className="rounded bg-gray-50 px-3 py-2 text-sm flex justify-between"
                        >
                          <span>{operator.full_name} ({operator.rut})</span>
                          <span className="text-gray-500">{operator.line?.name || "-"}</span>
                        </div>
                      ))
                    )}
                  </div>
                </CardContent>
              </Card>
            </TabsContent>
          </Tabs>
        </TabsContent>

        <TabsContent value="formulas" className="space-y-4 mt-4">
          {formulaView !== "list" && (
            <Card>
              <CardHeader>
                <CardTitle>Crear Fórmula de Producción</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
                <div>
                  <Label>Código de fórmula</Label>
                  <Input
                    value={formulaHeader.code}
                    onChange={(e) => setFormulaHeader((prev) => ({ ...prev, code: e.target.value }))}
                    placeholder="F-GEN-0001"
                  />
                </div>
                <div>
                  <Label>Nombre fórmula</Label>
                  <Input
                    value={formulaHeader.name}
                    onChange={(e) => setFormulaHeader((prev) => ({ ...prev, name: e.target.value }))}
                    placeholder="Ej: Receta Shampoo 250ml"
                  />
                </div>
                <div>
                  <Label>Descripción</Label>
                  <Input
                    value={formulaHeader.description}
                    onChange={(e) => setFormulaHeader((prev) => ({ ...prev, description: e.target.value }))}
                    placeholder="Descripción"
                  />
                </div>
                <div>
                  <Label>Producto terminado</Label>
                  <Select
                    value={formulaHeader.idproduct}
                    onValueChange={(value) => setFormulaHeader((prev) => ({ ...prev, idproduct: value }))}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="Seleccionar producto" />
                    </SelectTrigger>
                    <SelectContent>
                      {finishedProducts.map((product) => (
                        <SelectItem key={String(product.id)} value={String(product.id)}>
                          {product.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <Label>Cantidad óptima (batch)</Label>
                  <Input
                    type="number"
                    min="0.0001"
                    step="0.0001"
                    value={formulaHeader.yield_quantity}
                    onChange={(e) =>
                      setFormulaHeader((prev) => ({ ...prev, yield_quantity: parseNumericInput(e.target.value) }))
                    }
                    placeholder="Cantidad óptima"
                  />
                </div>
                <div>
                  <Label>Línea de producción</Label>
                  <Select
                    value={formulaHeader.idproduction_line}
                    onValueChange={(value) =>
                      setFormulaHeader((prev) => ({ ...prev, idproduction_line: value }))
                    }
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="Seleccionar línea (opcional)" />
                    </SelectTrigger>
                    <SelectContent>
                      {productionLines.map((line) => (
                        <SelectItem key={String(line.id)} value={String(line.id)}>
                          {line.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <Label>Supervisor</Label>
                  <Select
                    value={formulaHeader.idsupervisor}
                    onValueChange={(value) => setFormulaHeader((prev) => ({ ...prev, idsupervisor: value }))}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="Seleccionar supervisor" />
                    </SelectTrigger>
                    <SelectContent>
                      {supervisors.map((supervisor) => (
                        <SelectItem key={String(supervisor.id)} value={String(supervisor.id)}>
                          {supervisor.user_name || supervisor.name || supervisor.email || `Usuario ${supervisor.id}`}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>

              <Tabs value={formulaTab} onValueChange={setFormulaTab} className="w-full">
                <TabsList className="grid w-full grid-cols-3">
                  <TabsTrigger value="materials">Materias Primas</TabsTrigger>
                  <TabsTrigger value="direct-costs">Costos Directos</TabsTrigger>
                  <TabsTrigger value="labor">Mano de Obra</TabsTrigger>
                </TabsList>

                <TabsContent value="materials" className="mt-4 space-y-3">
                  <div className="grid grid-cols-1 md:grid-cols-5 gap-3">
                    <div className="md:col-span-2">
                      <Label>Materia prima</Label>
                      <Select
                        value={formulaMaterialDraft.idproduct}
                        onValueChange={(value) => {
                          const material = rawMaterials.find((item) => String(item.id) === String(value));
                          setFormulaMaterialDraft((prev) => ({
                            ...prev,
                            idproduct: value,
                            name: material?.name || "",
                            unit: material?.unit || "unit",
                          }));
                        }}
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="Seleccionar materia prima" />
                        </SelectTrigger>
                        <SelectContent>
                          {rawMaterials.map((material) => (
                            <SelectItem key={String(material.id)} value={String(material.id)}>
                              {material.name}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                    <div>
                      <Label>Unidad</Label>
                      <Input value={formulaMaterialDraft.unit} readOnly className="bg-gray-50" />
                    </div>
                    <div>
                      <Label>Cantidad</Label>
                      <Input
                        type="number"
                        min="0"
                        step="0.0001"
                        value={formulaMaterialDraft.quantity}
                        onChange={(e) =>
                          setFormulaMaterialDraft((prev) => ({ ...prev, quantity: parseNumericInput(e.target.value) }))
                        }
                      />
                    </div>
                    <div>
                      <Label>Margen (%)</Label>
                      <Input
                        type="number"
                        value={formulaMaterialDraft.margin_percent}
                        onChange={(e) =>
                          setFormulaMaterialDraft((prev) => ({
                            ...prev,
                            margin_percent: parseNumericInput(e.target.value),
                          }))
                        }
                      />
                    </div>
                  </div>
                  <Button type="button" onClick={addMaterialToFormula}>
                    <Plus className="w-4 h-4 mr-2" />
                    Agregar
                  </Button>
                  <div className="space-y-2">
                    {formulaMaterials.length === 0 ? (
                      <p className="text-sm text-gray-500">Sin materias primas agregadas.</p>
                    ) : (
                      formulaMaterials.map((row) => (
                        <div key={row.id} className="rounded border p-2 text-sm flex items-center justify-between">
                          <span>
                            {row.name} | {row.quantity} {row.unit}
                          </span>
                          <Button variant="outline" size="sm" onClick={() => removeFormulaRow("materials", row.id)}>
                            Eliminar
                          </Button>
                        </div>
                      ))
                    )}
                  </div>
                </TabsContent>

                <TabsContent value="direct-costs" className="mt-4 space-y-3">
                  <div className="grid grid-cols-1 md:grid-cols-4 gap-3">
                    <div className="md:col-span-2">
                      <Label>Costo directo</Label>
                      <Select
                        value={formulaDirectCostDraft.idproduction_cost}
                        onValueChange={(value) => {
                          const selected = getCostById(value);
                          setFormulaDirectCostDraft((prev) => ({
                            ...prev,
                            idproduction_cost: value,
                            name: selected?.name || "",
                            unit_cost: Number(selected?.cost || 0),
                            quantity_use: 1,
                            amount: Number(selected?.cost || 0),
                            cost_type: selected?.cost_type || "",
                            line_type: "operational",
                          }));
                        }}
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="Seleccionar costo directo" />
                        </SelectTrigger>
                        <SelectContent>
                          {operationalCosts.map((cost) => (
                            <SelectItem key={String(cost.id)} value={String(cost.id)}>
                              {cost.name}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                    <div>
                      <Label>Costo unitario</Label>
                      <Input value={formulaDirectCostDraft.unit_cost} readOnly className="bg-gray-50" />
                    </div>
                    <div>
                      <Label>Cantidad de uso</Label>
                      <Input
                        type="number"
                        min="0"
                        step="0.0001"
                        value={formulaDirectCostDraft.quantity_use}
                        onChange={(e) =>
                          setFormulaDirectCostDraft((prev) =>
                            recalculateCostLine(prev, e.target.value),
                          )
                        }
                      />
                    </div>
                    <div>
                      <Label>Costo total</Label>
                      <Input value={formulaDirectCostDraft.amount} readOnly className="bg-gray-50" />
                    </div>
                  </div>
                  <Button type="button" onClick={() => addCostToFormula("operational")}>
                    <Plus className="w-4 h-4 mr-2" />
                    Agregar
                  </Button>
                  <div className="space-y-2">
                    {formulaDirectCosts.length === 0 ? (
                      <p className="text-sm text-gray-500">Sin costos directos agregados.</p>
                    ) : (
                      formulaDirectCosts.map((row) => (
                        <div key={row.id} className="rounded border p-2 text-sm flex items-center justify-between">
                          <span>
                            {row.name} | Cant: {row.quantity_use} | Total: $
                            {Number(row.amount || 0).toLocaleString("es-CL")}
                          </span>
                          <Button variant="outline" size="sm" onClick={() => removeFormulaRow("direct-costs", row.id)}>
                            Eliminar
                          </Button>
                        </div>
                      ))
                    )}
                  </div>
                </TabsContent>

                <TabsContent value="labor" className="mt-4 space-y-3">
                  <div className="grid grid-cols-1 md:grid-cols-4 gap-3">
                    <div className="md:col-span-2">
                      <Label>Cargo</Label>
                      <Select
                        value={formulaLaborDraft.idproduction_cost}
                        onValueChange={(value) => {
                          const selected = getCostById(value);
                          setFormulaLaborDraft((prev) => ({
                            ...prev,
                            idproduction_cost: value,
                            name: selected?.name || "",
                            unit_cost: Number(selected?.cost || 0),
                            quantity_use: Number(selected?.quantity || 1),
                            amount: Number((Number(selected?.cost || 0) * Number(selected?.quantity || 1)).toFixed(2)),
                            cost_type: selected?.cost_type || "",
                            line_type: "labor",
                          }));
                        }}
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="Seleccionar cargo" />
                        </SelectTrigger>
                        <SelectContent>
                          {laborCosts.map((cost) => (
                            <SelectItem key={String(cost.id)} value={String(cost.id)}>
                              {cost.name}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                    <div>
                      <Label>Tipo costo</Label>
                      <Input value={formulaLaborDraft.cost_type || "-"} readOnly className="bg-gray-50" />
                    </div>
                    <div>
                      <Label>Costo estándar</Label>
                      <Input value={formulaLaborDraft.unit_cost} readOnly className="bg-gray-50" />
                    </div>
                    <div>
                      <Label>Cantidad</Label>
                      <Input
                        type="number"
                        min="0"
                        step="0.0001"
                        value={formulaLaborDraft.quantity_use}
                        onChange={(e) =>
                          setFormulaLaborDraft((prev) => recalculateCostLine(prev, e.target.value))
                        }
                      />
                    </div>
                    <div>
                      <Label>Subtotal</Label>
                      <Input value={formulaLaborDraft.amount} readOnly className="bg-gray-50" />
                    </div>
                  </div>
                  <Button type="button" onClick={() => addCostToFormula("labor")}>
                    <Plus className="w-4 h-4 mr-2" />
                    Agregar
                  </Button>
                  <div className="space-y-2">
                    {formulaLaborCosts.length === 0 ? (
                      <p className="text-sm text-gray-500">Sin mano de obra agregada.</p>
                    ) : (
                      formulaLaborCosts.map((row) => (
                        <div key={row.id} className="rounded border p-2 text-sm flex items-center justify-between">
                          <span>
                            {row.name} | {row.cost_type || "-"} | Cant: {row.quantity_use} | Subtotal: $
                            {Number(row.amount || 0).toLocaleString("es-CL")}
                          </span>
                          <Button variant="outline" size="sm" onClick={() => removeFormulaRow("labor", row.id)}>
                            Eliminar
                          </Button>
                        </div>
                      ))
                    )}
                  </div>
                </TabsContent>
              </Tabs>

                <Button onClick={handleSaveFormula} disabled={isCreatingFormula || isUpdatingFormula}>
                  <Save className="w-4 h-4 mr-2" />
                  {isCreatingFormula || isUpdatingFormula
                    ? "Guardando..."
                    : isEditingFormula
                      ? "Actualizar fórmula"
                      : "Guardar fórmula"}
                </Button>
              </CardContent>
            </Card>
          )}

          {formulaView !== "create" && (
            <Card>
              <CardHeader>
                <CardTitle>Fórmulas registradas</CardTitle>
              </CardHeader>
              <CardContent className="space-y-2">
              {formulas.length === 0 ? (
                <p className="text-sm text-gray-500">No hay fórmulas registradas.</p>
              ) : (
                formulas.map((formula) => (
                  <div key={String(formula.id)} className="rounded border p-3">
                    <p className="font-semibold">
                      {formula.code ? `${formula.code} - ` : ""}
                      {formula.name}
                    </p>
                    <p className="text-sm text-gray-500">
                      Producto: {formula.product?.name || formula.idproduct || "-"} | Materiales: {(formula.materials || []).length} | Costos: {(formula.costs || []).length}
                    </p>
                  </div>
                ))
              )}
              </CardContent>
            </Card>
          )}
        </TabsContent>

        <TabsContent value="orders" className="space-y-4 mt-4">
          <Card>
            <CardHeader>
              <CardTitle>Crear orden de producción</CardTitle>
            </CardHeader>
            <CardContent className="grid grid-cols-1 md:grid-cols-4 gap-3">
              <div className="md:col-span-2">
                <Label>Fórmula</Label>
                <Select
                  value={orderForm.formula_id}
                  onValueChange={(value) => setOrderForm((prev) => ({ ...prev, formula_id: value }))}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Seleccionar fórmula" />
                  </SelectTrigger>
                  <SelectContent>
                    {formulas.map((formula) => (
                      <SelectItem key={String(formula.id)} value={String(formula.id)}>
                        {formula.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label>Cantidad estimada</Label>
                <Input
                  type="number"
                  min="1"
                  value={orderForm.planned_quantity}
                  onChange={(e) =>
                    setOrderForm((prev) => ({ ...prev, planned_quantity: parseNumericInput(e.target.value) }))
                  }
                />
              </div>
              <div>
                <Label>Fecha producción</Label>
                <Input
                  type="date"
                  value={orderForm.production_date}
                  onChange={(e) => setOrderForm((prev) => ({ ...prev, production_date: e.target.value }))}
                />
              </div>
              <div className="md:col-span-4">
                <Button onClick={handleCreateOrder} disabled={isCreatingOrder}>
                  <ClipboardList className="w-4 h-4 mr-2" />
                  {isCreatingOrder ? "Guardando..." : "Guardar orden"}
                </Button>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Órdenes registradas</CardTitle>
            </CardHeader>
            <CardContent className="space-y-2">
              {orders.length === 0 ? (
                <p className="text-sm text-gray-500">No hay órdenes registradas.</p>
              ) : (
                orders.map((order) => (
                  <div key={String(order.id)} className="rounded border p-3 flex justify-between items-center">
                    <div>
                      <p className="font-semibold">Orden #{order.id}</p>
                      <p className="text-sm text-gray-500">
                        Fórmula: {formulasById[String(order.formula_id)]?.name || order.formula_id} | Cantidad:
                        {" "}
                        {Number(order.planned_quantity || 0)}
                      </p>
                    </div>
                    <Badge className={getStatusBadge(order.status)}>
                      {String(order.status || "draft")}
                    </Badge>
                  </div>
                ))
              )}
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="execution" className="space-y-4 mt-4">
          <Card>
            <CardHeader>
              <CardTitle>Seleccionar orden de trabajo</CardTitle>
            </CardHeader>
            <CardContent>
              <Select value={selectedOrderId} onValueChange={setSelectedOrderId}>
                <SelectTrigger>
                  <SelectValue placeholder="Seleccionar orden" />
                </SelectTrigger>
                <SelectContent>
                  {orders.map((order) => (
                    <SelectItem key={String(order.id)} value={String(order.id)}>
                      Orden #{order.id} - {formulasById[String(order.formula_id)]?.name || "Sin fórmula"}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              {selectedOrder && (
                <div className="mt-3 p-3 bg-gray-50 rounded border">
                  <p className="text-sm">
                    <strong>Estado:</strong>{" "}
                    <Badge className={getStatusBadge(selectedOrder.status)}>{String(selectedOrder.status || "draft")}</Badge>
                  </p>
                  <p className="text-sm mt-1">
                    <strong>Fórmula:</strong> {selectedOrderFormula?.name || selectedOrder.formula_id}
                  </p>
                </div>
              )}
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Registrar consumo real</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <div className="flex items-center justify-between">
                <Label>Materiales consumidos</Label>
                <Button
                  size="sm"
                  variant="outline"
                  onClick={() =>
                    setConsumptionForm((prev) => ({
                      ...prev,
                      materials: [...prev.materials, getInitialConsumptionMaterial()],
                    }))
                  }
                >
                  <Plus className="w-4 h-4 mr-1" />
                  Agregar línea
                </Button>
              </div>
              {consumptionForm.materials.map((item, idx) => (
                <div key={`cons-${idx}`} className="grid grid-cols-1 md:grid-cols-3 gap-2">
                  <Select
                    value={item.raw_material_id}
                    onValueChange={(value) =>
                      setConsumptionForm((prev) => ({
                        ...prev,
                        materials: prev.materials.map((row, rowIdx) =>
                          rowIdx === idx ? { ...row, raw_material_id: value } : row,
                        ),
                      }))
                    }
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="Materia prima" />
                    </SelectTrigger>
                    <SelectContent>
                      {rawMaterials.map((material) => (
                        <SelectItem key={String(material.id)} value={String(material.id)}>
                          {material.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <Input
                    placeholder="Lote (opcional)"
                    value={item.lot_id}
                    onChange={(e) =>
                      setConsumptionForm((prev) => ({
                        ...prev,
                        materials: prev.materials.map((row, rowIdx) =>
                          rowIdx === idx ? { ...row, lot_id: e.target.value } : row,
                        ),
                      }))
                    }
                  />
                  <Input
                    type="number"
                    min="0"
                    step="0.001"
                    placeholder="Cantidad real"
                    value={item.quantity_used}
                    onChange={(e) =>
                      setConsumptionForm((prev) => ({
                        ...prev,
                        materials: prev.materials.map((row, rowIdx) =>
                          rowIdx === idx ? { ...row, quantity_used: parseNumericInput(e.target.value) } : row,
                        ),
                      }))
                    }
                  />
                </div>
              ))}

              <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
                <div>
                  <Label>Costo mano de obra real</Label>
                  <Input
                    type="number"
                    min="0"
                    step="0.01"
                    value={consumptionForm.labor_cost}
                    onChange={(e) =>
                      setConsumptionForm((prev) => ({ ...prev, labor_cost: parseNumericInput(e.target.value) }))
                    }
                  />
                </div>
                <div>
                  <Label>Costo operativo real</Label>
                  <Input
                    type="number"
                    min="0"
                    step="0.01"
                    value={consumptionForm.operational_cost}
                    onChange={(e) =>
                      setConsumptionForm((prev) => ({
                        ...prev,
                        operational_cost: parseNumericInput(e.target.value),
                      }))
                    }
                  />
                </div>
              </div>

              <Button onClick={handleRegisterConsumption} disabled={isRegisteringConsumption}>
                <Save className="w-4 h-4 mr-2" />
                {isRegisteringConsumption ? "Guardando..." : "Registrar consumo"}
              </Button>

              {selectedOrderConsumption && (
                <Textarea
                  value={JSON.stringify(selectedOrderConsumption, null, 2)}
                  readOnly
                  rows={6}
                  className="font-mono text-xs"
                />
              )}
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Consolidación e ingreso a inventario</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <div className="flex items-center justify-between">
                <Label>Salidas por bodega</Label>
                <Button
                  size="sm"
                  variant="outline"
                  onClick={() =>
                    setConsolidationForm((prev) => ({
                      ...prev,
                      outputs: [...prev.outputs, getInitialOutput()],
                    }))
                  }
                >
                  <Plus className="w-4 h-4 mr-1" />
                  Agregar bodega
                </Button>
              </div>

              {consolidationForm.outputs.map((item, idx) => (
                <div key={`out-${idx}`} className="grid grid-cols-1 md:grid-cols-2 gap-2">
                  <Select
                    value={item.warehouse_id}
                    onValueChange={(value) =>
                      setConsolidationForm((prev) => ({
                        ...prev,
                        outputs: prev.outputs.map((row, rowIdx) =>
                          rowIdx === idx ? { ...row, warehouse_id: value } : row,
                        ),
                      }))
                    }
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="Bodega destino" />
                    </SelectTrigger>
                    <SelectContent>
                      {warehouses.map((warehouse) => (
                        <SelectItem key={String(warehouse.id)} value={String(warehouse.id)}>
                          {warehouse.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <Input
                    type="number"
                    min="0"
                    step="0.001"
                    value={item.quantity}
                    onChange={(e) =>
                      setConsolidationForm((prev) => ({
                        ...prev,
                        outputs: prev.outputs.map((row, rowIdx) =>
                          rowIdx === idx ? { ...row, quantity: parseNumericInput(e.target.value) } : row,
                        ),
                      }))
                    }
                    placeholder="Cantidad producida"
                  />
                </div>
              ))}

              <div className="flex flex-wrap gap-2">
                <Button onClick={handleConsolidate} disabled={isConsolidating}>
                  <PackageCheck className="w-4 h-4 mr-2" />
                  {isConsolidating ? "Consolidando..." : "Consolidar orden"}
                </Button>
                <Button variant="outline" onClick={handleInventoryEntry} disabled={isExecutingInventory}>
                  <Boxes className="w-4 h-4 mr-2" />
                  {isExecutingInventory ? "Ejecutando..." : "Ejecutar ingreso a inventario"}
                </Button>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}
