"use client";

import Button from "@/components/Forms/Button";
import Input from "@/components/Forms/Input";
import InputGroup from "@/components/Forms/InputGroup";
import InputSelectComponent from "@/components/Forms/InputSelect";
import { handleSweetAlert } from "@/components/Modal/SweetAlertConfirm";
import {
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  FormatFields,
  GetForm,
  proximoNumero,
  proximoNumeroFloat,
  validarRanges,
} from "@/utils";
import { Info, TriangleAlert, X } from "lucide-react";
import { Fragment, useEffect, useState } from "react";
import { toast } from "react-toastify";

type ITabelaPrecos = {
  id_custo_extra_tabela?: string;
  qtd_custo_extra_tabela: number | string;
  de_custo_extra_tabela: number | string;
  ate_custo_extra_tabela: number | string;
  id_custo_extra?: string;
};

export const minRange = "de_custo_extra_tabela";
export const maxRange = "ate_custo_extra_tabela";

const FormCustosExtras = ({
  onSubmitFunction,
  defaultValues,
  disabledFields,
  children,
  telhados,
  distribuidores,
  tiposCustos,
  optionsPercentuaisDe,
  tiposNegocios,
  todosTiposNegocios,
  ...rest
}: {
  telhados: any[];
  distribuidores: any[];
  tiposNegocios?: any[];
  [x: string]: any;
}) => {
  // const [yupSchema, setYupSchema] = useState<
  //   yup.ObjectSchema<{}, yup.AnyObject, {}, "">
  // >(yup.object().shape({}));

  const { handleSubmit, ...form } = GetForm();

  // const [formulas, setFormulas] = useState<any[]>([]);
  const [unitSelected, setUnitSelected] = useState<any>(
    (defaultValues && defaultValues["unidade_custo_extra"]) || "0",
  );
  const [tipoCustoExtra, setTipoCustoExtra] = useState(
    (defaultValues && defaultValues["tipo_custo_extra"]) || "0",
  );
  // const [formulaSelected, setFormulaSelected] = useState<any>(
  //   defaultValues && defaultValues["formula_custo_extra"]
  // );
  const [tabelaPrecos, setTabelaPrecos] = useState<ITabelaPrecos[]>(
    form?.control._formValues?.tabelaPrecos
      ? form?.control._formValues?.tabelaPrecos
      : defaultValues?.tabelaPrecos
        ? defaultValues.tabelaPrecos
        : [],
  );
  const [valuesKey, setValuesKey] = useState(1);
  const [stepForm, setStepForm] = useState(0);
  const [metodoCustoExtra, setMetodoCustoExtra] = useState(
    (defaultValues && defaultValues["metodo_custo_extra"]) || "1",
  );
  const [intersecoesRanges, setIntersecoesRanges] = useState<any>({});

  useEffect(() => {
    if (
      tipoCustoExtra != "2" &&
      (metodoCustoExtra == "1" ||
        metodoCustoExtra == "2" ||
        metodoCustoExtra == "6")
    ) {
      setMetodoCustoExtra("");
      form.setValue("metodo_custo_extra", "");
    }
    form.setValue("formula_custo_extra", "");
  }, [tipoCustoExtra]);

  useEffect(() => {
    if (unitSelected == "1") {
      form.setValue(
        "metodo_custo_extra" as never,
        {
          label: "Valor Percentual",
          value: "5",
        } as never,
      );
      setMetodoCustoExtra("5");
    } else if (unitSelected == "0" && metodoCustoExtra == "5") {
      // if (tipoCustoExtra === "2") {
      // form.setValue(
      //   "metodo_custo_extra" as never,
      //   {
      //     label: "Tabela Potência do Sistema",
      //     value: "6",
      //   } as never,
      // );
      // setMetodoCustoExtra("5");
      // // setTabelaPrecos([]);
      // return;
      // } else {
      form.setValue(
        "metodo_custo_extra" as never,
        {
          label: "Tabela de Módulos",
          value: "1",
        } as never,
      );
      setMetodoCustoExtra("1");
      setTabelaPrecos([]);
      // }
    }
    setValuesKey((prev) => prev + 1);
  }, [unitSelected]);

  // useEffect(() => {
  //   if (formulaSelected != "1" && formulaSelected != "2") {
  //     form.setValue("de_custo_extra" as never, "" as never);
  //     form.setValue("ate_custo_extra" as never, "" as never);
  //   }
  // }, [formulaSelected]);

  useEffect(() => {
    form.setValue("tabelaPrecos" as never, tabelaPrecos as never);
    const ranges = tabelaPrecos.map((precoInfo) => [
      Number(precoInfo[minRange]),
      Number(precoInfo[maxRange]),
    ]);
    const intersecoes = validarRanges(ranges);
    setIntersecoesRanges(intersecoes);
    // setIntersecoesRanges(() => {

    //   return [];
    // });
  }, [tabelaPrecos]);

  function onSubmitCustosExtras(data: any) {
    if (
      tabelaPrecos.some(
        (precoExtra, indexPrecoExtra) =>
          +precoExtra[minRange] > +precoExtra[maxRange] ||
          intersecoesRanges[String(indexPrecoExtra)]?.length > 0,
      )
    ) {
      return toast.error("Resolva os erros na tabela de custos!");
    }

    if (Array.isArray(data["id_tipo_negocio_custo_extra"])) {
      data["id_tipo_negocio_custo_extra"] =
        data["id_tipo_negocio_custo_extra"].join(",");
    }

    data["distribuidores_custo_extra"] =
      data["distribuidores_custo_extra"].join(",");
    data["tiposTelhado_custo_extra"] = data.tiposTelhado_custo_extra?.join(",");

    data["qtd_custo_extra"] = FormatFields.desformatarNumeros(
      data["qtd_custo_extra"],
    );
    if (unitSelected == "1") {
      data["metodo_custo_extra"] = "5";
    }
    if (
      metodoCustoExtra != "1" &&
      metodoCustoExtra != "2" &&
      metodoCustoExtra != "6"
    ) {
      data["tabelaPrecos"] = [];
    } else {
      data["qtd_custo_extra"] = "0";
    }
    return onSubmitFunction(data);
  }

  const columns = [
    {
      header:
        metodoCustoExtra == "1"
          ? `Qtd de Módulos De`
          : metodoCustoExtra == "6"
            ? "Potência do Sistema de (kW)"
            : `Potência do Inversor De (kW)`,
      accessorKey: "de_custo_extra_tabela",
    },
    {
      header:
        metodoCustoExtra == "1"
          ? `Qtd de Módulos Até`
          : metodoCustoExtra == "6"
            ? "Potência do Sistema até (kW)"
            : `Potência do Inversor Até (kW)`,
      accessorKey: "ate_custo_extra_tabela",
    },
    {
      header: unitSelected == 0 ? "Valor" : "Percentual %",
      accessorKey: "qtd_custo_extra_tabela",
    },
  ];

  return (
    <form
      onSubmit={handleSubmit(onSubmitCustosExtras)}
      key={form.key}
      {...rest}
    >
      {/* <div className="w-full flex flex-row justify-between">
        <div>
          <Button
            className={`${stepForm === 1 ? "block" : "hidden"}`}
            type="button"
            onClick={() => setStepForm((prev) => prev - 1)}
          >
            Voltar
          </Button>
        </div>
        {(metodoCustoExtra == "1" || metodoCustoExtra == "2") && (
          <div>
            <Button
              className={`${stepForm === 1 ? "hidden" : "block"}`}
              type="button"
              onClick={() => setStepForm((prev) => prev + 1)}
            >
              Tabela Custos
            </Button>
          </div>
        )}
      </div> */}
      <div
        className={`flex-grow overflow-y-auto overflow-scroll ${stepForm === 0 ? "block" : "hidden"}`}
      >
        <InputGroup>
          <Input
            name="nome_custo_extra"
            label="Nome"
            formulario={form}
            required
            error={"Preencha o Nome"}
            defaultValue={defaultValues && defaultValues["nome_custo_extra"]}
          />
          <Input
            name="descricaoProposta_custo_extra"
            label="Descrição para Proposta"
            formulario={form}
            required
            error={"Preencha a Descrição para Proposta"}
            defaultValue={
              defaultValues && defaultValues["descricaoProposta_custo_extra"]
            }
          />
          {/* <InputSelectComponent
            name="lojas_custo_extra"
            label="Loja(s)"
            formulario={form}
            isMulti
            options={[
              // { label: "Todos", value: "*" },
              ...lojas.map((e) => ({
                label: e.nome_loja,
                value: e.id_loja,
              })),
            ]}
            defaultValue={defaultValues && defaultValues["lojas_custo_extra"]}
          /> */}
        </InputGroup>
        <InputGroup>
          <InputSelectComponent
            name="id_tipo_negocio_custo_extra"
            label="Tipo de Negócio"
            formulario={form}
            isMulti
            options={[
              ...(tiposNegocios?.length == todosTiposNegocios?.length
                ? [{ label: "Todos", value: "*" }]
                : []),
              ...(tiposNegocios || []).map((tipoNegocio: any) => ({
                value: tipoNegocio.id_tipo_negocio,
                label: tipoNegocio.nome_tipo_negocio,
              })),
            ]}
            defaultValue={
              defaultValues && defaultValues["id_tipo_negocio_custo_extra"]
            }
          />
          <InputSelectComponent
            name="distribuidores_custo_extra"
            label="Distribuidores"
            formulario={form}
            isMulti
            options={[
              { label: "Todos", value: "*" },
              ...distribuidores.map((distribuidor) => ({
                value: distribuidor.id_distribuidor,
                label: distribuidor.nome_distribuidor,
              })),
            ]}
            defaultValue={
              defaultValues && defaultValues["distribuidores_custo_extra"]
            }
          />
          <InputSelectComponent
            name="tiposTelhado_custo_extra"
            label="Tipos de Telhados"
            formulario={form}
            isMulti
            options={[
              { label: "Todos", value: "*" },
              ...telhados.map((e) => ({
                label: e.nome_telhado,
                value: e.id_telhado,
              })),
            ]}
            defaultValue={
              defaultValues && defaultValues["tiposTelhado_custo_extra"]
            }
          />
        </InputGroup>
        <InputGroup>
          <InputSelectComponent
            name="tipo_custo_extra"
            label="Tipo de Custo"
            formulario={form}
            required
            error={"Preencha o Tipo de Custo"}
            options={tiposCustos}
            defaultValue={
              (defaultValues && defaultValues["tipo_custo_extra"]) || "0"
            }
            onChange={(e: any) => {
              setTipoCustoExtra(e.value);
              if (e.value != "1") {
                form.control.unregister(["label_custo_extra"] as never[], {
                  keepError: false,
                  keepValue: false,
                });
                form.setYupSchema((prev) => {
                  const fields: any = prev.fields;
                  delete fields["label_custo_extra"];
                  prev.fields = fields;
                  return prev;
                });
              }
              if (
                tipoCustoExtra == 2 &&
                e.value != 2 &&
                (metodoCustoExtra == "1" ||
                  metodoCustoExtra == "2" ||
                  metodoCustoExtra == "6")
              ) {
                setMetodoCustoExtra("");
                form.setValue("metodo_custo_extra", "");
              }
            }}
            formatOptionLabel={({ value, label, handleSweetAlertHtml }) => (
              <div className="flex flex-row gap-3">
                <div>{label}</div>
                <div
                  onClick={(e) => {
                    e.stopPropagation();
                    e.preventDefault();
                  }}
                  className="opacity-80"
                >
                  <Button
                    className={` bg-primary flex flex-row gap-2 rounded-full p-0`}
                    type="button"
                    onClick={(e: any) => {
                      e.stopPropagation();
                      handleSweetAlert({
                        icon: "info",
                        // title: "Cálculo Markup",
                        showDenyButton: false,
                        confirmButtonText: "Ok",
                        html: handleSweetAlertHtml || "",
                      });
                    }}
                  >
                    <Info />
                  </Button>
                </div>
              </div>
            )}
          />
          {tipoCustoExtra == "1" && (
            <Input
              name="label_custo_extra"
              label="Label para Proposta"
              formulario={form}
              required
              error={"Informe a Label"}
              defaultValue={defaultValues && defaultValues["label_custo_extra"]}
            />
          )}
          <InputSelectComponent
            name="unidade_custo_extra"
            label="Unidade de Cálculo"
            formulario={form}
            options={[
              { label: "Valor R$", value: "0" },
              { label: "Percentual %", value: "1" },
            ]}
            defaultValue={unitSelected}
            onChange={(e: any) => setUnitSelected(e.value)}
          />
          {unitSelected == "1" && (
            <InputSelectComponent
              name="percentualDe_custo_extra"
              label="Percentual de"
              formulario={form}
              options={optionsPercentuaisDe}
              required
              error="Informe sobre que valor o percentual será adicionado"
              dynamic
              defaultValue={
                defaultValues && defaultValues["percentualDe_custo_extra"]
              }
            />
          )}

          <InputSelectComponent
            // key={valuesKey}
            name="metodo_custo_extra"
            label="Método do Custo Extra"
            formulario={form}
            options={
              (unitSelected == "0" && [
                ...(tipoCustoExtra == 2
                  ? [
                      {
                        label: "Tabela de Módulos",
                        value: "1",
                      },
                      {
                        label: "Tabela Potência Inversor",
                        value: "2",
                      },
                      {
                        label: "Tabela Potência do Sistema",
                        value: "6",
                      },
                    ]
                  : []),
                {
                  label: "Valor Fixo",
                  value: "3",
                },
                {
                  label: "Fórmula",
                  value: "4",
                },
              ]) || [
                {
                  label: "Valor Percentual",
                  value: "5",
                },
              ]
            }
            defaultValue={
              form.control._formValues?.metodo_custo_extra ||
              (defaultValues && defaultValues["metodo_custo_extra"]) ||
              "1"
            }
            onChange={(e: any) =>
              setMetodoCustoExtra((prev: any) => {
                if (prev != e.value) {
                  setTabelaPrecos([]);
                  // form.reload();
                  form.control.unregister(["formula_custo_extra"] as never[], {
                    keepError: false,
                    keepValue: false,
                  });
                  form.setYupSchema((prev) => {
                    const fields: any = prev.fields;
                    delete fields["formula_custo_extra"];
                    prev.fields = fields;
                    return prev;
                  });
                  if (e.value != "1" && e.value != "2" && e.value != "5") {
                    form.setValue("qtd_custo_extra", "");
                  }
                }
                return e.value;
              })
            }
            skipEffect
          />
          {metodoCustoExtra == "4" && (
            <InputSelectComponent
              name="formula_custo_extra"
              label="Fórmula"
              options={[
                ...(tipoCustoExtra == "1"
                  ? [
                      {
                        label: "Fórmula Multiplicação da Entrada",
                        value: "1",
                        handleSweetAlertHtml: `
                          <div class="flex flex-col gap-2">
                            <div>
                              <div class="font-bold">
                                Fórmula Multiplicação da Entrada
                              </div>
                              <div>
                                (Qtd Informada * Valor Fixo)
                              </div>
                            </div>
                          </div>
                        `,
                      },
                    ]
                  : []),
                {
                  label: "Fórmula Multiplicação da Média de Dias",
                  value: "2",
                  handleSweetAlertHtml: `
                    <div class="flex flex-col gap-2">
                      <div>
                        <div class="font-bold">
                          Fórmula Multiplicação da Média de Dias
                        </div>
                        <div>
                          ((Arred(Qtd Mod / (Mod Inst Dia / Qtd Instaladores)) * Valor Fixo
                        </div>
                      </div>
                    </div>
                  `,
                },
                {
                  label: "Fórmula Multiplicação Qtd Módulos",
                  value: "3",
                  handleSweetAlertHtml: `
                    <div class="flex flex-col gap-2">
                      <div>
                        <div class="font-bold">
                          Fórmula Multiplicação Qtd Módulos
                        </div>
                        <div>
                          Qtd Mod * ${tipoCustoExtra == "1" ? "Valor Informado" : "Valor Fixo"}
                        </div>
                      </div>
                    </div>
                  `,
                },
                {
                  label: "Fórmula Multiplicação Potência Sistema",
                  value: "4",
                  handleSweetAlertHtml: `
                    <div class="flex flex-col gap-2">
                      <div>
                        <div class="font-bold">
                          Fórmula Multiplicação Potência Sistema
                        </div>
                        <div>
                          Potência Sistema * ${tipoCustoExtra == "1" ? "Valor Informado" : "Valor Fixo"}
                        </div>
                      </div>
                    </div>
                  `,
                },
                {
                  label: "Fórmula Multiplicação Qtd UCs",
                  value: "5",
                  handleSweetAlertHtml: `
                    <div class="flex flex-col gap-2">
                      <div>
                        <div class="font-bold">
                          Fórmula Multiplicação Qtd UCs
                        </div>
                        <div>
                          Qtd UCs * ${tipoCustoExtra == "1" ? "Valor Informado" : "Valor Fixo"}
                        </div>
                      </div>
                    </div>
                  `,
                },
              ]}
              formulario={form}
              defaultValue={
                defaultValues && defaultValues["formula_custo_extra"]
              }
              formatOptionLabel={({ value, label, handleSweetAlertHtml }) => (
                <div className="flex flex-row gap-3 items-center">
                  <div>{label}</div>
                  <div
                    onClick={(e) => {
                      e.stopPropagation();
                      e.preventDefault();
                    }}
                    className="opacity-80"
                  >
                    <Button
                      className={` bg-primary flex flex-row gap-2 rounded-full p-0`}
                      type="button"
                      onClick={(e: any) => {
                        e.stopPropagation();
                        handleSweetAlert({
                          icon: "info",
                          // title: "Cálculo Markup",
                          showDenyButton: false,
                          confirmButtonText: "Ok",
                          html: handleSweetAlertHtml || "",
                        });
                      }}
                    >
                      <Info />
                    </Button>
                  </div>
                </div>
              )}
              // onChange={(e: any) => {
              //   switch (e.value) {
              //     case "1":
              //       toast.info(
              //         "Fórmula Multiplicação da Entrada: (Qtd Informada * Valor Fixo)"
              //       );
              //       break;
              //     case "2":
              //       toast.info(
              //         "Fórmula Multiplicação da Média de Dias: ((Arred(Qtd Mod / (Mod Inst Dia / Qtd Instaladores)) * Valor Fixo"
              //       );
              //       break;

              //     default:
              //       break;
              //   }
              // }}
              // disabled
              required
              error="Informe a Fórmula desejada"
            />
          )}
        </InputGroup>
        {metodoCustoExtra != "1" &&
          metodoCustoExtra != "2" &&
          metodoCustoExtra != "6" && (
            <InputGroup>
              <Input
                name="qtd_custo_extra"
                label={unitSelected == "0" ? "Valor" : "Percentual (%)"}
                formulario={form}
                mascara="numero"
                prefix={unitSelected == "0" ? "R$" : ""}
                defaultValue={
                  Object.keys(form.control._formValues).includes(
                    "qtd_custo_extra",
                  )
                    ? form.control._formValues["qtd_custo_extra"]
                    : defaultValues && defaultValues["qtd_custo_extra"]
                }
              />
            </InputGroup>
          )}
      </div>
      {stepForm == 1 && (
        <div className={`${stepForm === 1 ? "block" : "hidden"}`}>
          <legend className="px-3 text-black dark:text-white bg-white rounded dark:bg-black text-center font-bold uppercase flex flex-col w-full">
            Tabela de Custo
          </legend>

          <div className={`flex flex-row gap-2 justify-end pb-4`}>
            <div className="flex flex-col justify-end">
              <Button
                type="button"
                onClick={() => {
                  setTabelaPrecos((prev) => [
                    ...prev,
                    columns.reduce((acc: any, col) => {
                      acc[col.accessorKey] =
                        col.accessorKey == minRange
                          ? ["2", "6"].includes(metodoCustoExtra)
                            ? proximoNumeroFloat(
                                tabelaPrecos.map((registro: any) => [
                                  Number(registro[minRange]),
                                  Number(registro[maxRange]),
                                ]),
                              )
                            : proximoNumero(
                                tabelaPrecos.map((registro: any) => [
                                  Number(registro[minRange]),
                                  Number(registro[maxRange]),
                                ]),
                              )
                          : col.accessorKey == maxRange
                            ? ["2", "6"].includes(metodoCustoExtra)
                              ? proximoNumeroFloat(
                                  tabelaPrecos.map((registro: any) => [
                                    Number(registro[minRange]),
                                    Number(registro[maxRange]),
                                  ]),
                                ) + 0.01
                              : proximoNumero(
                                  tabelaPrecos.map((registro: any) => [
                                    Number(registro[minRange]),
                                    Number(registro[maxRange]),
                                  ]),
                                ) + 1
                            : 0.0;
                      return acc;
                    }, {}),
                  ]);

                  setValuesKey((prev) => prev + 1);
                }}
              >
                Novo Custo
              </Button>
            </div>
          </div>
          <div className="h-full overflow-hidden flex flex-col items-center">
            <div className="w-fit shadow-md max-h-[50vh] overflow-auto flex flex-col items-center">
              <table className="w-fit">
                {/* <table className=""> */}
                <TableHeader>
                  <TableRow className="sticky top-[-1px] bg-[#eee] dark:bg-[#141d27] z-9 hover:bg-[#eee] dark:hover:bg-[#1d2a39]">
                    <TableHead className="font-bold py-2 px-1 border-b text-center">
                      Ações
                    </TableHead>
                    {columns.map((col, index) => (
                      <TableHead
                        key={index}
                        className="font-bold py-2 px-4 border-b text-center"
                      >
                        {col.header}
                      </TableHead>
                    ))}
                  </TableRow>
                </TableHeader>
                <tbody key={valuesKey}>
                  {tabelaPrecos.map(
                    (precoExtra: any, indexPrecoExtra: number) => {
                      return (
                        <Fragment key={indexPrecoExtra}>
                          <TableRow>
                            <TableCell>
                              <div className="flex justify-around gap-1">
                                {/* <button
                                title="Duplicar"
                                className="navButton bg-primary text-white"
                                type="button"
                                onClick={() => {}}
                              >
                                <Copy />
                              </button> */}
                                <button
                                  title="Remover"
                                  type="button"
                                  className="navButton bg-error text-white  "
                                  onClick={() => {
                                    setTabelaPrecos((prev) => {
                                      const newTabelaPrecos = [...prev];
                                      newTabelaPrecos.splice(
                                        indexPrecoExtra,
                                        1,
                                      );
                                      return newTabelaPrecos;
                                    });
                                    setValuesKey((prev) => prev + 1);
                                  }}
                                >
                                  <X />
                                </button>
                                {(+precoExtra[minRange] >
                                  +precoExtra[maxRange] ||
                                  intersecoesRanges[String(indexPrecoExtra)]
                                    ?.length > 0) && (
                                  <button
                                    type="button"
                                    className="navButton bg-warning text-white"
                                    onClick={() => {
                                      if (
                                        +precoExtra[minRange] >
                                        +precoExtra[maxRange]
                                      ) {
                                        toast.error(
                                          `"De" não pode ser maior que "Até"!`,
                                        );
                                      }
                                      if (
                                        intersecoesRanges[
                                          String(indexPrecoExtra)
                                        ]?.length > 0
                                      ) {
                                        toast.error(
                                          `O range faz intersecção com o(s) range(s): ${intersecoesRanges[
                                            String(indexPrecoExtra)
                                          ]
                                            .map(
                                              (interseccao: number) =>
                                                `${Number(
                                                  tabelaPrecos[
                                                    Number(interseccao)
                                                  ][minRange],
                                                ).toFixed(
                                                  metodoCustoExtra == "2"
                                                    ? 2
                                                    : 0,
                                                )} até ${Number(
                                                  tabelaPrecos[
                                                    Number(interseccao)
                                                  ][maxRange],
                                                ).toFixed(
                                                  metodoCustoExtra == "2"
                                                    ? 2
                                                    : 0,
                                                )}`,
                                            )
                                            .join(", ")}`,
                                        );
                                      }
                                    }}
                                  >
                                    <TriangleAlert />
                                  </button>
                                )}
                              </div>
                            </TableCell>
                            {columns.map((col, index) => (
                              <TableCell
                                key={index}
                                className="p-1 text-center"
                              >
                                <div className="mx-auto flex flex-row gap-2 justify-center">
                                  <Input
                                    // name={`indexes-${indexPrecoExtra}-${index}`}
                                    defaultValue={
                                      // index === 2
                                      //   ? FormatFields.formatarNumero(
                                      //       precoExtra[col.accessorKey]
                                      //     )
                                      //   : (+precoExtra[col.accessorKey]).toFixed(
                                      //       0
                                      //     )
                                      ["2", "6"].includes(metodoCustoExtra) ||
                                      index === 2
                                        ? FormatFields.formatarNumero(
                                            precoExtra[col.accessorKey],
                                          )
                                        : (+precoExtra[
                                            col.accessorKey
                                          ]).toFixed(0)
                                    }
                                    mascara={
                                      // index === 2 ? "numero" : "numerico"
                                      ["2", "6"].includes(metodoCustoExtra) ||
                                      index === 2
                                        ? "numero"
                                        : "numerico"
                                    }
                                    // width={`${index < 2 && `min-w-[130px] flex-1`} text-ellipsis`}
                                    width={`min-w-[130px] text-ellipsis`}
                                    onChange={(e: any) => {
                                      setTabelaPrecos((prev) => {
                                        const newTabelaPrecos = [...prev];
                                        newTabelaPrecos.splice(
                                          indexPrecoExtra,
                                          1,
                                          {
                                            ...prev[indexPrecoExtra],
                                            [col.accessorKey]:
                                              +FormatFields.desformatarNumeros(
                                                e.target.value,
                                              ),
                                          },
                                        );
                                        return newTabelaPrecos;
                                      });
                                    }}
                                    prefix={
                                      index == 2 && unitSelected == 0
                                        ? "R$"
                                        : ""
                                    }
                                    maxLength={
                                      ["2", "6"].includes(metodoCustoExtra) &&
                                      index < 2
                                        ? 6
                                        : undefined
                                    }
                                  />
                                </div>
                              </TableCell>
                            ))}
                          </TableRow>
                        </Fragment>
                      );
                    },
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}
      {/* <div className="sticky bottom-0 p-4 bg-white">{children}</div> */}
      <div className="sticky bottom-0 p-4 bg-white">
        <div className="w-full flex flex-row justify-between">
          <div>
            <Button
              className={`${stepForm === 1 ? "block" : "hidden"}`}
              type="button"
              onClick={() => setStepForm((prev) => prev - 1)}
            >
              Voltar
            </Button>
          </div>
          {(metodoCustoExtra == "1" ||
            metodoCustoExtra == "2" ||
            metodoCustoExtra == "6") &&
            stepForm == 0 && (
              <section>
                <Button
                  // className={`${stepForm === 1 ? "hidden" : "block"}`}
                  type="button"
                  onClick={() => setStepForm((prev) => prev + 1)}
                >
                  Tabela Custos
                </Button>
              </section>
            )}
          <div
            className={`${
              metodoCustoExtra != "1" &&
              metodoCustoExtra != "2" &&
              metodoCustoExtra != "6"
                ? "block"
                : stepForm === 1 || tabelaPrecos.length < 1
                  ? "hidden"
                  : "block"
            }`}
          >
            {children}
          </div>
        </div>
      </div>
    </form>
  );
};

export default FormCustosExtras;
