import React, { useState, useMemo } from "react";

const TagMultiSelect = ({
  label = "Select Items",
  id,
  options = [],
  dataSelected = [],
  onChange = () => {},
  containerClassName = "sofax-main-field",
  labelClassName = "",
  inputClassName = "block w-full px-4 py-2 border border-gray-300 rounded bg-white",
  required = false,
  disabled = false,
  helpText = "Click to select, and click the x to remove.",
  placeholder = "Select...",
}) => {
  // Local state for dropdown visibility and search term
  const [showOptions, setShowOptions] = useState(false);
  const [searchTerm, setSearchTerm] = useState("");

  // Filter options to get selected list
  const selectedOptions = options.filter((opt) =>
    dataSelected.includes(opt.value)
  );

  // Filter available options based on selection and search term
  const availableOptions = useMemo(
    () =>
      options.filter(
        (opt) =>
          !dataSelected.includes(opt.value) &&
          opt.label.toLowerCase().includes(searchTerm.toLowerCase())
      ),
    [options, dataSelected, searchTerm]
  );

  // Handle selection (converting string value to number)
  const handleSelectOption = (value) => {
    // If value is empty, do nothing.
    if (value === "") return;
    const numericValue = Number(value);
    if (!dataSelected.includes(numericValue)) {
      onChange([...dataSelected, numericValue]);
    }
    setShowOptions(false);
    setSearchTerm(""); // Reset search after selection
  };

  // Handle removal
  const removeSelected = (value) => {
    onChange(dataSelected.filter((val) => val !== value));
  };

  return (
    <div className={containerClassName}>
      {label && (
        <label htmlFor={id} className={labelClassName}>
          {label}
          {required && <span className="text-danger ml-1">*</span>}
        </label>
      )}
      <br />
      <div className="combo-box w-100">
        <div className="selected-tags mb-2 d-flex flex-wrap align-items-center">
          {selectedOptions.length > 0 ? (
            selectedOptions.map((option) => (
              <span
                key={option.value}
                className="d-inline-flex align-items-center mr-2 mb-2  border rounded px-3 py-1 small text-muted"
              >
                {option.label}
                <button
                  type="button"
                  className="btn btn-link ml-2 text-danger p-0"
                  onClick={() => removeSelected(option.value)}
                >
                  &times;
                </button>
              </span>
            ))
          ) : (
            <span className="text-muted">{placeholder}</span>
          )}
        </div>
        {!disabled && (
          <>
            {/* Search input */}
            <input
              type="text"
              placeholder="Search..."
              className="form-control mb-2"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
            />
            <select
              id={`${id}-select`}
              className={inputClassName}
              style={{ width: "100%" }}
              size={5}
              onChange={(e) => handleSelectOption(e.target.value)}
              disabled={disabled}
            >
              <option value="">--</option>
              {availableOptions.map((option) => (
                <option
                  key={option.value}
                  value={option.value}
                  // Add a text-secondary class for a lighter color
                  className="text-secondary"
                >
                  {option.label}
                </option>
              ))}
            </select>
          </>
        )}
        {helpText && (
          <small id={`${id}Help`} className="form-text text-muted">
            {helpText}
          </small>
        )}
      </div>
    </div>
  );
};

export default TagMultiSelect;
