import { ReactElement, use } from 'react';
import Button from '@arcblock/ux/lib/Button';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { BLOCKLET_SERVICE_PATH_PREFIX } from '@arcblock/ux/lib/Util/constant';
import { useMemoizedFn, useReactive } from 'ahooks';
import { translate } from '@arcblock/ux/lib/Locale/util';
import { SessionContext } from '@arcblock/did-connect-react/lib/Session';
import Toast from '@arcblock/ux/lib/Toast';

import type { SessionContext as TSessionContext } from '../../@types';
import ResourceDialog from './resource-dialog';
import { translations } from '../libs/locales';

export default function PublishComponent({
  componentDid,
  grantedRoles = undefined,
  onClose,
  render = undefined,
}: {
  componentDid: string;
  grantedRoles?: string[];
  onClose: () => void;
  render?: ({ onClick, loading }: { onClick: () => void; loading: boolean }) => ReactElement<any>;
}) {
  const { session } = use<TSessionContext>(SessionContext);
  const { locale } = useLocaleContext();
  const t = useMemoizedFn((key, data = {}) => {
    return translate(translations, key, locale, 'en', data);
  });
  const currentState = useReactive({
    showDialog: false,
    loading: false,
  });

  const exportUrl = `${BLOCKLET_SERVICE_PATH_PREFIX}/embed/resources/${componentDid}/publish?mode=dialog`;

  const handleClose = useMemoizedFn(() => {
    currentState.showDialog = false;
    onClose?.();
  });
  const handleLoad = useMemoizedFn(() => {
    currentState.loading = false;
  });
  const handleOpen = useMemoizedFn(() => {
    if (!session.user) {
      Toast.warning(t('needLogin'));
      return;
    }

    if (grantedRoles && grantedRoles.length > 0) {
      if (!grantedRoles?.includes(session.user?.role)) {
        Toast.warning(t('noPermission'));
        return;
      }
    }
    currentState.loading = true;
    currentState.showDialog = true;
  });

  return (
    <>
      {render ? (
        render({ onClick: handleOpen, loading: currentState.loading })
      ) : (
        <Button
          key="button"
          variant="outlined"
          color="secondary"
          type="button"
          className="submit"
          loading={currentState.loading}
          onClick={handleOpen}
          sx={{ mr: 1, ml: 1 }}>
          {t('exportResource')}
        </Button>
      )}

      {currentState.showDialog && (
        <ResourceDialog
          src={exportUrl}
          open
          onClose={handleClose}
          onLoad={handleLoad}
          componentDid={componentDid}
          loading={currentState.loading}
        />
      )}
    </>
  );
}
