import { useRef, cloneElement } from 'react';
import { Button } from '@mui/material';
import { useMemoizedFn } from 'ahooks';
import OrgTransferSelector from './selector';
import { OrgTransferProps } from './type';
import translations from './locales';
import { translate } from '../Locale/util';

/**
 * org transfer 弹框
 */
export default function Index({
  org,
  onSuccess,
  resourceId,
  buttonProps,
  buttonText,
  locale = 'en',
  dialogProps,
  children,
}: OrgTransferProps) {
  const t = useMemoizedFn((key, data = {}) => {
    return translate(translations, key, locale, 'en', data);
  });
  const dialogRef = useRef(null);

  const handleClick = () => {
    if (dialogRef.current) {
      (dialogRef.current as any).open({ selectedOrg: org });
    }
  };

  return (
    <>
      {children ? (
        cloneElement(children as React.ReactElement, { ...buttonProps, onClick: handleClick } as any)
      ) : (
        <Button {...buttonProps} onClick={handleClick}>
          {buttonText || t('transferOrg')}
        </Button>
      )}

      <OrgTransferSelector
        locale={locale}
        org={org}
        ref={dialogRef}
        resourceId={resourceId}
        onSuccess={onSuccess}
        dialogProps={dialogProps}
      />
    </>
  );
}
