import LoaderSun from "@/components/common/Loader/LoaderSun";
import Container from "@/components/Forms/Container";
import InputSelectComponent from "@/components/Forms/InputSelect";
import { handleSweetAlert } from "@/components/Modal/SweetAlertConfirm";
import ReactTable from "@/components/ReactTable/ReactTable";
import { listarDistribuidores } from "@/requests/CRUD/Distribuidores/listarDistribuidores";
import { obterLoja } from "@/requests/CRUD/Lojas/obterLoja";
import { cadastrarCustoExtra } from "@/requests/CRUD/Politica/cadastrarCustoExtra";
import { deletarCustoExtra } from "@/requests/CRUD/Politica/deletarCustoExtra";
import { editarCustoExtra } from "@/requests/CRUD/Politica/editarCustoExtra";
import { listarCustosExtras } from "@/requests/CRUD/Politica/listarCustosExtras";
import { listarTiposNegocios } from "@/requests/CRUD/TiposNegocios/listarTiposNegocios";
import { listarTodosTiposTelhados } from "@/requests/CRUD/TiposTelhados/listarTiposTelhados";
import { formatarValor, FormatFields } from "@/utils";
import { Trash } from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import { FieldValues } from "react-hook-form";
import FormCustosExtras from "./FormCustosExtras";

