import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import Toast from '@arcblock/ux/lib/Toast';
import { ConfirmDialog, api } from '@blocklet/payment-react';
import { Alert, Box, CircularProgress, MenuItem, Select, Typography } from '@mui/material';
import { useRequest } from 'ahooks';
import { useEffect, useState } from 'react';

const fetchData = (): Promise<any[]> => {
  return api.get('/api/passports').then((res: any) => res.data);
};

export default function AssignPassportDialog(props: { id: string; onCancel: any }) {
  const { t } = useLocaleContext();
  const { loading, error, data } = useRequest(fetchData);
  const [selected, setSelected] = useState('');

  useEffect(() => {
    if (data && data.length && !selected) {
      setSelected(data[0].name);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [data]);

  const onConfirm = async () => {
    if (!selected) {
      Toast.error(t('admin.passport.assignError'));
      return;
    }

    await api.put('/api/passports/assign', { name: selected, id: props.id });
    Toast.success(t('common.saved'));
    props.onCancel();
  };

  if (error) {
    return (
      <ConfirmDialog
        title={t('admin.passport.assign')}
        message={<Alert severity="error">{error.message}</Alert>}
        onConfirm={onConfirm}
        onCancel={props.onCancel}
        color="primary"
      />
    );
  }

  if (loading || !data) {
    return (
      <ConfirmDialog
        title={t('admin.passport.assign')}
        message={<CircularProgress />}
        onConfirm={onConfirm}
        onCancel={props.onCancel}
        color="primary"
      />
    );
  }

  const onRoleChange = (e: any) => {
    setSelected(e.target.value);
  };

  return (
    <ConfirmDialog
      title={t('admin.passport.assign')}
      message={
        <Box>
          <Typography>{t('admin.passport.assignTip')}</Typography>
          <Select value={selected} onChange={onRoleChange} size="small">
            {data.map((x) => (
              <MenuItem key={x.name} value={x.name}>
                <Typography color={selected ? 'text.primary' : 'text.secondary'}>{x.title}</Typography>
              </MenuItem>
            ))}
          </Select>
        </Box>
      }
      onConfirm={onConfirm}
      onCancel={props.onCancel}
      color="primary"
    />
  );
}
