import { useEffect, useRef } from "react";

const useSelect= (selector, options = {}) => {
  const selectRef = useRef(null);

  useEffect(() => {
    const $ = window.$;
    const node = selectRef.current;

    if (!node || !$.fn.select2) return;

    const $select = $(node);

    if (!$select.hasClass("select2-hidden-accessible")) {
      $select.select2({
        width: "100%",
        dropdownAutoWidth: true,
        ...options,
      });
    }

    return () => {
      if ($select.hasClass("select2-hidden-accessible")) {
        $select.select2("destroy");
      }
    };
  }, [options]);

  return selectRef;
};

export default useSelect;
