import {
  Listbox,
  ListboxButton,
  ListboxOption,
  ListboxOptions,
  Transition,
} from "@headlessui/react";
import {
  CheckIcon,
  ChevronUpDownIcon,
  XMarkIcon,
} from "@heroicons/react/24/outline";
import { __ } from "@wordpress/i18n";
import { Fragment, useEffect, useState } from "react";

const MultiSelect = ({
  placeholder = __("Select", "disco"),
  items,
  selected = [],
  onChange = () => {},
  invalid = false,
}) => {
  const [selectValue, setSelectedValue] = useState(selected);

  const handleChange = (selected) => {
    setSelectedValue(selected);
  };

  const handleRemoveItem = (value) => {
    // Use the displayed selection; the internal copy can be stale if `selected` changed.
    setSelectedValue(selected.filter((item) => item !== value));
  };

  useEffect(() => {
    onChange(selectValue);
  }, [selectValue]);

  return (
    <Listbox value={selected} onChange={handleChange} multiple>
      <div className="ino:relative ino:test">
        <ListboxButton
          className={`ino:relative ino:flex ino:min-h-9 ino:w-full ino:min-w-50 ino:grow ino:cursor-pointer ino:items-center ino:rounded-md ino:border ino:border-border ino:bg-card ino:py-1 ino:pr-9 ino:pl-2.5 ino:text-left ino:text-sm ino:shadow-xs ino:transition-colors ino:hover:border-primary/40 ino:focus:outline-none ino:focus-visible:ring-2 ino:focus-visible:ring-ring/50 ino:data-open:border-primary ${invalid ? "ino:border-red-500! ino:ring-2 ino:ring-red-500/15" : ""}`}
        >
          <span className="ino:flex ino:flex-wrap ino:gap-1.5 ino:text-foreground">
            {selected.length > 0
              ? selected?.map((value) => (
                  <span
                    className="ino:inline-flex ino:items-center ino:gap-1 ino:rounded-full ino:border ino:border-border ino:bg-muted ino:py-0.5 ino:pr-1 ino:pl-2.5 ino:text-xs ino:font-medium ino:text-foreground"
                    key={value}
                  >
                    {items[value]}

                    <XMarkIcon
                      onClick={(e) => {
                        e.stopPropagation();
                        handleRemoveItem(value);
                      }}
                      className="ino:size-4 ino:cursor-pointer ino:rounded-full ino:p-0.5 ino:text-muted-foreground ino:transition-colors ino:hover:bg-red-500/10 ino:hover:text-red-600"
                    />
                  </span>
                ))
              : (
                  <span className="ino:text-muted-foreground">
                    {placeholder}
                  </span>
                )}
          </span>
          <span className="ino:pointer-events-none ino:absolute ino:inset-y-0 ino:right-0 ino:flex ino:items-center ino:pr-2">
            <ChevronUpDownIcon
              className="ino:size-4 ino:text-muted-foreground"
              aria-hidden="true"
            />
          </span>
        </ListboxButton>
        <Transition
          as={Fragment}
          leave="ino:transition ino:ease-in ino:duration-100"
          leaveFrom="ino:opacity-100"
          leaveTo="ino:opacity-0"
        >
          <ListboxOptions className="ino:custom-scrollbar ino:absolute ino:z-10 ino:mt-1.5 ino:max-h-60 ino:w-full ino:cursor-pointer ino:overflow-auto ino:rounded-lg ino:border ino:border-border ino:bg-popover ino:p-1 ino:shadow-lg ino:outline-none">
            {items &&
              Object.keys(items).map((item) => (
                <ListboxOption
                  key={item}
                  className={({ focus }) =>
                    `ino:relative ino:m-0 ino:flex ino:items-center ino:justify-between ino:gap-2 ino:rounded-md ino:px-2 ino:py-1.5 ${focus ? "ino:bg-muted" : ""}`
                  }
                  value={item}
                >
                  {({ selected }) => (
                    <>
                      <span
                        className={`ino:block ino:truncate ino:text-sm ${
                          selected
                            ? "ino:font-medium ino:text-primary"
                            : "ino:text-foreground"
                        }`}
                      >
                        {items[item]}
                      </span>
                      {selected && (
                        <CheckIcon className="ino:size-4 ino:shrink-0 ino:text-primary" />
                      )}
                    </>
                  )}
                </ListboxOption>
              ))}
          </ListboxOptions>
        </Transition>
      </div>
    </Listbox>
  );
};
export default MultiSelect;
