import { handleSweetAlert } from "@/components/Modal/SweetAlertConfirm";
import { useColorContext } from "@/src/contexts/ColorContext";
import { useScreenContext } from "@/src/contexts/ScreenContext";
import { IInputSelectProps } from "@/types/formInterfaces";
import { GroupedOption } from "@/types/interface";
import { compararArraysDeObjetosPorLabel } from "@/utils";
import { motion } from "framer-motion";
import { Info } from "lucide-react";
import React, { useEffect, useMemo, useState } from "react";
import { createPortal } from "react-dom";
import { Controller } from "react-hook-form";
import Select, { GroupBase, OptionsOrGroups } from "react-select";
import makeAnimated from "react-select/animated";
import CreatableSelect from "react-select/creatable";
import { twMerge } from "tailwind-merge";
import * as yup from "yup";
import { Skeleton } from "../ui/skeleton";

const buildSelectStyles = (colorMode: string, isMulti = false) => {
  const isDark = colorMode === "dark";
  const disabledBg = isDark ? "#243447" : "#f1f5f9";
  const disabledBorder = isDark ? "#334155" : "#e2e8f0";
  const disabledText = isDark ? "#94a3b8" : "#94a3b8";
  const enabledBg = isDark ? "#1d2a39" : "#ffffff";
  const enabledBorder = isDark ? "#334155" : "#e2e8f0";
  const enabledText = isDark ? "#e2e8f0" : "#1e293b";

  return {
    container: (base: any) => ({
      ...base,
      width: "100%",
      maxWidth: "100%",
    }),
    control: (base: any, state: any) => ({
      ...base,
      display: "flex",
      flexDirection: "row",
      minHeight: isMulti ? 38 : 40,
      height: isMulti ? "auto" : base.height,
      borderRadius: 8,
      borderColor: state.isDisabled
        ? disabledBorder
        : state.isFocused
          ? "#3C50E0"
          : enabledBorder,
      backgroundColor: state.isDisabled ? disabledBg : enabledBg,
      boxShadow:
        state.isDisabled || !state.isFocused ? "none" : "0 0 0 1px #3C50E0",
      opacity: state.isDisabled ? 0.85 : 1,
      flexWrap: "nowrap",
      alignItems: "center",
      cursor: state.isDisabled ? "not-allowed" : "pointer",
      width: "100%",
      maxWidth: "100%",
      transition:
        "border-color 200ms, box-shadow 200ms, background-color 200ms",
      pointerEvents: state.isDisabled ? "auto" : base.pointerEvents,
      "&:hover": state.isDisabled
        ? {
            borderColor: disabledBorder,
            backgroundColor: disabledBg,
          }
        : {
            borderColor: state.isFocused
              ? "#3C50E0"
              : isDark
                ? "#475569"
                : "#cbd5e1",
          },
    }),
    valueContainer: (base: any, state: any) => ({
      ...base,
      padding: isMulti ? "2px 6px" : "2px 8px",
      flex: "1 1 0",
      minWidth: 0,
      maxWidth: "100%",
      flexWrap: isMulti ? "wrap" : "nowrap",
      alignItems: isMulti ? "flex-start" : "center",
      alignContent: isMulti ? "flex-start" : "center",
      gap: 4,
      overflow: "hidden",
      opacity: state.isDisabled ? 0.9 : 1,
    }),
    indicatorsContainer: (base: any, state: any) => ({
      ...base,
      flexShrink: 0,
      flexGrow: 0,
      alignItems: "center",
      alignSelf: "center",
      display: "flex",
      opacity: state.isDisabled ? 0.5 : 1,
    }),
    dropdownIndicator: (base: any, state: any) => ({
      ...base,
      padding: "0 8px",
      color: state.isDisabled ? disabledText : "#94a3b8",
    }),
    clearIndicator: (base: any, state: any) => ({
      ...base,
      padding: "0 4px",
      color: state.isDisabled ? disabledText : "#94a3b8",
      cursor: state.isDisabled ? "not-allowed" : "pointer",
    }),
    placeholder: (base: any, state: any) => ({
      ...base,
      color: state.isDisabled ? disabledText : isDark ? "#64748b" : "#94a3b8",
      whiteSpace: "nowrap",
      overflow: "hidden",
      textOverflow: "ellipsis",
      margin: 0,
    }),
    singleValue: (base: any, state: any) => ({
      ...base,
      color: state.isDisabled ? disabledText : enabledText,
      margin: 0,
    }),
    input: (base: any, state: any) => ({
      ...base,
      margin: 0,
      padding: 0,
      minWidth: isMulti ? "2px" : "2px",
      width: isMulti ? "2px" : "100%",
      maxWidth: isMulti ? "100%" : "100%",
      flex: isMulti ? "0 1 auto" : undefined,
      alignSelf: "center",
      color: state.isDisabled ? disabledText : enabledText,
      cursor: state.isDisabled ? "not-allowed" : "text",
    }),
    menu: (base: any) => ({
      ...base,
      borderRadius: 8,
      overflow: "hidden",
      boxShadow:
        "0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",
      zIndex: 9999,
    }),
    menuList: (base: any) => ({
      ...base,
      padding: 4,
    }),
    option: (provided: any, state: any) => ({
      ...provided,
      backgroundColor: state.isFocused
        ? isDark
          ? "#243447"
          : "#e6f0ff"
        : state.isSelected
          ? isDark
            ? "#1d2a39"
            : "#dbeafe"
          : isDark
            ? "#1d2a39"
            : "#fff",
      color: isDark ? "#fff" : "inherit",
      padding: "8px 12px",
      borderRadius: 6,
      cursor: "pointer",
    }),
    menuPortal: (base: any) => ({
      ...base,
      zIndex: 9999999999,
      backgroundColor: isDark ? "#1d2a39" : "#fff",
      fontSize: "13px",
    }),
    multiValue: (base: any, state: any) => ({
      ...base,
      margin: 0,
      borderRadius: 6,
      maxWidth: "100%",
      backgroundColor: state.isDisabled
        ? isDark
          ? "#334155"
          : "#e2e8f0"
        : isDark
          ? "#334155"
          : "#eff6ff",
      opacity: state.isDisabled ? 0.8 : 1,
    }),
    multiValueLabel: (base: any, state: any) => ({
      ...base,
      color: state.isDisabled ? disabledText : isDark ? "#e2e8f0" : "#1e40af",
      fontSize: 12,
      padding: "2px 6px",
      whiteSpace: "normal",
      wordBreak: "break-word",
      lineHeight: 1.35,
    }),
    multiValueRemove: (base: any, state: any) => ({
      ...base,
      color: state.isDisabled ? disabledText : isDark ? "#94a3b8" : "#3b82f6",
      borderRadius: "0 6px 6px 0",
      cursor: state.isDisabled ? "not-allowed" : "pointer",
      ":hover": state.isDisabled
        ? {}
        : {
            backgroundColor: isDark ? "#475569" : "#dbeafe",
            color: isDark ? "#f1f5f9" : "#1d4ed8",
          },
    }),
  };
};

