/**
 * 筛选
 */

import React, { FC, useCallback, useMemo, useState } from "react";
import { Select, SelectProps } from "@atomintl/aui-next";
import find from "ramda/src/find";
import { SelectButton } from "./SelectButton";
import clsx from "clsx";
const { Option } = Select;

interface OptionProps {
  label: string;
  value: any;
}
interface Props extends SelectProps {
  value: any;
  list: OptionProps[];
  classes?: {
    customizeSelect?: string;
  };
  disable?: boolean;
}

export const PlaceSelect: FC<Props> = props => {
  const [open, setOpen] = useState(false);
  const { list, value, classes } = props;
  const label = useMemo(() => {
    if (list?.length) {
      return find(item => item.value === value, list)?.label ?? list[0].label ?? "";
    }
    return "";
  }, [list, value]);

  const onChange = (val: string) => {
    setOpen(false);
    props.onChange?.(val);
  };

  const onClose = useCallback((val: boolean) => {
    setOpen(val);
  }, []);

  return (
    <Select
      value={value}
      onChange={onChange}
      placement="right"
      className={clsx("cursor-pointer", props.className)}
      optionWidth={props.optionWidth ?? 116}
      open={open}
      onOpenChange={onClose}
      disabled={props.disable}
      customizeSelect={
        <SelectButton open={open} className={classes?.customizeSelect}>
          {label}
        </SelectButton>
      }
    >
      {list.map(item => (
        <Option value={item.value} key={item.value}>
          {item.label}
        </Option>
      ))}
    </Select>
  );
};

PlaceSelect.defaultProps = {};

export { SelectButton };
