"use client";

import * as React from "react";

import {
  Combobox,
  ComboboxChip,
  ComboboxChips,
  ComboboxChipsInput,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxItem,
  ComboboxList,
  useComboboxAnchor,
} from "@/components/ui/combobox";

export type StaffMultiSelectOption = {
  value: string;
  label: string;
};

type StaffMultiSelectProps = {
  id?: string;
  value: string[];
  onChange: (value: string[]) => void;
  options: StaffMultiSelectOption[];
  placeholder?: string;
};

export function StaffMultiSelect({
  id,
  value,
  onChange,
  options,
  placeholder = "Select staff",
}: StaffMultiSelectProps) {
  const anchor = useComboboxAnchor();

  const selected = React.useMemo(
    () => options.filter((option) => value.includes(option.value)),
    [options, value],
  );

  return (
    <Combobox
      multiple
      items={options}
      value={selected}
      onValueChange={(next) => {
        onChange((next ?? []).map((item) => item.value));
      }}
      itemToStringLabel={(item) => item.label}
      isItemEqualToValue={(item, current) => item.value === current.value}
    >
      <ComboboxChips
        ref={anchor}
        id={id}
        className="max-h-28 min-h-9 w-full content-start overflow-y-auto"
      >
        {selected.map((item) => (
          <ComboboxChip key={item.value}>
            {item.label}
          </ComboboxChip>
        ))}
        <ComboboxChipsInput placeholder={selected.length === 0 ? placeholder : "Add…"} />
      </ComboboxChips>
      <ComboboxContent anchor={anchor} className="w-(--anchor-width)">
        <ComboboxEmpty>No staff found</ComboboxEmpty>
        <ComboboxList>
          {(item) => (
            <ComboboxItem key={item.value} value={item}>
              {item.label}
            </ComboboxItem>
          )}
        </ComboboxList>
      </ComboboxContent>
    </Combobox>
  );
}