// Componente customizado para exibir tags de valores selecionados
const CustomMultiValue = ({ data, removeProps }: any) => {
  return (
    <div className="inline-flex max-w-full items-start gap-1 rounded bg-blue-100 px-2 py-1 text-xs font-medium text-blue-800 dark:bg-blue-900 dark:text-blue-100">
      <span className="min-w-0 break-words leading-snug">{data.label}</span>
      <button
        type="button"
        className="shrink-0 leading-none text-blue-600 hover:text-blue-900 dark:text-blue-300 dark:hover:text-blue-200"
        onClick={(e) => {
          e.preventDefault();
          e.stopPropagation();
          removeProps?.onClick?.();
        }}
        onMouseDown={(e) => e.preventDefault()}
      >
        ×
      </button>
    </div>
  );
};

// Componente para limitar exibição a 2 itens
const CustomValueContainer = ({ children, ...props }: any) => {
  const [showHidden, setShowHidden] = React.useState(false);
  const [coords, setCoords] = React.useState({ top: 0, left: 0, width: 0 });
  const containerRef = React.useRef<HTMLDivElement>(null);
  const portalRef = React.useRef<HTMLDivElement>(null);

  // Função para calcular a posição atualizada
  const updateCoords = React.useCallback(() => {
    if (containerRef.current) {
      const rect = containerRef.current.getBoundingClientRect();

      // Se tivermos a ref do portal, podemos subtrair a altura exata dele
      // Caso contrário, usamos um valor estimado ou fixo para o cálculo inicial
      const portalHeight = portalRef.current?.offsetHeight || 150;
      const margin = 8;

      const hasSpaceOnTop = rect.top > portalHeight + margin;

      // setCoords({
      //   // top: rect.bottom + window.scrollY + 5, // 5px de espaçamento
      //   // Topo do input - altura do portal - margem de 8px
      //   top: rect.top + window.scrollY - portalHeight - 8,
      //   left: rect.left + window.scrollX,
      //   width: rect.width,
      // });
      if (hasSpaceOnTop) {
        // Posiciona em CIMA
        setCoords({
          top: rect.top + window.scrollY - portalHeight - margin,
          left: rect.left + window.scrollX,
          width: rect.width,
          // position: 'top'
        });
      } else {
        // Posiciona em BAIXO (caso não tenha espaço em cima)
        setCoords({
          top: rect.bottom + window.scrollY + margin,
          left: rect.left + window.scrollX,
          width: rect.width,
          // position: 'bottom'
        });
      }
    }
  }, []);

  // Efeito para monitorar eventos globais quando o popover abrir
  React.useEffect(() => {
    if (showHidden) {
      // Atualiza a posição imediatamente ao abrir
      updateCoords();

      // Listeners para atualizar em tempo real
      window.addEventListener("scroll", updateCoords, true); // 'true' captura scroll em containers internos também
      window.addEventListener("resize", updateCoords);

      return () => {
        window.removeEventListener("scroll", updateCoords, true);
        window.removeEventListener("resize", updateCoords);
      };
    }
  }, [showHidden, updateCoords]);

  // Detectar cliques fora do container
  React.useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (
        containerRef.current &&
        !containerRef.current.contains(event.target as Node) &&
        !(event.target as HTMLElement).closest(".portal-overflow-menu") // Evita fechar ao clicar dentro do portal
      ) {
        setShowHidden(false);
      }
    }

    if (showHidden) {
      document.addEventListener("mousedown", handleClickOutside);
      return () =>
        document.removeEventListener("mousedown", handleClickOutside);
    }
  }, [showHidden]);

  // const handleToggle = (e: React.MouseEvent) => {
  //   e.preventDefault();
  //   e.stopPropagation();

  //   if (!showHidden && containerRef.current) {
  //     const rect = containerRef.current.getBoundingClientRect();
  //     // Calculamos a posição para o portal aparecer logo abaixo ou acima do input
  //     setCoords({
  //       top: rect.bottom + window.scrollY,
  //       left: rect.left + window.scrollX,
  //       width: rect.width,
  //     });
  //   }
  //   setShowHidden(!showHidden);
  // };

  const childArray = React.Children.toArray(children);
  const multiValues = childArray.filter(
    (child: any) =>
      child?.type?.displayName === "MultiValue" ||
      (child?.props && "data" in child.props && "removeProps" in child.props),
  );

  const visibleValues = multiValues.slice(0, 2);
  const hiddenValues = multiValues.slice(2);
  const hiddenCount = hiddenValues.length;
  const inputAndPlaceholder = childArray.filter(
    (child: any) =>
      child?.type?.displayName !== "MultiValue" &&
      !(child?.props && "data" in child.props && "removeProps" in child.props),
  );

  return (
    <>
      <div
        ref={containerRef}
        {...props.innerProps}
        className="relative flex min-w-0 flex-1 flex-wrap content-start items-start gap-1 overflow-hidden px-2 py-1"
      >
        {visibleValues}
        {hiddenCount > 0 && (
          <button
            type="button"
            onClick={(e) => {
              e.preventDefault();
              e.stopPropagation();
              setShowHidden(!showHidden);
            }}
            className="inline-flex shrink-0 items-center gap-1 rounded bg-gray-200 px-2 py-1 text-xs font-medium whitespace-nowrap text-gray-800 transition hover:bg-gray-300 active:bg-gray-400 dark:bg-gray-700 dark:text-gray-200 dark:hover:bg-gray-600"
            onMouseDown={(e) => {
              e.stopPropagation();
            }}
          >
            +{hiddenCount}
          </button>
        )}
        {inputAndPlaceholder.length > 0 && (
          <div className="inline-flex w-auto min-w-[2px] max-w-full shrink-0 grow-0 items-center self-center">
            {inputAndPlaceholder}
          </div>
        )}

        {/* Tooltip com itens ocultos */}
        {hiddenCount > 0 &&
          showHidden &&
          createPortal(
            <div
              ref={portalRef} // Atribuímos a ref aqui
              // className="absolute bottom-full left-0 mb-2 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded shadow-2xl p-2 max-h-48 overflow-auto w-max"
              // style={{ zIndex: 99999999 }}
              className="portal-overflow-menu bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded shadow-2xl p-2 max-h-48 overflow-auto flex flex-col gap-1"
              style={{
                position: "absolute",
                zIndex: 999999,
                top: `${coords.top}px`,
                left: `${coords.left}px`,
                minWidth: "150px",
                width: `${coords.width}px`, // Opcional: faz o popover ter a mesma largura do select
              }}
            >
              {hiddenValues.map((value, index) => (
                <div
                  key={index}
                  // className="px-3 py-2 text-sm text-gray-800 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 rounded cursor-default"
                  className="px-2 py-1 text-sm text-gray-800 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 rounded cursor-pointer flex justify-between items-center group"
                  onClick={(e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    (value as any)?.props?.removeProps?.onClick?.();
                  }}
                  onMouseDown={(e) => e.preventDefault()}
                >
                  <span>{(value as any)?.props?.data?.label}</span>
                  <span className="text-[10px] text-red-500 font-bold opacity-0 group-hover:opacity-100 transition">
                    X
                  </span>
                  {/* {typeof value === "object" &&
                  value !== null &&
                  "props" in value
                    ? (value as any)?.props?.data?.label
                    : ""} */}
                </div>
              ))}
            </div>,
            document.body,
          )}
      </div>
    </>
  );
};

