import Button from "@/components/Forms/Button";
import { useAuth } from "@/src/contexts/authContext";
import { ArrowLeft, ArrowRight, Loader } from "lucide-react";
import { useEffect, useState } from "react";

const ResumoValoresTrocaInversor = ({
  novosInversoresSelecionados,
  inversoresAntigos,
  setCanChangeView,
  valorProposta,
  loaded,
  handleChangeTrigger,
}: any) => {
  const { usuario } = useAuth();
  const [totalGeralFormatado, setTotalGeralFormatado] = useState<any>();
  const [totalDesconto, setTotalDesconto] = useState("");
  const [valueDiscount, setValueDiscount] = useState<any>();

  const totalNovosInversores = novosInversoresSelecionados.reduce(
    (acc: number, item: any) => {
      const preco = parseFloat(item.precoUnitario_item) || 0;
      const qtd = parseInt(item.qtd_item) || 1;
      return acc + preco * qtd;
    },
    0
  );

  const totalInversoresAntigos = inversoresAntigos
    .filter((a: any) => a.tipo_item === "8")
    .reduce((acc: number, item: any) => {
      const preco = parseFloat(item.precoUnitario_item) || 0;
      const qtd = parseInt(item.qtd_item) || 1;
      return acc + preco * qtd;
    }, 0);

  const totalGeral =
    parseFloat(valorProposta) - totalInversoresAntigos + totalNovosInversores;
  const valorPropostaFormatado = parseFloat(valorProposta).toLocaleString(
    "pt-BR",
    {
      style: "currency",
      currency: "BRL",
    }
  );
  const totalAntigosFormatado = totalInversoresAntigos.toLocaleString("pt-BR", {
    style: "currency",
    currency: "BRL",
  });

  const totalFormatado = totalNovosInversores.toLocaleString("pt-BR", {
    style: "currency",
    currency: "BRL",
  });
  useEffect(() => {
    setTotalGeralFormatado(totalGeral);
  }, []);

  const handleChangeDiscount = (e: any) => {
    const valorInput = parseFloat(valueDiscount);
    const descontoMaximoPercentual = usuario?.max_desconto_usuario || 0;

    const descontoMaximoValor = (totalGeral * descontoMaximoPercentual) / 100;

    if (valorInput > descontoMaximoValor) {
      alert(
        `Desconto máximo permitido é de R$ ${descontoMaximoValor.toFixed(2)}`
      );

      e.target.value = descontoMaximoValor.toFixed(2);
      return;
    }
    setTotalDesconto(
      valorInput.toLocaleString("pt-BR", {
        style: "currency",
        currency: "BRL",
      })
    );
    const valorComDesconto = totalGeral - valorInput;
    setTotalGeralFormatado(valorComDesconto);
  };

  return (
    <div className="w-full py-2 text-black">
      <div
        onClick={() => setCanChangeView(false)}
        className="flex gap-3 hover:opacity-40 cursor-pointer items-center"
      >
        <ArrowLeft size={17} />
        <span className="text-md">Voltar</span>
      </div>
      <div className="w-full  text-center mb-3 justify-center">
        <span className="underline text-lg w-full">Resumo de alteração</span>
      </div>

      <div className="flex justify-between mt-7 text-md items-center">
        <div className="border relative rounded-md p-2">
          <span className="absolute -top-3 bg-white px-4">
            Inversores antigos
          </span>
          <div className="px-4 mt-3 flex-wrap ">
            {inversoresAntigos
              .filter((a: any) => a.tipo_item === "8")
              .map((inversorAntigo: any, i: number) => (
                <div className="flex items-center gap-2" key={i}>
                  <span className="p-1 bg-stroke px-3 rounded-md">
                    {inversorAntigo.qtd_item}x
                  </span>
                  <span>{inversorAntigo.descricao_item}</span>
                  {usuario?.visualiza_custo_kit_usuario === "1" && (
                    <span className="p-1 px-2 rounded-md font-medium text-sm bg-meta-3">
                      R$
                      {Number(inversorAntigo.precoUnitario_item).toLocaleString(
                        "pt-BR",
                        {
                          minimumFractionDigits: 2,
                          maximumFractionDigits: 2,
                        }
                      )}
                    </span>
                  )}
                </div>
              ))}
          </div>
        </div>
        <ArrowRight />
        <div className="border relative rounded-md p-2">
          <span className="absolute -top-3 bg-white px-4">
            Inversores novos
          </span>
          <div className="flex mt-3 flex-col gap-4 px-4 ">
            {novosInversoresSelecionados.map((inversor: any, i: number) => (
              <div className="flex items-center gap-2" key={i}>
                <span className="p-1 bg-stroke px-3 rounded-md">
                  {inversor.qtd_item ?? "1"}x
                </span>
                <span>{inversor.descricao_item}</span>
                {usuario?.visualiza_custo_kit_usuario === "1" && (
                  <span className="p-1 px-2 rounded-md font-medium text-sm bg-meta-3">
                    R$
                    {Number(inversor.precoUnitario_item).toLocaleString(
                      "pt-BR",
                      {
                        minimumFractionDigits: 2,
                        maximumFractionDigits: 2,
                      }
                    )}
                  </span>
                )}
              </div>
            ))}
          </div>
        </div>
      </div>
      <div className="mt-2">
        <hr />
        <div className="w-full flex text-center gap-9 mt-3 justify-end">
          <span className="">Valor atual da Proposta: </span>
          <span className="">{valorPropostaFormatado}</span>
        </div>
        <div className="w-full flex text-center gap-9 mt-3 justify-end">
          <span className="">Valor inversores antigos: </span>
          <span className="text-meta-1">-{totalAntigosFormatado}</span>
        </div>
        <div className="w-full flex text-center gap-9 mt-3 justify-end">
          <span className="">Valor inversores novos: </span>
          <span className="text-meta-3">+{totalFormatado}</span>
        </div>
        <div className=" flex w-full justify-end my-2">
          <div className="bg-stroke w-67 h-[1px]"></div>
        </div>
        <div className="w-full flex text-center text-sm gap-2 mt-3 justify-end">
          <input
            className="border text-center rounded-md px-2"
            placeholder="Desconto"
            onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
              let value = e.target.value;

              // Remove tudo que não for número
              const numericValue = value.replace(/\D/g, "");

              // Divide por 100 para manter duas casas decimais
              const float = parseFloat(numericValue) / 100;

              // Formata para moeda BRL
              const formatted = float.toLocaleString("pt-BR", {
                style: "currency",
                currency: "BRL",
              });

              e.target.value = formatted;

              // Atualiza o valor limpo no estado
              setValueDiscount(float);
            }}
          />
          <div
            onClick={handleChangeDiscount}
            className="bg-meta-5 cursor-pointer rounded-md p-1 px-3"
          >
            <span className="text-white ">Aplicar</span>
          </div>
        </div>
        {totalDesconto !== "" && (
          <div className="w-full flex text-center gap-9 mt-3 justify-end">
            <span className="">Desconto: </span>
            <span className="text-meta-1">-{totalDesconto}</span>
          </div>
        )}
        <div className="w-full flex text-center gap-9 mt-3 justify-end">
          <span className="">Valor total: </span>
          <span className="text-meta-3">
            {totalGeralFormatado?.toLocaleString("pt-BR", {
              style: "currency",
              currency: "BRL",
            })}
          </span>
        </div>
        <div className="w-full flex text-center gap-9 mt-9 justify-end">
          <Button
            className=" bottom-0 w-2/5 bf bg-primary text-sm"
            type="button"
            disabled={novosInversoresSelecionados.length === 0 || loaded}
            onClick={() => {
              handleChangeTrigger(totalGeralFormatado);
            }}
          >
            {loaded ? (
              <span className="mr-3 size-5 animate-spin ">
                <Loader />
              </span>
            ) : (
              <span>Confirmar troca</span>
            )}
          </Button>
        </div>
      </div>
    </div>
  );
};

export default ResumoValoresTrocaInversor;
