"use client";

import Input from "@/components/Forms/Input";
import InputSelectComponent from "@/components/Forms/InputSelect";
import { listarPerfis } from "@/requests/CRUD/Perfil/listarPerfis";
import { GetForm } from "@/utils";
import { useEffect, useState } from "react";
import { FaInfoCircle } from "react-icons/fa";
import Swal from "sweetalert2";

const FormCategoriasAnexos = ({
  onSubmitFunction,
  defaultValues,
  disabledFields,
  children,
  ...rest
}: any) => {
  const { handleSubmit, ...form } = GetForm();
  const [dadosPerfis, setDadosPerfis] = useState([]);
  const nomeCategoria: any =
    form.watch?.("identificacao_cfg_anexo" as never) || "";

  const normalizarNomeRelacionamento = (nome: string) =>
    String(nome || "")
      .normalize("NFD")
      .replace(/[\u0300-\u036f]/g, "")
      .trim()
      .replace(/[^a-zA-Z0-9]+/g, "_")
      .replace(/^_+|_+$/g, "")
      .toLowerCase();

  const nomeTagRelacionamento = `${normalizarNomeRelacionamento(nomeCategoria)}`;

  useEffect(() => {
    listarPerfis().then((res) => setDadosPerfis(res));
  }, []);

  const formSubmit = (data: any) => {
    const formatedData = {
      ...data,
      perfis_cfg_anexo: data.perfis_cfg_anexo.join(","),
    };

    onSubmitFunction(formatedData);
  };

  return (
    <>
      <form onSubmit={handleSubmit(formSubmit)} {...rest}>
        <div className="flex flex-row justify-center gap-2 items-center">
          <Input
            name="identificacao_cfg_anexo"
            label={
              <span className="flex items-center gap-2">
                Nome da Categoria
                <button
                  type="button"
                  className="text-primary hover:opacity-80"
                  onClick={() => {
                    Swal.fire({
                      icon: "info",
                      title: "Nome da Tag de Relacionamento",
                      html: `Esse nome também vira uma tag de relacionamento.<br/>Acentos são removidos, separadores viram <b>_</b> é adicionado.<br/><br/>Tag gerada: <b>${nomeTagRelacionamento}</b>`,
                      confirmButtonText: "Entendi",
                      confirmButtonColor: "#4CAF50",
                    });
                  }}
                  aria-label="Informações sobre a tag de relacionamento"
                >
                  <FaInfoCircle size={14} />
                </button>
              </span>
            }
            width={"xl:w-1/3"}
            formulario={form}
            defaultValue={defaultValues?.identificacao_cfg_anexo}
          />
          <InputSelectComponent
            name="perfis_cfg_anexo"
            label="Perfil"
            width={"xl:w-1/3"}
            isMulti
            required
            formulario={form}
            options={[
              {
                label: "Todos",
                value: "*",
              },
              ...dadosPerfis.map((perfil: any) => ({
                value: perfil.id_perfil,
                label: perfil.nome_perfil,
              })),
            ]}
            defaultValue={defaultValues?.perfis_cfg_anexo}
          />
        </div>
        {children}
      </form>
    </>
  );
};

export default FormCategoriasAnexos;
