import { Image } from '@tarojs/components';

import { Popup } from '@taroify/core';
import classNames from 'classnames';
import { isEqual } from 'lodash-es';

import SafeBottomPadding from '@/components/safe-bottom-padding';

import './index.less';

export interface ISelectOption<T> {
  label: string;
  value?: T;
}

export interface ISelectProps<T = BL.Anything> {
  value?: ISelectOption<T>['value'];
  options: ISelectOption<T>[];
  title?: string;
  onSelect: (value: ISelectOption<T>['value']) => void;
  className?: string;
}

export interface IPopupSelectProps<T = BL.Anything> extends ISelectProps<T> {
  open: boolean;
  onClose: () => void;
}

const PREFIX = 'bl-select';

function Select(props: ISelectProps) {
  const { value: selectValue, options, title = '筛选', className, onSelect } = props;
  return (
    <div className={classNames(PREFIX, className)}>
      <div className={`${PREFIX}__title`}>{title}</div>
      <div className={`${PREFIX}__items-container`}>
        {options.map(option => {
          const { label, value } = option;
          const isSelect = isEqual(value, selectValue);
          return (
            <div
              key={label}
              className={classNames(`${PREFIX}__salary-item`, { selected: isSelect })}
              onClick={() => onSelect(option.value)}
            >
              <div>{label}</div>
              {isSelect && (
                <Image
                  mode="aspectFit"
                  className={`${PREFIX}__select-icon`}
                  src={require('@/statics/svg/success.svg')}
                />
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

export function PopupSelect(props: IPopupSelectProps) {
  const { open, onClose, ...otherProps } = props;

  return (
    <Popup className={`${PREFIX}__with-popup`} placement="bottom" open={open} onClose={onClose}>
      <Select {...otherProps} />
      <SafeBottomPadding />
    </Popup>
  );
}

export default Select;
