import classNames from 'classnames';
import { useState } from 'react';

import PickerToolbar from '@/components/picker-toolbar';
import { EMPLOY_TYPE_TITLE_MAP, EmployType } from '@/constants/job';
import Toast from '@/utils/toast';

import './index.less';

interface IProps {
  onConfirm: (employType: EmployType) => void;
}

interface IGroupProps {
  name: string;
  types: string[];
  typeTitleMap: Record<string, string>;
  selectTypes: string[];
  onClickItem: (item: string) => void;
}

const PREFIX = 'job-type-picker';

const TypeGroup = (props: IGroupProps) => {
  const { name, types, selectTypes, typeTitleMap, onClickItem } = props;
  return (
    <div className={`${PREFIX}__group`}>
      <div className={`${PREFIX}__group-title`}>{name}</div>
      <div className={`${PREFIX}__group-items-container`}>
        {types.map(type => (
          <div
            key={type}
            onClick={() => onClickItem(type)}
            className={classNames(`${PREFIX}__group-item`, { selected: selectTypes.includes(type) })}
          >
            {typeTitleMap[type]}
          </div>
        ))}
      </div>
    </div>
  );
};

function JobPicker(props: IProps) {
  const [selectedEmployTypes, setSelectedEmployTypes] = useState<EmployType[]>([EmployType.Full, EmployType.Part]);
  const { onConfirm } = props;

  const handleClickEmployType = (clickType: EmployType) => {
    if (selectedEmployTypes.includes(clickType)) {
      setSelectedEmployTypes(selectedEmployTypes.filter(type => type !== clickType));
    } else {
      setSelectedEmployTypes(selectedEmployTypes.concat([clickType]));
    }
  };

  const handleClickReset = () => {
    setSelectedEmployTypes([EmployType.Full, EmployType.Part]);
  };

  const handleClickConfirm = () => {
    if (!selectedEmployTypes.length) {
      Toast.error('至少选择一个');
      return;
    }
    const newEmployType = selectedEmployTypes.length === 1 ? selectedEmployTypes[0] : EmployType.All;
    onConfirm(newEmployType);
  };

  return (
    <div className={PREFIX}>
      <div className={`${PREFIX}__groups-container`}>
        <TypeGroup
          name="职位类型"
          types={[EmployType.Full, EmployType.Part]}
          typeTitleMap={EMPLOY_TYPE_TITLE_MAP}
          selectTypes={selectedEmployTypes}
          onClickItem={handleClickEmployType}
        />
      </div>
      <PickerToolbar
        cancelText="重置"
        confirmText="确定"
        onClickCancel={handleClickReset}
        onClickConfirm={handleClickConfirm}
      />
    </div>
  );
}

export default JobPicker;
