'use client';

import { useControllableValue } from 'ahooks';
import { cn } from '@/lib';

type TagItem = {
  label: string;
  value: string;
};

type TagSelectProps = {
  options?: {
    label: string;
    value: string;
  }[];
  readonly?: boolean;
  mode?: 'single' | 'multiple';
  value?: string | string[];
  onChange?: (value: string | string[], option: TagItem | TagItem[]) => void;
  render?: (option: TagItem, index: number) => React.ReactNode;
} & React.HTMLAttributes<HTMLDivElement>;

const TagSelect: React.FC<TagSelectProps> = (props) => {
  const {
    options = [],
    readonly = false,
    mode = 'single',
    render = (o) => o.label,
    ...rest
  } = props;
  const [value, onChange] = useControllableValue(props, {
    valuePropName: 'value',
    defaultValuePropName: 'defaultValue',
    trigger: 'onChange',
  });

  const selected =
    mode === 'single' ? [value].filter(Boolean) : (value as string[]) || [];

  const handleSelect = (option: TagItem) => {
    if (readonly) return;
    if (mode === 'single') {
      onChange(option.value === value ? undefined : option.value, option);
    } else {
      const newValues = selected.includes(option.value)
        ? selected.filter((v) => v !== option.value)
        : [...selected, option.value];
      const newOptions = selected.includes(option.value)
        ? selected.filter((v) => v !== option.value)
        : [...selected, option.value];
      onChange(newValues, newOptions);
    }
  };

  return (
    <div {...rest} className={cn('flex flex-wrap gap-2.5', rest.className)}>
      {options.map((option, index) => {
        return (
          <div
            className={cn(
              'bg-text-color/20 text-text-color-1 flex h-7.5 items-center rounded-full px-2.5 py-1 text-sm',
              selected?.includes(option.value) && 'text-text-color',
              !readonly && 'hover:cursor-pointer'
            )}
            key={option.value}
            onClick={() => handleSelect(option)}
          >
            {render(option, index)}
          </div>
        );
      })}
    </div>
  );
};

export default TagSelect;
