import ModalComponente from "@/components/Modal/ModalComponente";
import { listarUsuarios } from "@/requests/CRM/Dashboard/listarDashboard";
import { listarPerfis } from "@/requests/CRUD/Perfil/listarPerfis";
import {
  cadastrarAutomacaoTarefa,
  editarAutomacaoTarefa,
  excluirAutomacaoTarefa,
} from "@/requests/CRUD/Tarefa/cadastrarTarefa";
import {
  listarAutomacoesTarefa,
  listarTarefasGeradas,
} from "@/requests/CRUD/Tarefa/listarTarefas";
import { listarTiposTarefas } from "@/requests/CRUD/Tarefa/listarTipoTarefa";
import { useKanbanContext } from "@/src/contexts/kanbanContext";
import { useEffect, useState } from "react";
import Swal from "sweetalert2";
import FormTarefasGeradas from "./formTarefasGeradas";

const CardTarefas = ({
  etapas,
  selectedFunilDestiny,
  setSelectedFunilDestiny,
  idEtapa,
  funis,
}: any) => {
  const [automacoesTarefa, setAutomacoesTarefa] = useState<any>([]);
  const [tiposTarefas, setTiposTarefas] = useState<any>([]);
  const [tarefasGeradas, setTarefasGeradas] = useState<any>([]);
  const { listarDadosKanban } = useKanbanContext();

  const [openModalCadastro, setOpenModalCadastro] = useState(false);
  const [openModalEdicao, setOpenModalEdicao] = useState<any>(false);
  const [usuarios, setUsuarios] = useState<any>([]);
  const [perfis, setPerfis] = useState<any>([]);

  useEffect(() => {
    listarTiposTarefas().then((res) => {
      setTiposTarefas(res);
    });
    listarUsuarios().then((res) => {
      setUsuarios(res);
    });
    listarPerfis().then((res) => {
      setPerfis(res);
    });
    listarTarefasGeradas().then((res) => {
      setTarefasGeradas(res);
    });
  }, []);

  useEffect(() => {
    listarAutomacoesTarefa(idEtapa).then((res) => {
      setAutomacoesTarefa(res);
    });
  }, [openModalCadastro, openModalEdicao]);

  const submitAutomacaoTarefa = (data: any) => {
    if (data["usuario_tarefa_id"]?.length > 0) {
      data["usuario_tarefa_id"] = data["usuario_tarefa_id"]?.join(",");
    }
    if (data["perfil_tarefa_id"]?.length > 0) {
      data["perfil_tarefa_id"] = data["perfil_tarefa_id"]?.join(",");
    }

    data["etapa_automacao_id"] = idEtapa;
    return cadastrarAutomacaoTarefa(data).then((res) =>
      setOpenModalCadastro(false),
    );
  };

  const formatarMudancas = (
    antigos: any,
    novos: any,
    opcoes: {
      etapas: any[];
      funis: any[];
      tiposTarefas: any[];
      usuarios: any[];
      perfis: any[];
      tarefasLoja: any[];
    },
  ): string[] => {
    const mudancas: string[] = [];

    const getNome = (
      id: any,
      lista: any[] = [],
      campoId: string = "id",
      campoNome: string = "nome",
    ) => {
      if (!Array.isArray(lista)) {
        return typeof lista === "string" ? lista : id;
      }
      return (
        lista.find((item) => item[campoId] == id)?.[campoNome] ?? id ?? "nenhum"
      );
    };

    for (const campo in novos) {
      const antigo = antigos[campo];
      const novo = novos[campo];
      if (antigo === novo || (antigo == null && novo == null)) continue;

      let nomeCampo = campo
        .replace(/_/g, " ")
        .replace(/\b\w/g, (l) => l.toUpperCase());
      let valorAntigo = antigo;
      let valorNovo = novo;

      switch (campo) {
        case "etapa_destino_id":
          valorAntigo = getNome(
            antigo,
            opcoes.etapas,
            "id_etapa_funil",
            "titulo_etapa_funil",
          );
          valorNovo = getNome(
            novo,
            opcoes.etapas,
            "id_etapa_funil",
            "titulo_etapa_funil",
          );
          break;
        case "funil_destino_id":
          valorAntigo = getNome(
            antigo,
            opcoes.funis,
            "id_funil",
            "titulo_funil",
          );
          valorNovo = getNome(novo, opcoes.funis, "id_funil", "titulo_funil");
          break;
        case "tipo_tarefa_id":
          valorAntigo = getNome(
            antigo,
            opcoes.tiposTarefas,
            "id_tipo_tarefa",
            "nome_tipo_tarefa",
          );
          valorNovo = getNome(
            novo,
            opcoes.tiposTarefas,
            "id_tipo_tarefa",
            "nome_tipo_tarefa",
          );
          break;
        case "responsavel_tarefa_id":
          valorAntigo = getNome(
            antigo,
            opcoes.usuarios,
            "id_usuario",
            "nome_usuario",
          );
          valorNovo = getNome(
            novo,
            opcoes.usuarios,
            "id_usuario",
            "nome_usuario",
          );
          break;
        case "usuario_tarefa_id":
          if (antigo) {
            const usuariosAntigos = antigo
              .split(",")
              .map((id: any) =>
                getNome(id, opcoes.usuarios, "id_usuario", "nome_usuario"),
              );
            valorAntigo = usuariosAntigos.join(", ");
          }

          if (novo) {
            const novosIds = Array.isArray(novo) ? novo : novo.split(",");
            const usuariosNovos = novosIds.map((id: any) =>
              getNome(id, opcoes.usuarios, "id_usuario", "nome_usuario"),
            );
            valorNovo = usuariosNovos.join(", ");
          }
          break;

        case "perfil_tarefa_id":
          if (antigo) {
            const perfisAntigos = antigo
              .split(",")
              .map((id: any) =>
                getNome(id, opcoes.perfis, "id_perfil", "nome_perfil"),
              );
            valorAntigo = perfisAntigos.join(", ");
          }

          if (novo) {
            const novosIds = Array.isArray(novo) ? novo : novo.split(",");
            const perfisNovos = novosIds.map((id: any) =>
              getNome(id, opcoes.perfis, "id_perfil", "nome_perfil"),
            );
            valorNovo = perfisNovos.join(", ");
          }
          break;

        case "prazo_tarefa":
          valorAntigo = `${antigo} dias`;
          valorNovo = `${novo} dias`;
          break;
      }

      mudancas.push(
        `${nomeCampo} alterado de '${valorAntigo || "nenhum"}' para '${valorNovo || "nenhum"}'`,
      );
    }
    return mudancas;
  };

  const editTarefa = (data: any) => {
    data["etapa_automacao_id"] = idEtapa;
    data["id_automacao_tarefa"] = openModalEdicao.id_automacao_tarefa;

    if (data["usuario_tarefa_id"]?.length > 0) {
      data["usuario_tarefa_id"] = data["usuario_tarefa_id"].join(",");
    }
    if (data["perfil_tarefa_id"]?.length > 0) {
      data["perfil_tarefa_id"] = data["perfil_tarefa_id"].join(",");
    }

    const mudancas = formatarMudancas(openModalEdicao, data, {
      etapas,
      funis,
      tiposTarefas,
      usuarios,
      perfis,
      tarefasLoja: tarefasGeradas,
    });

    data["descricao_mudancas"] = mudancas.join("; ");
    return editarAutomacaoTarefa(data).then(() => {
      listarDadosKanban();
      if (
        tarefasGeradas?.find(
          (tarefa: any) =>
            tarefa.automacao_tarefa_gerada ===
            openModalEdicao?.id_automacao_tarefa,
        )
      ) {
        return Swal.fire({
          icon: "error",
          title: "Erro",
          text: "Não é possível editar automação pois já possui tarefas geradas, para editar finalize as tarefas geradas!",
        });
      }
      setOpenModalEdicao(false);
    });
  };

  return (
    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mt-6">
      {automacoesTarefa?.map((tarefa: any, index: number) => (
        <div
          key={index}
          className="rounded-2xl border border-gray/20 bg-white dark:bg-background/80 p-4 shadow-md dark:shadow-lg space-y-2 transition-colors"
        >
          <div className="text-sm font-medium text-gray-800 dark:text-white font-primary">
            <span className="font-semibold text-foreground">
              Código Tarefa:
            </span>{" "}
            {tarefa.tarefa_loja_id}
          </div>
          <div className="text-sm text-muted-foreground">
            <span className="font-semibold text-foreground">ID:</span>{" "}
            {tarefa.id_automacao_tarefa}
          </div>
          <div className="text-sm text-muted-foreground">
            <span className="font-semibold text-foreground">Tipo Tarefa:</span>{" "}
            {
              tiposTarefas.find(
                (tipo: any) => tipo.id_tipo_tarefa == tarefa.tipo_tarefa_id,
              )?.nome_tipo_tarefa
            }
          </div>
          <div className="text-sm text-muted-foreground">
            <span className="font-semibold text-foreground">Automação:</span>{" "}
            Gerar Tarefa
          </div>
          <div className="text-sm text-muted-foreground">
            <span className="font-semibold text-foreground">Entrega:</span>{" "}
            {tarefa.prazo_tarefa} dias
          </div>
          <div className="text-sm text-muted-foreground">
            <span className="font-semibold text-foreground">Funil:</span>{" "}
            {funis.find(
              (funil: any) => funil.id_funil == tarefa.funil_destino_id,
            )?.titulo_funil || "Nenhum"}
          </div>
          <div className="text-sm text-muted-foreground">
            <span className="font-semibold text-foreground">Etapa:</span>{" "}
            {etapas.find(
              (etapa: any) => etapa.id_etapa_funil == tarefa.etapa_destino_id,
            )?.titulo_etapa_funil || "Nenhuma"}
          </div>
          <div className="text-sm text-muted-foreground">
            <span className="font-semibold text-foreground">Responsável:</span>{" "}
            {tarefa.responsavel_tarefa_id == "perfilUsuario"
              ? perfis.filter((perfil: any) =>
                  tarefa.perfil_tarefa_id
                    ?.split(",")
                    .includes(String(perfil.id_perfil)),
                ).length > 0
                ? perfis
                    .filter((perfil: any) =>
                      tarefa.perfil_tarefa_id
                        ?.split(",")
                        .includes(String(perfil.id_perfil)),
                    )
                    .map((perfil: any) => perfil.nome_perfil)
                    .join(", ")
                : "Nenhum"
              : tarefa.responsavel_tarefa_id == "listaUsuario"
                ? usuarios.filter((usuario: any) =>
                    tarefa.usuario_tarefa_id
                      ?.split(",")
                      .includes(String(usuario.id_usuario)),
                  ).length > 0
                  ? usuarios
                      .filter((usuario: any) =>
                        tarefa.usuario_tarefa_id
                          ?.split(",")
                          .includes(String(usuario.id_usuario)),
                      )
                      .map((usuario: any) => usuario.nome_usuario)
                      .join(", ")
                  : "Nenhum"
                : tarefa.responsavel_tarefa_id == "pre_vendedor"
                  ? "Pré-Vendedor do Projeto"
                  : tarefa.responsavel_tarefa_id == "vendedor"
                    ? "Vendedor do Projeto"
                    : tarefa.responsavel_tarefa_id == "tecnico"
                      ? "Técnico do Projeto"
                      : tarefa.responsavel_tarefa_id == "gerente"
                        ? "Gerente do Projeto"
                        : tarefa.responsavel_tarefa_id == "instalador"
                          ? "Instalador do Projeto"
                          : ""}
          </div>
          <div className="flex justify-between pt-2">
            <button
              type="button"
              onClick={() => {
                Swal.fire({
                  title: "Atenção",
                  text: "Você tem certeza que deseja excluir essa automação?",
                  icon: "warning",
                  showCancelButton: true,
                  confirmButtonText: "Sim",
                  cancelButtonText: "Não",
                }).then((result) => {
                  if (result.isConfirmed) {
                    excluirAutomacaoTarefa(tarefa).then(() => {
                      listarDadosKanban();
                      listarAutomacoesTarefa(idEtapa).then((res) => {
                        setAutomacoesTarefa(res);
                      });
                    });
                  }
                });
              }}
              className="text-sm text-danger font-semibold hover:underline font-primary"
            >
              Excluir
            </button>
            <button
              type="button"
              onClick={() => {
                if (
                  tarefasGeradas?.find(
                    (tarefaGerada: any) =>
                      tarefaGerada.automacao_tarefa_gerada ==
                      tarefa?.id_automacao_tarefa,
                  )
                ) {
                  return Swal.fire({
                    icon: "error",
                    title: "Erro",
                    text: "Não é possível editar automação pois já possui tarefas geradas, para editar finalize as tarefas geradas!",
                  });
                }
                setOpenModalEdicao(tarefa);
              }}
              className="text-sm text-primary font-semibold hover:underline font-primary"
            >
              Editar
            </button>
          </div>
        </div>
      ))}

      <div
        onClick={() => setOpenModalCadastro(true)}
        className="flex items-center justify-center rounded-2xl border-2 border-dashed border-muted hover:border-primary transition cursor-pointer p-4 text-center bg-white dark:bg-background/80 shadow-sm dark:shadow-lg"
      >
        <span className="text-3xl font-bold text-muted-foreground dark:text-white">
          +
        </span>
      </div>

      <ModalComponente
        hasForm={false}
        header={
          <div className="w-full flex flex-row justify-center uppercase font-bold">
            Criação Automação Tarefa
          </div>
        }
        hasSaveButton={false}
        opened={openModalCadastro}
        onClose={() => setOpenModalCadastro(false)}
        className={"overflow-x-hidden"}
      >
        <FormTarefasGeradas
          defaultValues={null}
          etapas={etapas}
          onSubmitFunction={submitAutomacaoTarefa}
          selectedFunilDestiny={selectedFunilDestiny}
          usuarios={usuarios}
          perfis={perfis}
          tiposTarefas={tiposTarefas}
          setSelectedFunilDestiny={setSelectedFunilDestiny}
          funis={funis}
        />
      </ModalComponente>
      <ModalComponente
        hasForm={false}
        header={
          <div className="w-full flex flex-row justify-center uppercase font-bold">
            Editar Automação Tarefa
          </div>
        }
        hasSaveButton={false}
        opened={openModalEdicao}
        onClose={() => setOpenModalEdicao(false)}
        className={"overflow-x-hidden"}
      >
        <FormTarefasGeradas
          defaultValues={openModalEdicao}
          etapas={etapas}
          onSubmitFunction={editTarefa}
          selectedFunilDestiny={selectedFunilDestiny}
          usuarios={usuarios}
          perfis={perfis}
          tiposTarefas={tiposTarefas}
          setSelectedFunilDestiny={setSelectedFunilDestiny}
          funis={funis}
        />
      </ModalComponente>
    </div>
  );
};

export default CardTarefas;