const InputSelectComponent = ({
  name,
  label,
  width,
  options: newOptions,
  formulario,
  creatable,
  onChange,
  isMulti = false,
  defaultValue,
  controlledValue,
  required,
  disabled,
  menuPlacement = "auto",
  skipEffect = false,
  minimumCharacter = false,
  captureInputChange,
  removeDocumentBody = false,
  error,
  placeholder,
  dynamic = false,
  textSize = "text-md",
  labelSize = "text-md",
  formatOptionLabel,
  schema,
  menuPositionFixed = false,
  validateCreateOption,
  isCategorizado,
  infoMessage,
}: IInputSelectProps) => {
  const SelectComponent = creatable ? CreatableSelect : Select;
  const [isLoading, setIsLoading] = useState(false);
  const [darkTheme, setDarkTheme] = useState(false);
  const { onDrawer } = useScreenContext();
  const [options, setOptions] = useState<
    | OptionsOrGroups<any, GroupBase<any>>
    | { value: string; label: string; isDisabled?: boolean }[]
  >([]);
  const animatedComponents = makeAnimated();
  // undefined (não null!) como sentinela de "ainda não inicializei" - null é
  // um defaultValue LEGÍTIMO (ex: opção "Automático" com value:null), e o
  // guard abaixo (linha ~643) só compara "!== defaultValue" - usar null aqui
  // colidia com esse caso real e fazia o formulario.setValue nunca rodar,
  // deixando o campo vazio em vez de mostrar a opção selecionada.
  const lastInitializedDefaultValue = React.useRef<any>(undefined);
  const lastFieldName = React.useRef<string | undefined>(undefined);

  const emptyOption = { value: "", label: "Escolha", isDisabled: true };

  useEffect(() => {
    // Não injeta "Escolha" quando o comportamento é mínimo de caracteres antes de listar
    if (!minimumCharacter && (!newOptions || newOptions.length === 0)) {
      // Quando não houver nenhuma opção, deixa a opção "Escolha" sem valor
      if (
        compararArraysDeObjetosPorLabel(
          [emptyOption] as any[],
          options as any[],
        ) ||
        options.length === 0
      ) {
        setOptions([emptyOption]);
      } else if (options.length === 0) {
        setOptions([emptyOption]);
      }
      return;
    }

    if (
      // newOptions.some(
      //   (option, index) =>
      //     option?.label != options[index]?.label ||
      //     option?.value != options[index]?.value
      // )
      (compararArraysDeObjetosPorLabel(
        (newOptions || []) as any[],
        (options || []) as any[],
      )
        ? true
        : newOptions?.[0]?.options
          ? compararArraysDeObjetosPorLabel(
              (newOptions ?? []).flatMap((curr: any) => curr.options ?? []),
              (options ?? []).flatMap((curr: any) => curr.options ?? []),
            )
          : false) ||
      (options?.length ?? 0) === 0
    ) {
      const hasOptions = newOptions && newOptions.length > 0;
      setOptions(
        hasOptions
          ? newOptions
          : [{ value: "", label: "Escolha", isDisabled: true }],
      );
    }
  }, [newOptions]);

  const { colorMode } = useColorContext();

  const handleEnterToNextField = (e: React.KeyboardEvent) => {
    if (e.key === "Enter") {
      e.preventDefault();
      const form = (e.target as HTMLElement).closest("form");
      if (!form) return;

      const elements = Array.from(form.elements) as HTMLElement[];
      const index = elements.indexOf(e.target as HTMLElement);
      for (let i = index + 2; i < elements.length; i++) {
        const next = elements[i];
        if (
          next &&
          typeof next.focus === "function" &&
          !next.hasAttribute("disabled") &&
          next.tabIndex !== -1
        ) {
          next.focus();
          break;
        }
      }
    }
  };

  useEffect(() => {
    if (formulario && name != undefined) {
      const newSchema = formulario.yupSchema.fields;
      if (isMulti) {
        newSchema[name] = required
          ? yup
              .array()
              .of(
                yup
                  .string()
                  .transform((e) => (e?.value ? String(e.value) : "")),
              )
              .min(1, "É necessário selecionar pelo menos um")
              .required(error)
          : yup
              .array()
              .of(
                yup
                  .string()
                  .transform((e) => (e?.value ? String(e.value) : "")),
              );
      } else {
        newSchema[name] = required
          ? yup
              .string()
              .transform((e) => (e?.value ? String(e?.value) : ""))
              .required(error)
          : yup.string().transform((e) => (e?.value ? String(e.value) : ""));
      }
      newSchema[name] = schema || newSchema[name];
      formulario.setYupSchema(yup.object().shape(newSchema));
      if (
        defaultValue !== undefined &&
        options[0] != undefined &&
        !Object.keys(formulario.control._formValues).includes(name)
      ) {
        formulario.setValue(
          name as never,
          formulario.control._formValues[name] as never,
        );
      }
    }

    return () => {
      dynamic &&
        formulario?.control.unregister([name] as never[], {
          keepValue: false,
          keepError: false,
        });
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // useEffect(() => {
  // }, [defaultValue]);

  // Helpers para tratar diferentes formatos de defaultValue evitando erros de split
  const getMultiSelected = (
    defaultVal: any,
    opts: { value: any; label: any }[],
  ) => {
    if (!defaultVal) return [];
    let values: string[] = [];
    if (typeof defaultVal === "string") {
      values = defaultVal
        .split(",")
        .map((v: string) => v.trim())
        .filter(Boolean);
    } else if (Array.isArray(defaultVal)) {
      values = defaultVal
        .map((v) =>
          v && typeof v === "object" && "value" in v
            ? String(v.value)
            : String(v),
        )
        .filter(Boolean);
    } else if (typeof defaultVal === "object" && defaultVal !== null) {
      if ("value" in defaultVal) values = [String((defaultVal as any).value)];
    } else {
      values = [String(defaultVal)];
    }
    return opts.filter((o) => values.includes(String(o.value)));
  };

  const getSingleSelected = (
    defaultVal: any,
    opts: { value: any; label: any }[],
  ) => {
    if (!defaultVal) return "";
    if (
      typeof defaultVal === "object" &&
      defaultVal !== null &&
      "value" in defaultVal &&
      "label" in defaultVal
    ) {
      return defaultVal; // já é o objeto option
    }
    return opts.find((o) => String(o.value) == String(defaultVal)) || "";
  };

  useEffect(() => {
    if (lastFieldName.current !== name) {
      lastInitializedDefaultValue.current = undefined;
      lastFieldName.current = name;
    }

    function updateDefaultValue() {
      if (skipEffect) {
        return;
      }
      // Após remontagem (ex: troca de abas), o form pode já ter um valor
      // selecionado pelo usuário — não sobrescrever com o defaultValue
      if (lastInitializedDefaultValue.current === null && name) {
        const currentFormValue = formulario?.control?._formValues?.[name];
        const isOptionShape = (v: any) =>
          v && typeof v === "object" && "value" in v && "label" in v;
        const hasSelectedValue = isMulti
          ? Array.isArray(currentFormValue) &&
            currentFormValue.some(isOptionShape)
          : isOptionShape(currentFormValue);
        if (hasSelectedValue) {
          lastInitializedDefaultValue.current = defaultValue;
          return;
        }
      }
      if (defaultValue !== undefined && options[0] != undefined) {
        if (lastInitializedDefaultValue.current !== defaultValue) {
          const resolvedValue = isMulti
            ? getMultiSelected(defaultValue, options as any)
            : getSingleSelected(defaultValue, options as any);

          formulario?.setValue(
            name as never,
            (resolvedValue as never) || ""
          );

          // Mark as initialized if we successfully found a valid option, or if the defaultValue itself is empty
          if (
            (resolvedValue && (!isMulti || (resolvedValue as any[]).length > 0)) ||
            defaultValue === "" ||
            defaultValue === null
          ) {
            lastInitializedDefaultValue.current = defaultValue;
          }
        }
      }
    }
    updateDefaultValue();
  }, [defaultValue, options, skipEffect, name, isMulti]);

  const selectStyles = useMemo(
    () => buildSelectStyles(colorMode ?? "light", isMulti),
    [colorMode, isMulti],
  );

  const formatGroupLabel = (data: GroupedOption) => (
    <div>
      <span>{data.label}</span>
      <span>{data.options.length}</span>
    </div>
  );

  const shouldShowDistribuidorCadastroInfo =
    name === "codDistribuidor_item" && !isMulti;
  const infoMessageToShow = shouldShowDistribuidorCadastroInfo
    ? "Atenção! Nesta lista mostra apenas Distribuidores Cadastrados, pois os Nativos não permitem edição e cadastros de itens por aqui, apenas pela integração do Distribuidor."
    : infoMessage;

  return (
    <div className={`${width ? width : "w-full"} relative`}>
      {label && (
        <label
          htmlFor={name}
          className={twMerge(
            `mb-[10px] labelInputDynamic text-black dark:text-white flex flex-row`,
            typeof label === "string" ? "whitespace-nowrap" : "whitespace-normal",
            labelSize
          )}
        >
          {typeof label == "string"
            ? label
                .split(" ")
                .map((str: string) =>
                  str.length > 3 ? str[0].toUpperCase() + str.slice(1) : str,
                )
                .join(" ")
            : label}{" "}
          {infoMessageToShow && (
            <button
              type="button"
              className="ml-1 text-primary"
              onClick={(e) => {
                e.preventDefault();
                e.stopPropagation();
                handleSweetAlert({
                  icon: "info",
                  title: "Atenção!",
                  showDenyButton: false,
                  confirmButtonText: "Ok",
                  html: infoMessageToShow,
                });
              }}
            >
              <Info size={26} />
            </button>
          )}
          <span className="text-[#ff2b2b] font-semibold ">
            {required && "*"}
          </span>
        </label>
      )}
      <div className="relative">
        {minimumCharacter ||
        (((options?.length > 0 && options[0] !== undefined) ||
          creatable == true) &&
          name !== undefined &&
          formulario !== undefined) ? (
          <Controller
            name={name as any}
            control={formulario?.control}
            defaultValue={
              defaultValue
                ? isMulti
                  ? getMultiSelected(defaultValue, options as any)
                  : getSingleSelected(defaultValue, options as any)
                : isMulti
                  ? []
                  : ""
            }
            render={({ field }: { field: any }) => (
              <>
                <SelectComponent
                  // formatGroupLabel={formatGroupLabel}
                  menuPosition={menuPositionFixed ? "fixed" : "absolute"}
                  isClearable
                  maxMenuHeight={300}
                  components={
                    isMulti
                      ? {
                          MultiValue: CustomMultiValue,
                          ValueContainer: CustomValueContainer,
                        }
                      : {}
                  }
                  isOptionDisabled={(opt: any) =>
                    opt?.value === "" || opt?.isDisabled
                  }
                  onCreateOption={(inputValue: string) => {
                    // Verifica se já existe uma opção com esse label ou value (case insensitive)
                    const existingOption = options.find(
                      (option) =>
                        option.label.toLowerCase() ==
                          inputValue.toLowerCase() ||
                        option.value?.toLowerCase?.() ===
                          inputValue.toLowerCase(),
                    );

                    // Se já existe, apenas seleciona ela
                    if (existingOption) {
                      if (isMulti) {
                        const newValue = [
                          ...(field.value || []),
                          existingOption,
                        ].filter(
                          (v, i, arr) =>
                            arr.findIndex((o: any) => o.value === v.value) ===
                            i,
                        );
                        field.onChange(newValue);
                        onChange && onChange(newValue as any);
                      } else {
                        field.onChange(existingOption);
                        onChange && onChange(existingOption);
                      }
                      return;
                    }

                    let newOption = { label: inputValue, value: inputValue };

                    if (validateCreateOption && creatable) {
                      const validated = validateCreateOption(
                        inputValue,
                        options as any,
                      );
                      if (!validated) return;
                      newOption = validated;
                    }

                    const updatedOptions = [...options, newOption];
                    setOptions(updatedOptions);

                    if (isMulti) {
                      defaultValue = [...(field.value || []), newOption];
                      field.onChange([...(field.value || []), newOption]);
                    } else {
                      defaultValue = newOption;
                      field.onChange(newOption);
                    }

                    if (onChange) {
                      if (isMulti) {
                        onChange([...(field.value || []), newOption] as any);
                      } else {
                        onChange(newOption as any);
                      }
                    }
                  }}
                  closeMenuOnSelect={isMulti ? false : true}
                  styles={selectStyles}
                  menuPortalTarget={
                    onDrawer ? null : removeDocumentBody ? null : document.body
                  }
                  {...field}
                  className={`${textSize} relative w-full text-black dark:text-white font-medium appearance-none rounded bg-transparent outline-none transition focus:border-primary active:border-primary dark:border-form-strokedark dark:focus:border-primary`}
                  options={options}
                  noOptionsMessage={({ inputValue }) =>
                    minimumCharacter
                      ? "Digite ao menos 3 letras"
                      : formulario?.errors && name && formulario.errors[name]
                        ? formulario.errors[name]?.message
                            ?.split(" ")
                            .map((str: string) => {
                              return str.length > 3
                                ? str[0].toUpperCase() + str.slice(1)
                                : str;
                            })
                            .join(" ")
                        : "Nenhum resultado"
                  }
                  placeholder={placeholder || "Selecione uma opção"}
                  isMulti={isMulti}
                  menuPlacement={menuPlacement}
                  isDisabled={disabled}
                  defaultValue={
                    defaultValue
                      ? isMulti
                        ? getMultiSelected(defaultValue, options as any)
                        : getSingleSelected(defaultValue, options as any)
                      : isMulti
                        ? []
                        : ""
                  }
                  onInputChange={(e) => {
                    if (minimumCharacter) {
                      captureInputChange(e);
                    }
                    return e;
                  }}
                  onChange={(selectedOption: any, actionMeta) => {
                    if (field.onChange) {
                      field.onChange(selectedOption || "", actionMeta);
                      if (isMulti) {
                        if (
                          selectedOption?.some(
                            (option: any) => option.value == "*",
                          )
                        ) {
                          if (
                            selectedOption[selectedOption.length - 1]?.value ==
                            "*"
                          ) {
                            selectedOption = (options as any).filter(
                              (option: any) => option.value == "*",
                            );
                            formulario!.setValue(
                              name as never,
                              selectedOption as never,
                            );
                          } else {
                            selectedOption = options.filter(
                              (option) =>
                                !selectedOption
                                  ?.map((o: any) => o.value)
                                  .includes(option.value),
                            );
                            formulario!.setValue(
                              name as never,
                              selectedOption as never,
                            );
                          }
                        }
                      }
                    }
                    if (onChange) {
                      onChange(selectedOption || "");
                    }
                  }}
                  formatOptionLabel={formatOptionLabel}
                />
              </>
            )}
          />
        ) : options?.length > 0 &&
          options[0] != undefined &&
          !minimumCharacter ? (
          <Select
            closeMenuOnSelect={isMulti ? false : true}
            maxMenuHeight={300}
            components={
              isMulti
                ? {
                    MultiValue: CustomMultiValue,
                    ValueContainer: CustomValueContainer,
                  }
                : {}
            }
            styles={selectStyles}
            menuPortalTarget={
              onDrawer ? null : removeDocumentBody ? null : document.body
            }
            className={twMerge(
              `relative w-full text-black dark:text-white font-medium appearance-none rounded bg-transparent outline-none transition focus:border-primary active:border-primary dark:border-form-strokedark dark:focus:border-primary`,
              textSize,
            )}
            placeholder={placeholder || "Selecione uma opção"}
            isMulti={isMulti}
            isDisabled={disabled}
            {...(controlledValue !== undefined
              ? {
                  value: isMulti
                    ? getMultiSelected(controlledValue, options as any)
                    : getSingleSelected(controlledValue, options as any),
                }
              : {
                  defaultValue: defaultValue
                    ? isMulti
                      ? getMultiSelected(defaultValue, options as any)
                      : getSingleSelected(defaultValue, options as any)
                    : isMulti
                      ? []
                      : "",
                })}
            options={options}
            onChange={(selectedOption: any, actionMeta) => {
              if (isMulti) {
                if (selectedOption.some((option: any) => option.value == "*")) {
                  formulario?.setValue(
                    name as never,
                    (options as any).filter(
                      (option: any) => option.value == "*",
                    ) as never,
                  );
                  selectedOption = (options as any).filter(
                    (option: any) => option.value == "*",
                  );
                }
              }
              if (onChange) {
                onChange(selectedOption || "");
              }
            }}
            menuPlacement={menuPlacement}
            formatOptionLabel={formatOptionLabel}
          />
        ) : (
          <Skeleton className="relative w-full h-[37px] css-t3ipsp-control" />
        )}
      </div>
      {formulario?.errors && name && formulario.errors[name] && (
        <motion.span
          className="text-danger text-sm"
          initial={{ opacity: 0, y: -5 }}
          animate={{ opacity: 1, y: 0 }}
          exit={{ opacity: 0, y: -5 }}
          transition={{ duration: 0.2 }}
        >
          {(name && label
            ? formulario.errors[name]?.message?.replaceAll(name, label)
            : formulario.errors[name]?.message
          )
            ?.split(" ")
            .map((str: string) => {
              return str.length > 3 ? str[0].toUpperCase() + str.slice(1) : str;
            })
            .join(" ")}
        </motion.span>
      )}
    </div>
  );
};

export default InputSelectComponent;
