import {
  Kit,
  QuadroDeCustosData,
  Servico,
  Total,
} from "@/types/QuadroDeCustos";
import { formatarValor, FormatFields } from "@/utils";
import React from "react";
interface CustoProps {
  data: QuadroDeCustosData;
  valorProjeto: any;
  // form?: any;
}
const QuadroDeCustos: React.FC<CustoProps> = ({
  data,
  valorProjeto,
  // form
}) => {
  const somaPercentuais = data.custos.reduce((total, item) => {
    const percentualNumerico = parseFloat(item?.percentual.replace(",", "."));
    return total + percentualNumerico;
  }, 0);
  const formatarNumero = FormatFields.formatarNumero;

  const somaValores = data.custos.reduce((total, item) => {
    let valorFormatado = item.valor.trim();

    if (valorFormatado.includes(",")) {
      valorFormatado = valorFormatado.replace(/\./g, "").replace(",", ".");
    }
    const valorNumerico = parseFloat(valorFormatado) || 0;

    return total + valorNumerico;
  }, 0);

  const somaValoresAplicandoPoliticaPrecoVenda = (namesToInclude: any) =>
    data.custos.reduce((total, item) => {
      if (namesToInclude.some((term: any) => item.descricao.includes(term))) {
        return total; // Skip items that match any of the excluded terms
      }
      let valorFormatado = item.valor.trim();

      if (valorFormatado.includes(",")) {
        valorFormatado = valorFormatado.replace(/\./g, "").replace(",", ".");
      }
      const valorNumerico = parseFloat(valorFormatado) || 0;

      return total + valorNumerico;
    }, 0);

  const calcularSomaValores = (itens: (Kit | Servico | Total)[]) => {
    return itens.reduce((total, item) => {
      let valorFormatado = item.valor.trim();

      if (valorFormatado.includes(",")) {
        valorFormatado = valorFormatado.replace(/\./g, "").replace(",", ".");
      }
      const valorNumerico = parseFloat(valorFormatado) || 0;

      return total + valorNumerico;
    }, 0);
  };

  const calcularSomaLucros = (itens: (Kit | Servico | Total)[]) => {
    return itens.reduce((total, item) => {
      if (item?.title && item?.title.toUpperCase().includes("LUCRO")) {
        let valorFormatado = item.valor.trim();

        if (valorFormatado.includes(",")) {
          valorFormatado = valorFormatado.replace(/\./g, "").replace(",", ".");
        }
        const valorNumerico = parseFloat(valorFormatado) || 0;
        return total + valorNumerico;
      }
      return total;
    }, 0);
  };
  const calcularSomaCustos = () => {
    const somaValoresKit = calcularSomaValores(data.kit);
    const somaValoresServico = calcularSomaValores(data.servico);
    const somaValoresTotal = calcularSomaValores(data.total);
    const calculo = data.custos
      .filter((custo) => custo.class === "custoASomar")
      .reduce((total, item) => {
        let valorFormatado = item.valor.trim();
        if (valorFormatado.includes(",")) {
          valorFormatado = valorFormatado.replace(/\./g, "").replace(",", ".");
        }

        const valorNumerico = parseFloat(valorFormatado) || 0;

        return total + valorNumerico;
      }, 0);
    return calculo + somaValoresKit + somaValoresServico + somaValoresTotal;
  };
  const calcularSomaTotalProjeto = () => {
    const calculoSomaLucros = calcularSomaLucros(
      [data.kit, data.servico, data.total].flat().filter(Boolean)
    );
    const calculoSomaCustos = calcularSomaCustos();

    return calculoSomaLucros + calculoSomaCustos;
  };
  function getPorcentagemPorValor(valor: number, total: number) {
    if (isNaN(valor)) {
      valor = 0;
    }
    const porcentagem = (valor / total) * 100;
    return porcentagem.toFixed(2) + "%";
  }
  const percentLucro =
    (calcularSomaLucros(
      [data.kit, data.servico, data.total].flat().filter(Boolean)
    ) /
      somaValores) *
    100;
  const teste =
    calcularSomaCustos() -
    calcularSomaLucros(
      [data.kit, data.servico, data.total].flat().filter(Boolean)
    );
  // form?.setValue(
  //   "totalProjeto",
  //   calcularSomaCustos() -
  //     calcularSomaLucros(
  //       [data.kit, data.servico, data.total].flat().filter(Boolean)
  //     ) +
  //     calcularSomaLucros(
  //       [data.kit, data.servico, data.total].flat().filter(Boolean)
  //     )
  // );

  const percentCusto = (teste / somaValores) * 100;
  const calculosTotaisProjeto = [
    {
      title: "TOTAL DO LUCRO DO PROJETO",
      valor: formatarValor(
        calcularSomaLucros(
          [data.kit, data.servico, data.total].flat().filter(Boolean)
        )
      ),
      percent: percentLucro,
    },
    {
      title: "TOTAL DE CUSTOS PROJETO",
      valor: formatarValor(
        calcularSomaCustos() -
          calcularSomaLucros(
            [data.kit, data.servico, data.total].flat().filter(Boolean)
          )
      ),
      percent: percentCusto,
    },
    {
      title: "TOTAL DO PROJETO",
      valor: formatarValor(
        calcularSomaCustos() -
          calcularSomaLucros(
            [data.kit, data.servico, data.total].flat().filter(Boolean)
          ) +
          calcularSomaLucros(
            [data.kit, data.servico, data.total].flat().filter(Boolean)
          )
      ),
      percent: percentLucro + percentCusto,
    },
  ];

  const renderizarTabela = (
    dados: (Kit | Servico | Total)[],
    somaValores: number,
    tituloTotal: string
  ) => (
    <table className="custos-table">
      <>
        <thead>
          <tr>
            <th>{dados[0].sobre}</th>
            <th>{formatarValor(dados[0].valor)}</th>
            <th>{dados[0].percent}%</th>
          </tr>
        </thead>
        <tbody>
          {dados.slice(1).map((item, index) => (
            <tr key={index}>
              <td
                className={`font-bold ${item.title?.includes("LUCRO") ? "text-success" : ""}`}
              >
                {item.title}
              </td>
              <td
                className={`font-bold ${item.title?.includes("LUCRO") ? "text-success" : ""}`}
              >
                {formatarValor(item.valor)}
              </td>
              <td>
                {item.title === "TOTAL DO SERVIÇO"
                  ? item.percent
                  : formatarNumero(item.percent) + "%"}
              </td>
            </tr>
          ))}
          <tr>
            <td className={`text-danger`}>{tituloTotal}</td>
            <td className={`text-danger`}>{formatarValor(somaValores)}</td>
          </tr>
        </tbody>
      </>
    </table>
  );
  const somaValoresKit = calcularSomaValores(data.kit);
  const somaValoresServico = calcularSomaValores(data.servico);
  const somaValoresTotal = calcularSomaValores(data.total);
  return (
    <div className="justify-center grid">
      <h2 className="font-bold text-center max-sm:text-sm mb-2 text-lg uppercase my-2 border-b-2 border-meta-5/70">
        Quadro de Custos e Lucro
      </h2>

      <table className="custos-table">
        <thead>
          <tr>
            <th>Descrição do item</th>
            <th>Valor</th>
            <th>% Ref ao Total</th>
          </tr>
        </thead>
        <tbody>
          {data.custos.map((item, index) => (
            <tr key={index}>
              <td>{item.descricao}</td>
              <td className={index == 0 ? "text-primary" : "text-danger"}>
                {formatarValor(Number(item.valor))}
              </td>
              <td>{getPorcentagemPorValor(Number(item.valor), somaValores)}</td>
            </tr>
          ))}
          <tr className="font-bold bg-[#b7b7b7] text-black">
            <td>PREÇO DE VENDA APLICANDO A POLÍTICA DE COMISSÃO</td>
            <td>{formatarValor(somaValores)}</td>
            <td>{somaPercentuais}%</td>
          </tr>
        </tbody>
      </table>
      <table className="custos-table bg-[#f5de0f]  border-2 border-meta-6 text-black bg-opacity-60 font-semibold">
        <thead>
          <tr>
            <td className="!border-meta-6">Custo do Kit + Custos Adicionais</td>
            <td className="!border-meta-6">
              {" "}
              {formatarValor(
                somaValoresAplicandoPoliticaPrecoVenda(["COMISSÃO", "TOTAL"])
              )}
            </td>
          </tr>
          <tr>
            <td>PREÇO DE VENDA APLICANDO A POLÍTICA DE PREÇO</td>
            <td>
              {formatarValor(
                somaValoresAplicandoPoliticaPrecoVenda(["COMISSÃO"])
              )}
            </td>
          </tr>
        </thead>
      </table>

      {renderizarTabela(
        data.kit,
        somaValoresKit,
        "Total Custos sobre o PRODUTO"
      )}
      {renderizarTabela(
        data.servico,
        somaValoresServico,
        "Total Custos sobre o SERVICO"
      )}
      {renderizarTabela(
        data.total,
        somaValoresTotal,
        "Total Custos sobre o TOTAL"
      )}
      <table className="custos-table">
        {calculosTotaisProjeto.map((calc, i) => (
          <tr className="font-bold  bg-[#b7b7b7] text-black" key={i}>
            <td
              className={`font-bold ${calc.title?.includes("LUCRO") ? "bg-[#1b8a0b]/80 text-white" : calc.title?.includes("CUSTOS") ? "bg-danger/80 text-white" : "bg-[#ffff00]/80"}`}
            >
              {calc.title}
            </td>
            <td
              className={`font-bold ${calc.title?.includes("LUCRO") ? "bg-success/80 text-white" : calc.title?.includes("CUSTOS") ? "bg-danger/80 text-white" : "bg-[#ffff00]/80"}`}
            >
              {calc.valor}
            </td>
            <td
              className={`${calc.title?.includes("TOTAL DO PROJETO") && "bg-[#ffff00]/80"}`}
            >
              {formatarNumero(calc.percent)}%
            </td>
          </tr>
        ))}
      </table>

      {data.baseImposto && (
        <>
          <h2 className="font-bold text-center max-sm:text-sm mb-2 text-lg uppercase my-2 border-b-2 border-meta-5/70">
            Base do Imposto
          </h2>
          <table className="custos-table">
            <thead>
              <tr>
                <th>Valor Base para o Imposto</th>
                <th>% Do Imposto</th>
                <th>Valor do Imposto</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td>{formatarValor(Number(data.baseImposto.valorBase))}</td>
                <td>
                  {formatarNumero(Number(data.baseImposto.percentual))}%
                </td>
                <td className="text-danger">
                  {formatarValor(Number(data.baseImposto.valorImposto))}
                </td>
              </tr>
            </tbody>
          </table>
        </>
      )}
    </div>
  );
};

export default QuadroDeCustos;
