import { useEffect, useState } from 'react';
import { Radio, Modal, Spin, Popover, Button } from 'antd';
import useSelectRole from './hook';
import style from './index.less';
import { FormattedMessage, useIntl } from 'umi';
import { reloadReactNode } from '../utils/jsxformat';

type SelectRoleProps = {
  appId: number;
  children?: React.ReactChildren;
  value?: API.RoleListItem;
  onChange?: (value: API.RoleListItem) => void;
};

const SelectRole: React.FC<SelectRoleProps> = ({ appId, value, onChange, children }) => {
  const { roleList, loading } = useSelectRole({ appId, isAllowApply: 1 });
  const { formatMessage } = useIntl();
  const [open, setOpen] = useState(false);
  const [selectValue, setSelectValue] = useState<API.RoleListItem | undefined>();

  const triggerRender = () => {
    const name = roleList?.find((item) => item.id === value?.id)?.name;
    return reloadReactNode(
      <Button
        type="primary"
        key="role"
        onClick={() => {
          setOpen(true);
        }}
      >
        {name ?? <FormattedMessage id="component.roleSelect.select" defaultMessage="选择角色" />}
      </Button>,
      setOpen,
      children,
    );
  };

  const closeModal = () => {
    setOpen(false);
    setSelectValue(undefined);
  };

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

  return (
    <>
      <Modal
        title={formatMessage({ id: 'component.roleSelect.title' })}
        width={800}
        open={open}
        onCancel={closeModal}
        footer={
          <div style={{ display: 'flex', justifyContent: 'center' }}>
            <Button
              type="primary"
              disabled={!selectValue?.id}
              onClick={() => {
                if (selectValue) {
                  onChange?.(selectValue);
                }
                closeModal();
              }}
            >
              {formatMessage({ id: 'component.roleSelect.confirm' })}
            </Button>
          </div>
        }
      >
        <Spin spinning={loading}>
          <Radio.Group value={selectValue?.id}>
            <div className={style.radioWrap}>
              {roleList?.map((item) => {
                return (
                  <Radio
                    value={item.id}
                    key={item.id}
                    onChange={() => {
                      setSelectValue(item);
                    }}
                  >
                    <Popover content={item?.name}>
                      <span className={style.roleName}> {item?.name}</span>
                    </Popover>
                  </Radio>
                );
              })}
            </div>
          </Radio.Group>
        </Spin>
      </Modal>
      {triggerRender()}
    </>
  );
};

export default SelectRole;
