import InputSelectComponent from "@/components/Forms/InputSelect-test";
import {
  Table,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useCapaCard } from "@/src/contexts/CardContext";
import { useEffect, useMemo } from "react";
import { useFieldArray, useWatch } from "react-hook-form";
import CardTarefas from "./cardTarefa";

const ConfiguracoesAutomacoesEtapa = ({
  form,
  defaultValues,
  dadosFunil,
  selectedAction,
  setSelectedAction,
  funis,
  selectedFunilDestiny,
  setSelectedFunilDestiny,
  etapas,
  atualizarListaFunisParalelos,
}: any) => {
  const { tiposNegocios } = useCapaCard();
  const { control, setValue, getValues, watch } = form;

  useEffect(() => {
    if (defaultValues?.id_funil && defaultValues?.id_etapa_funil) {
      atualizarListaFunisParalelos();
    }
  }, [defaultValues?.id_funil, defaultValues?.id_etapa_funil]);

  const tiposPermitidosIds = useMemo(() => {
    const raw = String(dadosFunil?.tipo_negocio_funil ?? "*");
    const arr = raw
      .split(",")
      .map((s) => s.trim())
      .filter(Boolean);
    return arr.length ? arr : ["*"];
  }, [dadosFunil?.tipo_negocio_funil]);

  const tiposAtivosIntegrador = useMemo(() => {
    if (!tiposNegocios) return [];
    if (tiposPermitidosIds.includes("*")) return tiposNegocios;
    return tiposNegocios.filter((t: any) =>
      tiposPermitidosIds.includes(String(t.id_tipo_negocio)),
    );
  }, [tiposNegocios, tiposPermitidosIds]);

  const {
    fields: automacoes,
    append,
    remove,
  } = useFieldArray({
    control: form.control,
    name: "automacoes",
  });
  useEffect(() => {
    if (tiposAtivosIntegrador.length === 1) {
      form.setValue(
        "automacoes.0.tipo_negocio_funil_paralelo",
        tiposAtivosIntegrador[0].id_tipo_negocio,
      );
    }
  }, [tiposAtivosIntegrador, form]);

  useEffect(() => {
    if (tiposAtivosIntegrador.length === 1) {
      if (automacoes.length > 0) {
        const automacoesD = automacoes[0] as any;
        setSelectedAction(automacoesD?.acao_funil_paralelo);
      }
    }
  }, [tiposAtivosIntegrador, automacoes]);
  const getVal = (v: any) => (v && typeof v === "object" ? v.value : v);

  const automacoesWatch =
    useWatch({ control: form.control, name: "automacoes" }) || [];

  // Sincroniza selectedAction do modo single com o valor do form
  const acaoSingleWatch = useWatch({
    control: form.control,
    name: "acao_funil_paralelo",
  });
  useEffect(() => {
    const v = getVal(acaoSingleWatch) ?? "nenhuma";
    setSelectedAction(v);
  }, [acaoSingleWatch, setSelectedAction]);

  const tiposSelecionados = (automacoesWatch || [])
    .map((a: any) => String(getVal(a?.tipo_negocio_funil_paralelo) ?? ""))
    .filter(Boolean);

  // Opções de tipo por linha (não permitir duplicado, exceto manter o do próprio)
  const getOpcoesTipoPorLinha = (idx: number) => {
    const valorAtual = String(
      getVal(automacoesWatch?.[idx]?.tipo_negocio_funil_paralelo) ?? "",
    );
    return tiposAtivosIntegrador
      .filter(
        (t: any) =>
          !tiposSelecionados.includes(String(t.id_tipo_negocio)) ||
          String(t.id_tipo_negocio) === valorAtual,
      )
      .map((t: any) => ({
        label: t.nome_tipo_negocio,
        value: t.id_tipo_negocio,
      }));
  };

  // Botão "Adicionar automação" só se ainda houver tipos disponíveis
  const podeAdicionarAutomacao =
    tiposAtivosIntegrador.length > 1 &&
    tiposAtivosIntegrador.some(
      (t: any) => !tiposSelecionados.includes(String(t.id_tipo_negocio)),
    );

  // Funções de filtro/validacao por linha
  const getAcaoLinha = (idx: number) =>
    getVal(automacoesWatch?.[idx]?.acao_funil_paralelo) ?? "nenhuma";

  const getFunilDestinoLinha = (idx: number) =>
    String(getVal(automacoesWatch?.[idx]?.funil_destino) ?? "");

  // Regra: se ação = duplicar, não permitir mesmo funil de origem (limpa se necessário)
  useEffect(() => {
    (automacoesWatch || []).forEach((a: any, idx: number) => {
      const acao = getAcaoLinha(idx);
      const funilSel = getVal(a?.funil_destino);
      if (
        acao === "duplicar" &&
        String(funilSel) === String(dadosFunil?.id_funil)
      ) {
        form.setValue(`automacoes.${idx}.funil_destino`, undefined);
        form.setValue(
          `automacoes.${idx}.etapa_destino_funil_paralelo`,
          undefined,
        );
      }
    });
  }, [automacoesWatch, dadosFunil?.id_funil, form]);

  const opcoesFunisPorLinha = (idx: number) => {
    const acao = getAcaoLinha(idx);
    return [
      { value: undefined, label: "Nenhuma" },
      ...funis
        .filter((funil: any) => {
          // const hasAnyValue = funil.tipo_negocio_funil
          //   .split(",")
          //   .some((tipo: any) => {
          //     if (dadosFunil.tipo_negocio_funil === "*") return true;
          //     return (
          //       dadosFunil.tipo_negocio_funil.split(",").includes(tipo) ||
          //       tipo === "*"
          //     );
          //   });
          const hasAnyValue = true;
          const baseValid =
            Number(funil.status_funil) === 1 &&
            funil.id_funil != 0 &&
            hasAnyValue;

          return acao === "duplicar"
            ? baseValid && funil.id_funil !== dadosFunil.id_funil
            : baseValid;
        })
        .map((funil: any) => ({
          value: String(funil.id_funil),
          label: funil.titulo_funil,
        }))
        .sort((a: any, b: any) => a.label.localeCompare(b.label)),
    ];
  };

  const opcoesEtapasPorLinha = (idx: number) => {
    const funilId = getFunilDestinoLinha(idx);
    return [
      { value: undefined, label: "Nenhuma" },
      ...etapas
        .filter(
          (etapa: any) =>
            String(etapa.grupo_etapa_funil) === String(funilId) &&
            etapa.status_etapa_funil == 1,
        )
        .map((etapa: any) => ({
          value: String(etapa.id_etapa_funil),
          label: etapa.titulo_etapa_funil,
        })),
    ];
  };

  return (
    <div>
      <div className="flex flex-col justify-center items-center w-full">
        <Tabs defaultValue="geral" className="w-full">
          <TabsList>
            <TabsTrigger value="geral">Geral</TabsTrigger>
            <TabsTrigger value="tarefa">Tarefa</TabsTrigger>
          </TabsList>

          <TabsContent value="geral" className="w-full">
            <Table className="min-w-full bg-white dark:bg-[#1d2a39] border border-gray-300 shadow-sm">
              <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-4 border-b text-center">
                    Ação
                  </TableHead>
                  <TableHead className="font-bold py-2 px-4 border-b text-center">
                    Tipo de Negócio
                  </TableHead>
                  <TableHead className=" font-bold py-2 px-4 border-b text-center">
                    Para o Fluxo
                  </TableHead>
                  <TableHead className=" font-bold py-2 px-4 border-b text-center">
                    Para a Etapa
                  </TableHead>
                  {tiposAtivosIntegrador.length > 1 && (
                    <TableHead className=" font-bold py-2 px-4 border-b text-center">
                      Ações
                    </TableHead>
                  )}
                </TableRow>
              </TableHeader>

              <tbody>
                {tiposAtivosIntegrador.length <= 1 ? (
                  <TableRow className="py-2 text-center">
                    <TableCell className="py-2 text-center">
                      <InputSelectComponent
                        name="automacoes.0.acao_funil_paralelo"
                        formulario={form}
                        options={[
                          { value: "nenhuma", label: "NENHUMA" },
                          { value: "duplicar", label: "DUPLICAR" },
                          { value: "mover", label: "MOVER" },
                        ]}
                        onChange={(e: any) => {
                          const v = e?.value ?? e;
                          if (v === "nenhuma") {
                            form.setValue(
                              "funil_destino" as never,
                              undefined as never,
                            );
                            form.setValue(
                              "etapa_destino_funil_paralelo" as never,
                              undefined as never,
                            );
                          }
                          setSelectedAction(v);
                        }}
                      />
                    </TableCell>

                    {/* <TableCell className="py-2 text-center">
              <div className="mx-auto flex flex-row gap-2">
                Selecione as opções desejadas
              </div>
            </TableCell> */}
                    {selectedAction != "nenhuma" && (
                      <>
                        <TableCell>
                          <InputSelectComponent
                            name="automacoes.0.tipo_negocio_funil_paralelo"
                            formulario={form}
                            options={tiposAtivosIntegrador.map((t) => ({
                              label: t.nome_tipo_negocio,
                              value: t.id_tipo_negocio,
                            }))}
                            disabled={tiposAtivosIntegrador.length === 1}
                          />
                        </TableCell>
                        <TableCell className="py-2 text-center">
                          <InputSelectComponent
                            name="automacoes.0.funil_destino"
                            // label="Fluxo"
                            textSize="10px"
                            formulario={form}
                            options={[
                              { value: undefined, label: "Nenhuma" },
                              ...funis
                                .filter((funil: any) => {
                                  const acao =
                                    getVal(acaoSingleWatch) ?? "nenhuma";
                                  let hasAnyValue = true;
                                  // if (dadosFunil.tipo_negocio_funil == "*") {
                                  //   hasAnyValue = true;
                                  // } else {
                                  //   hasAnyValue =
                                  //     funil.tipo_negocio_funil === "*"
                                  //       ? true
                                  //       : funil.tipo_negocio_funil
                                  //           .split(",")
                                  //           .some((tipo: any) =>
                                  //             dadosFunil.tipo_negocio_funil
                                  //               .split(",")
                                  //               .includes(tipo),
                                  //           );
                                  // }

                                  const baseValid =
                                    Number(funil.status_funil) === 1 &&
                                    funil.id_funil != 0 &&
                                    hasAnyValue;

                                  return acao === "duplicar"
                                    ? baseValid &&
                                        funil.id_funil !== dadosFunil.id_funil
                                    : baseValid;
                                })
                                .map((funil: any) => ({
                                  value: String(funil.id_funil),
                                  label: funil.titulo_funil,
                                }))
                                .sort((a: any, b: any) =>
                                  a.label.localeCompare(b.label),
                                ),
                            ]}
                            onChange={(e: any) => {
                              setSelectedFunilDestiny(String(e?.value ?? ""));
                              form.setValue(
                                "automacoes.0.etapa_destino_funil_paralelo" as never,
                                undefined as never,
                              );
                            }}
                          />
                        </TableCell>

                        <TableCell className="py-2 text-center">
                          <InputSelectComponent
                            name="automacoes.0.etapa_destino_funil_paralelo"
                            formulario={form}
                            options={[
                              { value: undefined, label: "Nenhuma" },
                              ...etapas
                                .filter(
                                  (etapa: any) =>
                                    String(etapa.grupo_etapa_funil) ===
                                      String(selectedFunilDestiny) &&
                                    etapa.status_etapa_funil == 1,
                                )
                                .map((etapa: any) => ({
                                  value: String(etapa.id_etapa_funil),
                                  label: etapa.titulo_etapa_funil,
                                })),
                            ]}
                          />
                        </TableCell>
                      </>
                    )}
                  </TableRow>
                ) : (
                  <>
                    {automacoes.map((field: any, idx: number) => {
                      const optsAcao = [
                        { value: "nenhuma", label: "NENHUMA" },
                        { value: "duplicar", label: "DUPLICAR" },
                        { value: "mover", label: "MOVER" },
                      ];
                      const optsTipo = getOpcoesTipoPorLinha(idx);
                      const optsFunil = opcoesFunisPorLinha(idx);
                      const optsEtapa = opcoesEtapasPorLinha(idx);

                      return (
                        <TableRow key={field.id} className="py-2 text-center">
                          <TableCell className="py-2 text-center">
                            <InputSelectComponent
                              name={`automacoes.${idx}.acao_funil_paralelo`}
                              formulario={form}
                              options={optsAcao}
                              // defaultValue={automacoes.${idx}.acao_funil_paralelo}
                              onChange={(e: any) => {
                                const v = e?.value ?? e;
                                if (v === "nenhuma") {
                                  form.setValue(
                                    `automacoes.${idx}.funil_destino`,
                                    undefined,
                                  );
                                  form.setValue(
                                    `automacoes.${idx}.etapa_destino_funil_paralelo`,
                                    undefined,
                                  );
                                }
                              }}
                            />
                          </TableCell>

                          {getAcaoLinha(idx) !== "nenhuma" && (
                            <>
                              <TableCell>
                                <InputSelectComponent
                                  name={`automacoes.${idx}.tipo_negocio_funil_paralelo`}
                                  formulario={form}
                                  options={optsTipo}
                                />
                              </TableCell>

                              <TableCell className="py-2 text-center">
                                <InputSelectComponent
                                  name={`automacoes.${idx}.funil_destino`}
                                  formulario={form}
                                  options={optsFunil}
                                  onChange={() => {
                                    form.setValue(
                                      `automacoes.${idx}.etapa_destino_funil_paralelo`,
                                      undefined,
                                    );
                                  }}
                                />
                              </TableCell>

                              <TableCell className="py-2 text-center">
                                <InputSelectComponent
                                  name={`automacoes.${idx}.etapa_destino_funil_paralelo`}
                                  formulario={form}
                                  options={optsEtapa}
                                />
                              </TableCell>

                              <TableCell className="py-2 text-center">
                                <button
                                  type="button"
                                  className="text-red-600 hover:underline"
                                  onClick={() => remove(idx)}
                                >
                                  Remover
                                </button>
                              </TableCell>
                            </>
                          )}
                        </TableRow>
                      );
                    })}

                    <TableRow>
                      <TableCell colSpan={5} className="py-3 text-center">
                        <button
                          type="button"
                          className="px-3 py-2 rounded bg-blue-600 text-white disabled:opacity-50"
                          disabled={!podeAdicionarAutomacao}
                          onClick={() => {
                            const proximoTipo = tiposAtivosIntegrador.find(
                              (t: any) =>
                                !tiposSelecionados.includes(
                                  String(t.id_tipo_negocio),
                                ),
                            );
                            append({
                              acao_funil_paralelo: "nenhuma",
                              tipo_negocio_funil_paralelo: proximoTipo
                                ? proximoTipo.id_tipo_negocio
                                : undefined,
                              funil_destino: undefined,
                              etapa_destino_funil_paralelo: undefined,
                            });
                          }}
                        >
                          Adicionar automação
                        </button>
                      </TableCell>
                    </TableRow>
                  </>
                )}
              </tbody>
            </Table>
          </TabsContent>

          <TabsContent value="tarefa" className="w-full space-y-6">
            <CardTarefas
              etapas={etapas}
              selectedFunilDestiny={selectedFunilDestiny}
              setSelectedFunilDestiny={setSelectedFunilDestiny}
              idEtapa={defaultValues?.id}
              funis={funis}
            />
          </TabsContent>
        </Tabs>
      </div>
    </div>
  );
};

export default ConfiguracoesAutomacoesEtapa;