const CustosExtras = ({ id_loja }: any) => {
  const [tiposNegocios, setTiposNegocios] = useState<any[]>([]);
  const [todosTiposNegocios, setTodosTiposNegocios] = useState<any[]>([]);
  const [tipoNegocioSelecionado, setTipoNegocioSelecionado] = useState("1");
  const [filtroSelecionado, setFiltroSelecionado] = useState("0");
  const [tipoCustoSelecionado, setTipoCustoSelecionado] = useState("*");
  const [tableKey, setTableKey] = useState(0);
  const [telhados, setTelhados] = useState<any[]>([]);
  const [distribuidores, setDistribuidores] = useState<any[]>([]);
  const [isLoaded, setIsLoaded] = useState(false);

  // Filtros novos
  const [filtroStatus, setFiltroStatus] = useState<string>("1");
  const [filtroDistribuidor, setFiltroDistribuidor] = useState<string>("*");
  const [filtroMetodoCustoExtra, setFiltroMetodoCustoExtra] =
    useState<string>("*");
  const [filtroTipoTelhado, setFiltroTipoTelhado] = useState<string>("*");
  const [filtroCustoConsideradoLiberação, setFiltroCustoConsideradoLiberação] =
    useState<string>("*");
  const [filtroTipoNegocio, setFiltroTipoNegocio] = useState<string>("*");

  const tiposCustos = [
    {
      label: "Seleção",
      value: "0",
      handleSweetAlertHtml: `
        <div class="flex flex-col gap-2">
          <div>
            <div class="font-bold">
              Na Proposta:
            </div>
            <div>
              Será possível selecionar com uma checkbox (<input type="checkbox" />) se o valor entrará ou não no cálculo da precificação
            </div>
          </div>
        </div>
      `,
    },
    {
      label: "Seleção com Entrada",
      value: "1",
      handleSweetAlertHtml: `
        <div class="flex flex-col gap-2">
          <div>
            <div class="font-bold">
              Na Proposta:
            </div>
            <div>
              Igualmente a "Seleção" será possível selecionar se entrará no cálculo com a diferença de ser possível informar/alterar seu valor
            </div>
          </div>
        </div>
      `,
    },
    {
      label: "Automático",
      value: "2",
      handleSweetAlertHtml: `
        <div class="flex flex-col gap-2">
          <div>
            <div class="font-bold">
              Na Proposta:
            </div>
            <div>
              O valor automaticamente entrará no cálculo da precificação
            </div>
          </div>
        </div>
      `,
    },
  ];

  const optionsPercentuaisDe = [
    { label: "Valor do Kit", value: "1" },
    { label: "Valor do Produto", value: "2" },
    { label: "Valor do Serviço", value: "3" },
  ];

  function updateTableKey() {
    setTableKey(tableKey + 1);
  }

  useEffect(() => {
    Promise.all([
      listarTiposNegocios().then(async (tiposNegociosRes) => {
        const lojaData = await obterLoja({ id_loja });
        const tiposNegociosFiltered = tiposNegociosRes.filter((tp: any) =>
          lojaData?.tipos_negocios_loja.split(",").includes(tp.id_tipo_negocio)
        );
        // const tiposNegociosArr = tiposNegociosFiltered.map((tipo: any) => ({
        //   ...tipo,
        //   value: tipo.id_tipo_negocio,
        //   label: tipo.nome_tipo_negocio,
        // }));
        setTiposNegocios(tiposNegociosFiltered);
        setTodosTiposNegocios(tiposNegociosRes);
      }),
      listarTodosTiposTelhados().then((res) => {
        setTelhados(res);
      }),
      listarDistribuidores().then((res) => {
        res = [
          {
            id_distribuidor: "0",
            nome_distribuidor: "Kit Próprio",
            status_distribuidor: "1",
          },
          ...res,
        ];
        setDistribuidores(res);
        // setDistribuidores([
        //   { label: "Todos", value: "*" },
        //   ...res.map((distribuidor: any) => ({
        //     ...distribuidor,
        //     value: distribuidor.id_distribuidor,
        //     label: distribuidor.nome_distribuidor,
        //   })),
        // ]);
      }),
    ]).finally(() => setIsLoaded(true));
  }, []);

  useEffect(() => {
    listarCustosExtrasComParametros(
      filtroSelecionado,
      filtroTipoNegocio,
      tipoCustoSelecionado,
    );
    updateTableKey();
  }, [
    filtroStatus,
    filtroDistribuidor,
    filtroMetodoCustoExtra,
    filtroTipoTelhado,
    filtroCustoConsideradoLiberação,
    filtroTipoNegocio,
    tipoCustoSelecionado,
  ]);

  const listarCustosExtrasComParametros = (
    metodo: string,
    tipo_negocio: string,
    tipo_custo_extra: string
  ) => {
    return () =>
      listarCustosExtras({
        metodo,
        tipo_negocio,
        tipo_custo_extra,
        id_loja,
      });
  };

  const columns = [
    {
      header: "Código",
      accessorKey: "id_custo_extra",
    },
    {
      header: "Status",
      accessorKey: "status_custo_extra",
    },
    {
      header: "Tipos de Negócio",
      accessorKey: "tipoNegocio_custo_extra",
    },
    {
      header: "Nome",
      accessorKey: "nome_custo_extra",
    },
    {
      header: "Descrição para Proposta",
      accessorKey: "descricaoProposta_custo_extra",
    },
    {
      header: "Método do Custo Extra",
      accessorKey: "metodo_custo_extra",
    },
    {
      header: "Distribuidores",
      accessorKey: "distribuidores_custo_extra",
    },
    {
      header: "Tipos de telhado",
      accessorKey: "tiposTelhado_custo_extra",
    },
    {
      header: "Tipo de Custo",
      accessorKey: "tipo_custo_extra",
    },
    {
      header: "Valor",
      accessorKey: "qtd_custo_extra",
    },
    {
      header: "Unidade de cálculo",
      accessorKey: "unidade_custo_extra",
    },

    {
      header: "Percentual de",
      accessorKey: "percentualDe_custo_extra",
    },
    {
      header: "Fórmula",
      accessorKey: "formula_custo_extra",
    },
    {
      header: "Tabela Custos",
      accessorKey: "tabelaPrecos",
    },
  ];

  const metodoCustoExtraOptions = [
    { value: "*", label: "Todos" },
    { value: "1", label: "Tabela de Módulos" },
    { value: "2", label: "Tabela Potência do Inversor" },
    { value: "3", label: "Valor Fixo" },
    { value: "4", label: "Fórmula" },
    { value: "5", label: "Valor Percentual" },
    { value: "6", label: "Tabela Potência do Sistema" },
  ];

  const onSubmitFunction = async (data: FieldValues) => {
    data["loja_custo_extra"] = id_loja;

    if (!data["qtd_custo_extra"]) {
      data["qtd_custo_extra"] = null;
    }

    return cadastrarCustoExtra(data);
  };

  const onEdifFunction = async (data: FieldValues) => {
    data["loja_custo_extra"] = id_loja;

    if (
      data["status_custo_extra"] !== true &&
      data["status_custo_extra"] !== false &&
      (!data["qtd_custo_extra"] || data["qtd_custo_extra"] == 0)
    ) {
      data["qtd_custo_extra"] = null;
    }

    return editarCustoExtra(data);
  };

  function formatCustosExtras(arr: any[]) {
    return arr.map((e) => {
      e["distribuidores_custo_extra"] =
        e["distribuidores_custo_extra"] == "*"
          ? "Todos"
          : distribuidores
              .filter((distribuidor) =>
                e["distribuidores_custo_extra"]
                  ?.split(",")
                  .includes(distribuidor.id_distribuidor)
              )
              .map((distribuidor) => distribuidor.nome_distribuidor)
              .join(", ");
      e["tiposTelhado_custo_extra"] =
        e["tiposTelhado_custo_extra"] == "*"
          ? "Todos"
          : telhados.filter((telhado) =>
                e["tiposTelhado_custo_extra"]
                  ?.split(",")
                  .includes(telhado.id_telhado)
              ).length > 3
            ? telhados
                .filter((telhado) =>
                  e["tiposTelhado_custo_extra"]
                    ?.split(",")
                    .includes(telhado.id_telhado)
                )
                .filter((telhado, i) => i < 3)
                .map((telhado) => telhado.nome_telhado)
                .join(", ") + ", ..."
            : telhados
                .filter((telhado) =>
                  e["tiposTelhado_custo_extra"]
                    ?.split(",")
                    .includes(telhado.id_telhado)
                )
                .map((telhado) => telhado.nome_telhado)
                .join(", ");
      e["consideraCompraMaterial_custo_extra"] =
        e["consideraCompraMaterial_custo_extra"] === "1" ? "Sim" : "Não";
      e["qtd_custo_extra"] = !["1", "2", "5"].includes(e["metodo_custo_extra"])
        ? e["unidade_custo_extra"] == "1"
          ? FormatFields.formatarNumero(e.qtd_custo_extra) + "%"
          : formatarValor(e.qtd_custo_extra)
        : "";
      e["tabelaPrecos"] = e["tabelaPrecos"]?.length > 0 && (
        <div className="table">
          <div className="table-row-group">
            <div className="table-row">
              <div className="table-cell px-2 py-1 border-b border-b-black-2">
                De {e["metodo_custo_extra"] == "1" ? "" : "(kW)"}
              </div>
              <div className="table-cell px-2 py-1 border-b border-b-black-2">
                Até {e["metodo_custo_extra"] == "1" ? "" : "(kW)"}
              </div>
              <div className="table-cell px-2 py-1 border-b border-b-black-2">
                Valor
              </div>
            </div>
            {e["tabelaPrecos"].map(
              (precoExtra: any, indexPrecoExtra: number) => (
                <div className="table-row" key={indexPrecoExtra}>
                  <div className="table-cell px-2 py-1">
                    {/* {Number(precoExtra.de_custo_extra_tabela).toFixed(0)} */}
                    {e["metodo_custo_extra"] == "1"
                      ? Number(precoExtra.de_custo_extra_tabela).toFixed(0)
                      : FormatFields.formatarNumero(
                          precoExtra.de_custo_extra_tabela
                        )}
                  </div>
                  <div className="table-cell px-2 py-1">
                    {/* {Number(precoExtra.ate_custo_extra_tabela).toFixed(0)} */}
                    {e["metodo_custo_extra"] == "1"
                      ? Number(precoExtra.ate_custo_extra_tabela).toFixed(0)
                      : FormatFields.formatarNumero(
                          precoExtra.ate_custo_extra_tabela
                        )}
                  </div>
                  <div className="table-cell px-2 py-1">
                    {formatarValor(precoExtra.qtd_custo_extra_tabela)}
                  </div>
                </div>
              )
            )}
          </div>
        </div>
      );
      e["tipo_custo_extra"] = tiposCustos.find(
        (tipoCusto) => tipoCusto.value == e["tipo_custo_extra"]
      )?.label;
      e["formula_custo_extra"] =
        e["metodo_custo_extra"] == "4"
          ? [
              {
                label: "Fórmula Multiplicação da Entrada",
                value: "1",
              },
              {
                label: "Fórmula Multiplicação da Média de Dias",
                value: "2",
              },
              {
                label: "Fórmula Multiplicação Qtd Módulos",
                value: "3",
              },
              {
                label: "Fórmula Multiplicação Potência Sistema",
                value: "4",
              },
              {
                label: "Fórmula Multiplicação Qtd UCs",
                value: "5",
              },
            ].find(
              (formulaCusto) => formulaCusto.value == e["formula_custo_extra"]
            )?.label
          : "";
      e["percentualDe_custo_extra"] =
        e["unidade_custo_extra"] == "1"
          ? optionsPercentuaisDe.find(
              (percentual) => percentual.value == e["percentualDe_custo_extra"]
            )?.label
          : "";
      e["unidade_custo_extra"] =
        e["unidade_custo_extra"] == "0" ? "Valor R$" : "Percentual %";

      e["tipoNegocio_custo_extra"] =
        e["id_tipo_negocio_custo_extra"] == "*"
          ? "Todos"
          : // tiposNegocios
            todosTiposNegocios
              .filter(
                (tipoNegocio) =>
                  e["id_tipo_negocio_custo_extra"]
                    ?.split(",")
                    .includes(tipoNegocio.id_tipo_negocio) ||
                  e["id_tipo_negocio_custo_extra"] == "*"
              )
              .map((tipoNegocio) => tipoNegocio.nome_tipo_negocio)
              .join(", ") || "-";

      // Formatar Método do Custo Extra
      e["metodo_custo_extra"] =
        metodoCustoExtraOptions.find(
          (metodo) => metodo.value == e["metodo_custo_extra"]
        )?.label || "-";

      return e;
    });
  }

  function formatExcelCustosExtras({ data, originalData, columns, name }: any) {
    const newData: any[] = [];

    originalData.map((originalValues: any, indexOriginalValues: number) => {
      const tabelaPrecos = originalValues["tabelaPrecos"];
      if (tabelaPrecos?.length > 0) {
        tabelaPrecos.map((preco: any) => {
          preco["de_custo_extra_tabela"] =
            originalValues["metodo_custo_extra"] == "1"
              ? Number(preco.de_custo_extra_tabela).toFixed(0)
              : preco.de_custo_extra_tabela;
          // : FormatFields.formatarNumero(preco.de_custo_extra_tabela);
          preco["ate_custo_extra_tabela"] =
            originalValues["metodo_custo_extra"] == "1"
              ? Number(preco.ate_custo_extra_tabela).toFixed(0)
              : preco.ate_custo_extra_tabela;
          // : FormatFields.formatarNumero(preco.ate_custo_extra_tabela);
          newData.push({
            ...data[indexOriginalValues],
            // de_custo_extra_tabela: "",
            // ate_custo_extra_tabela: "",
            // qtd_custo_extra_tabela: "",
            ...preco,
          });
        });
      } else {
        newData.push(data[indexOriginalValues]);
      }
    });

    const newColumns = [
      ...columns,
      {
        header: "Tabela de Custos De",
        accessorKey: "de_custo_extra_tabela",
      },
      {
        header: "Tabela de Custos Até",
        accessorKey: "ate_custo_extra_tabela",
      },
      {
        header: "Tabela de Custos Valor",
        accessorKey: "qtd_custo_extra_tabela",
      },
    ];
    newColumns.splice(columns.length - 1, 1);
    return { data: newData, columns: newColumns, name };
  }

  const CustomForm = useCallback(
    (props: any) => (
      <FormCustosExtras
        telhados={telhados}
        distribuidores={distribuidores}
        tiposCustos={tiposCustos}
        optionsPercentuaisDe={optionsPercentuaisDe}
        tiposNegocios={tiposNegocios}
        todosTiposNegocios={todosTiposNegocios}
        {...props}
      />
    ),
    [distribuidores, optionsPercentuaisDe, telhados, tiposCustos, tiposNegocios]
  );

  const listFunctionFiltrada = useCallback(async () => {

    const res = await listarCustosExtras({
      metodo: filtroSelecionado,
      tipo_negocio: "*",
      tipo_custo_extra: tipoCustoSelecionado,
      id_loja,
    });

    return res.filter((e: any) => {
      const statusOk =
        filtroStatus === "*" || e.status_custo_extra == filtroStatus;

      const distribuidorOk =
        filtroDistribuidor === "*" ||
        !e.distribuidores_custo_extra ||
        e.distribuidores_custo_extra == "*" ||
        e.distribuidores_custo_extra?.split(",").includes(filtroDistribuidor);

      const metodoCustoOk =
        filtroMetodoCustoExtra === "*" ||
        !e.metodo_custo_extra ||
        e.metodo_custo_extra == "*" ||
        e.metodo_custo_extra == filtroMetodoCustoExtra;

      const tipoTelhadoOk =
        filtroTipoTelhado === "*" ||
        !e.tiposTelhado_custo_extra ||
        e.tiposTelhado_custo_extra == "*" ||
        e.tiposTelhado_custo_extra.split(",").includes(filtroTipoTelhado);

      const tipoNegocioOk =
        filtroTipoNegocio === "*" ||
        !e.id_tipo_negocio_custo_extra ||
        e.id_tipo_negocio_custo_extra == "*" ||
        e.id_tipo_negocio_custo_extra
          .split(",")
          .map((v: string) => v.trim()) // ✅ remove espaços extras
          .includes(filtroTipoNegocio);

      const custoLibOk =
        filtroCustoConsideradoLiberação === "*" ||
        e.considerar_lib_custo_extra == filtroCustoConsideradoLiberação;

      return (
        statusOk &&
        distribuidorOk &&
        tipoTelhadoOk &&
        tipoNegocioOk &&
        metodoCustoOk
      );
    });
  }, [
    filtroSelecionado,
    tipoCustoSelecionado,
    filtroStatus,
    filtroMetodoCustoExtra,
    filtroDistribuidor,
    filtroTipoTelhado,
    filtroTipoNegocio,
    id_loja,
  ]);

  const tableKeyD = `${tipoNegocioSelecionado}-${filtroDistribuidor}-${filtroTipoTelhado}-${filtroStatus}-${filtroMetodoCustoExtra}-${filtroTipoNegocio}-${tipoCustoSelecionado}-${tableKey}`;
  return (
    <>
      {isLoaded ? (
        <Container>
          {/* ── Filtros ── */}
          <div className="p-3 rounded-md relative border border-black/20 mb-4">
            <span className="bg-white dark:bg-black px-2 absolute -top-3 font-semibold text-sm">
              Filtros
            </span>
            <div className="flex flex-wrap gap-3">
              {/* Filtro Tipos de Negócio */}
              <div className="min-w-[180px] flex-1">
                <InputSelectComponent
                  name="filtro_tipo_negocio"
                  label="Tipo de Negócio"
                  options={[
                    { label: "Todos", value: "*" },
                    ...tiposNegocios.map((tipoNegocio) => ({
                      label: tipoNegocio.nome_tipo_negocio,
                      value: tipoNegocio.id_tipo_negocio,
                    })),
                  ]}
                  onChange={(e: any) => {
                    setFiltroTipoNegocio(e?.value ?? "*");
                  }}
                  defaultValue={filtroTipoNegocio}
                  width="w-full"
                />
              </div>

              {/* Filtro Status */}
              <div className="min-w-[150px] flex-1">
                <InputSelectComponent
                  name="filtro_status"
                  label="Status"
                  options={[
                    { label: "Todos", value: "*" },
                    { label: "Ativo", value: "1" },
                    { label: "Inativo", value: "0" },
                  ]}
                  onChange={(e: any) => {
                    setFiltroStatus(e?.value ?? "1");
                  }}
                  defaultValue={filtroStatus}
                  width="w-full"
                />
              </div>
              <div className="min-w-[150px] flex-1">
                <InputSelectComponent
                  name="filtro_metodo"
                  label="Método Custo Extra"
                  options={metodoCustoExtraOptions}
                  onChange={(e: any) => {
                    setFiltroMetodoCustoExtra(e?.value ?? "*");
                  }}
                  defaultValue={filtroMetodoCustoExtra}
                  width="w-full"
                />
              </div>

              <div className="min-w-[180px] flex-1">
                <InputSelectComponent
                  name="filtro_tipo_custo"
                  label="Tipo de Custo"
                  options={[
                    { label: "Todos", value: "*" },
                    ...tiposCustos.map((tipo) => ({
                      label: tipo.label,
                      value: tipo.value,
                    })),
                  ]}
                  onChange={(e: any) => {
                    setTipoCustoSelecionado(e?.value ?? "*");
                  }}
                  defaultValue={tipoCustoSelecionado}
                  width="w-full"
                />
              </div>

              {/* Filtro Distribuidores */}
              <div className="min-w-[180px] flex-1">
                <InputSelectComponent
                  name="filtro_distribuidor"
                  label="Distribuidor"
                  options={[
                    { label: "Todos", value: "*" },
                    ...distribuidores.map((d) => ({
                      label: d.nome_distribuidor,
                      value: d.id_distribuidor,
                    })),
                  ]}
                  onChange={(e: any) => {
                    setFiltroDistribuidor(e?.value ?? "*");
                  }}
                  defaultValue={filtroDistribuidor}
                  width="w-full"
                />
              </div>

              <div className="min-w-[180px] flex-1">
                <InputSelectComponent
                  name="filtro_tipo_telhado"
                  label="Tipo de Telhado"
                  options={[
                    { label: "Todos", value: "*" },
                    ...telhados.map((t) => ({
                      label: t.nome_telhado,
                      value: t.id_telhado,
                    })),
                  ]}
                  onChange={(e: any) => {
                    setFiltroTipoTelhado(e?.value ?? "*");
                  }}
                  defaultValue={filtroTipoTelhado}
                  width="w-full"
                />
              </div>
            </div>
          </div>

          <ReactTable
            key={tableKeyD}
            columns={columns}
            listFunction={listFunctionFiltrada}
            formatFunction={formatCustosExtras}
            idCol="id_custo_extra"
            isActiveCol="status_custo_extra"
            canEdit
            canDesactive
            editFunction={onEdifFunction}
            createFunction={onSubmitFunction}
            Form={CustomForm}
            pageName="Custos Extras"
            actionButtons={(
              rowData: any,
              updateTable: any,
              setIsLoading: any,
              { idCol, isActive, isActiveCol, pageName, editFunction }: any
            ) => [
              {
                className: `navButton buttonDanger`,
                onClick: (e: any) => {
                  handleSweetAlert(
                    {
                      icon: "warning",
                      title: `Exclusão de ${pageName}`,
                      html: `Tem certeza que deseja <b>Excluir</b> o registro ${rowData[idCol]}?`,
                    },
                    async () => {
                      return deletarCustoExtra(rowData).then(() =>
                        updateTable()
                      );
                    }
                  );
                },
                content: <Trash />,
              },
            ]}
            formatExcel={formatExcelCustosExtras}
          />
        </Container>
      ) : (
        <div className="w-full h-[500px] flex flex-col justify-center items-center">
          <LoaderSun />
        </div>
      )}
    </>
  );
};

export default CustosExtras;
