"use client";

import { useEffect, useState } from "react";

import LoaderSun from "@/components/common/Loader/LoaderSun";
import Input from "@/components/Forms/Input";
import InputSelectComponent from "@/components/Forms/InputSelect";
import { listarLojas } from "@/requests/CRUD/Lojas/listarLojas";
import { GetForm } from "@/utils";
import "katex/dist/katex.min.css";

const FormFormaPagamento = ({
  onSubmitFunction,
  defaultValues,
  disabledFields,
  children,
  lojas: oldLojas,
  tiposForma,
  tipos_negocio,
  ...rest
}: {
  lojas: any[];
  tiposForma: any[];
  [x: string]: any;
}) => {
  const [lojas, setLojas] = useState(oldLojas);
  const [lojasSelecionadas, setLojasSelecionadas] = useState<any[]>(
    defaultValues ? defaultValues["cod_lojas_forma"]?.split(",") || [] : []
  );
  const [tipoDeFormaSelecionada, setTipoDeFormaSelecionada] = useState(
    defaultValues && defaultValues["tipo_forma"]
  );
  const [tiposNegociosLojas, setTiposNegociosLojas] = useState<any[]>(
    tipos_negocio?.filter((tipo: any) =>
      lojas
        ?.filter((loja) =>
          (defaultValues
            ? defaultValues["cod_lojas_forma"]?.split(",") || []
            : []
          )?.includes(loja?.id_loja)
        )
        ?.some((loja) =>
          loja?.tipos_negocios_loja?.split(",")?.includes(tipo?.id_tipo_negocio)
        )
    ) || []
  );

  const { handleSubmit, ...form } = GetForm();

  const [options, setOptions] = useState(
    (defaultValues && defaultValues["prazos_forma"]?.split(","))?.map(
      (option: any) => ({
        label: option == "0" ? "A vista" : option,
        value: option,
      })
    ) || []
  );

  useEffect(() => {
    setTiposNegociosLojas([]);
    listarLojas().then((newLojas) => {
      setLojas(newLojas);
      const dadosLojasSelecionadas = newLojas?.filter((loja: any) =>
        lojasSelecionadas?.includes(loja?.id_loja)
      );
      const newTiposNegociosLojas = tipos_negocio?.filter((tipo: any) =>
        dadosLojasSelecionadas?.some((loja: any) =>
          loja?.tipos_negocios_loja?.split(",")?.includes(tipo?.id_tipo_negocio)
        )
      );

      setTiposNegociosLojas(newTiposNegociosLojas);

      const form_cod_tipos_negocios = form.getValues("cod_tipos_negocios");
      if (form_cod_tipos_negocios) {
        if (
          form_cod_tipos_negocios?.[0]?.value == "*" &&
          newTiposNegociosLojas?.length == tipos_negocio?.length
        ) {
        } else if (form_cod_tipos_negocios?.[0]?.value == "*") {
          form.setValue(
            "cod_tipos_negocios",
            newTiposNegociosLojas?.map((tipo: any) => ({
              ...tipo,
              label: tipo?.nome_tipo_negocio,
              value: tipo?.id_tipo_negocio,
            }))
          );
        } else {
          form.setValue(
            "cod_tipos_negocios",
            form_cod_tipos_negocios?.filter((t: any) =>
              newTiposNegociosLojas?.some(
                (tipo: any) => tipo?.id_tipo_negocio == t?.value
              )
            )
          );
        }
      }
    });
  }, [lojasSelecionadas, oldLojas]);

  useEffect(() => {
    // Gerar opções de 30 em 30 dias até 360 (12 meses)
    const bancOptions = [];
    for (let i = 30; i <= 360; i += 30) {
      bancOptions.push({
        label: `${i}`,
        value: i.toString(),
      });
    }

    // Se já existem defaultValues, manter; senão usar as opções geradas
    if (!defaultValues || !defaultValues["prazos_forma"]) {
      setOptions(bancOptions);
    }
  }, [lojasSelecionadas, lojas]);

  useEffect(() => {
    if (defaultValues && defaultValues["prazos_forma"]) {
      form.setValue("prazos_forma", options);
    }
  }, []);

  function onSubmitFormFormaPagamento(data: any) {
    return onSubmitFunction(data);
  }

  return (
    <>
      {true ? (
        <form
          onSubmit={handleSubmit(onSubmitFormFormaPagamento)}
          key={form.key}
          {...rest}
          className="flex flex-row flex-wrap gap-3"
        >
          <Input
            name="nome_forma"
            label="Nome"
            formulario={form}
            required
            error="Informe o Nome"
            defaultValue={defaultValues && defaultValues["nome_forma"]}
            width="flex-1"
          />
          <InputSelectComponent
            name="exige_instituicao_forma"
            label="Exige Instituição Financeira"
            formulario={form}
            options={[
              { label: "Não", value: "0" },
              { label: "Sim", value: "1" },
            ]}
            defaultValue={
              defaultValues && defaultValues["exige_instituicao_forma"]
            }
            width="flex-1"
          />
          {children}
        </form>
      ) : (
        <div className="flex justify-center w-full">
          <LoaderSun />
        </div>
      )}
    </>
  );
};

export default FormFormaPagamento;
