import type { ModalProps } from 'antd';
import { Button, Input, Modal } from 'antd';
import { memo, useEffect, useState } from 'react';
import style from './index.less';
import { FormattedMessage } from 'umi';
import { UserSelect } from '../index';
import { reloadReactNode } from '../utils/jsxformat';
import type { UserSelectProps } from '../UserSelect';

type UserSelectModalProps = {
  /**
   * @description value传入对象时，selectValue属性为选中值
   */
  value?: any;
  onChange?: (value: any) => void;
  /**
   * @description 考虑到有其他表单项的场景，自定义渲染
   */
  renderItem?: (data: any, onDataChange: (value: any) => void) => React.ReactNode;
  /** @description 选择填入本人 */
  currentUser?: { id: number; nameZh?: string; nameEn?: string; state?: number };
  children?: React.ReactNode;
} & Omit<UserSelectProps, 'value' | 'onChange'> & { modalProps?: ModalProps };

const UserSelectModal: React.FC<UserSelectModalProps> = ({
  value,
  onChange,
  renderItem,
  children,
  modalProps,
  ...restProps
}) => {
  const [data, setData] = useState<any>();
  const [open, setOpen] = useState<boolean>(false);

  const triggerRender = () => {
    return reloadReactNode(
      <a
        onClick={() => {
          setOpen(true);
        }}
      >
        {<FormattedMessage id="component.UserSelect.select" defaultMessage="选择用户" />}
      </a>,
      setOpen,
      children,
    );
  };

  const handleOk = () => {
    setOpen(false);
    onChange?.(data);
    setData(undefined);
  };

  useEffect(() => {
    if (open) {
      setData(value);
    }
  }, [value, open]);

  return (
    <>
      <Modal
        // 默认标题
        title={<FormattedMessage id="component.UserSelect.select" defaultMessage="选择用户" />}
        open={open}
        onCancel={() => {
          setOpen(false);
          setData(undefined);
        }}
        onOk={handleOk}
        {...modalProps}
        okButtonProps={{
          disabled: typeof data === 'object' ? false : !Boolean(data),
        }}
      >
        <div className={style.userSelectModalWrap}>
          <UserSelect
            value={typeof data === 'object' ? data.selectValue : data}
            onChange={(val) =>
              typeof value === 'object'
                ? setData((state) => ({ ...state, selectValue: val }))
                : setData(val)
            }
            {...restProps}
          />
          {<>{renderItem?.(data, (info) => setData((state) => ({ ...state, ...info })))}</>}
        </div>
      </Modal>
      {triggerRender()}
    </>
  );
};

export default memo(UserSelectModal);
