/* eslint-disable @typescript-eslint/naming-convention */
import { useState } from 'react';
import PropTypes from 'prop-types';
import { useReactive, useMemoizedFn } from 'ahooks';
import noop from 'lodash/noop';
import Dialog from '@arcblock/ux/lib/Dialog';
import Spinner from '@mui/material/CircularProgress';
import DialogContentText from '@mui/material/DialogContentText';
import Typography from '@mui/material/Typography';
import TextField from '@mui/material/TextField';
import Alert from '@mui/material/Alert';
import Toast from '@arcblock/ux/lib/Toast';
import Button from '@arcblock/ux/lib/Button';
import { translate } from '@arcblock/ux/lib/Locale/util';

import { formatAxiosError } from '../../UserCenter/libs/utils';
import useOrg from './use-org';
import translations from './locales';

export default function CreateOrgDialog({ onSuccess = noop, onCancel = noop, locale = 'en' }) {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const { createOrg } = useOrg();
  const t = useMemoizedFn((key, data = {}) => {
    return translate(translations, key, locale, 'en', data);
  });

  const form = useReactive({
    name: '',
    description: '',
  });

  const onSubmit = async () => {
    const _name = form.name.trim();
    if (!_name) {
      setError(t('nameEmpty'));
      return;
    }

    if (_name.length > 25) {
      setError(t('nameTooLong', { length: 25 }));
      return;
    }

    const _description = form.description.trim();

    if (_description.length > 255) {
      setError(t('descriptionTooLong', { length: 25 }));
      return;
    }

    setError('');
    setLoading(true);

    try {
      await createOrg({ name: _name, description: _description });
      onSuccess();
    } catch (err) {
      console.error(err);
      const errMsg = formatAxiosError(err);
      setError(errMsg);
      Toast.error(errMsg);
    } finally {
      setLoading(false);
    }
  };

  const body = (
    <div>
      <Typography component="div" style={{ marginTop: 16 }}>
        <TextField
          label={t('mutate.name')}
          autoComplete="off"
          variant="outlined"
          name="name"
          data-cy="mutate-org-input-name"
          fullWidth
          autoFocus
          value={form.name}
          onChange={(e) => {
            setError('');
            form.name = e.target.value;
          }}
          disabled={loading}
        />
      </Typography>

      <Typography component="div" style={{ marginTop: 16, marginBottom: 16 }}>
        <TextField
          label={t('mutate.description')}
          autoComplete="off"
          variant="outlined"
          name="description"
          data-cy="mutate-org-input-description"
          fullWidth
          value={form.description}
          onChange={(e) => {
            setError('');
            form.description = e.target.value;
          }}
          disabled={loading}
          multiline
          rows={3}
        />
      </Typography>
    </div>
  );

  return (
    <Dialog
      title={t('mutate.title', { mode: t('create') })}
      fullWidth
      open
      onClose={onCancel}
      showCloseButton={false}
      actions={
        <>
          <Button onClick={onCancel} color="inherit">
            {t('cancel')}
          </Button>
          <Button
            data-cy="mutate-org-confirm"
            onClick={onSubmit}
            color="primary"
            disabled={loading}
            variant="contained"
            autoFocus>
            {loading && <Spinner size={16} />}
            {t('create')}
          </Button>
        </>
      }>
      <DialogContentText component="div">{body}</DialogContentText>
      {!!error && (
        <Alert severity="error" style={{ width: '100%', margin: 0 }}>
          {error}
        </Alert>
      )}
    </Dialog>
  );
}

CreateOrgDialog.propTypes = {
  onSuccess: PropTypes.func,
  onCancel: PropTypes.func,
  locale: PropTypes.string,
};
