import { Box, MenuItem, Select, SelectChangeEvent, LinearProgress } from '@mui/material';
import { useMemoizedFn, useReactive } from 'ahooks';
import { translate } from '@arcblock/ux/lib/Locale/util';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import Toast from '@arcblock/ux/lib/Toast';
import ArrowDownwardIcon from '@arcblock/icons/lib/ArrowDown';

import { translations } from '../libs/locales';
import { client } from '../../libs/client';
import { User } from '../../@types';
import { formatAxiosError } from '../libs/utils';

const languages = [
  { name: 'English', code: 'en' },
  { name: '中文', code: 'zh' },
];

export default function ConfigProfile({ user, onSave }: { user: User; onSave: (type: 'profile') => void }) {
  const { locale, changeLocale } = useLocaleContext();
  const t = useMemoizedFn((key, data = {}) => {
    return translate(translations, key, locale, 'en', data);
  });
  const currentState = useReactive({
    locale: user.locale,
    loading: false,
  });

  const handleChange = useMemoizedFn(async (e: SelectChangeEvent<string>) => {
    try {
      const { value } = e.target;
      currentState.loading = true;
      await client.user.saveProfile({
        locale: value,
      });
      await onSave('profile');
      changeLocale(value);
      currentState.locale = value;
    } catch (err) {
      Toast.error(formatAxiosError(err as any));
    } finally {
      currentState.loading = false;
    }
  });
  return (
    <Box
      sx={{
        gap: 1,
        display: 'grid',
        alignItems: 'center',
        gridTemplateColumns: {
          xs: '1fr',
          sm: 'max-content 1fr',
        },
      }}>
      <Box>{t('commonSetting.locale')}</Box>
      <Box>
        {currentState.loading ? (
          <LinearProgress
            color="primary"
            sx={{
              height: 2,
            }}
          />
        ) : (
          <Box
            sx={{
              height: 2,
              visibility: 'hidden',
            }}
          />
        )}
        <Select
          value={currentState.locale}
          onChange={handleChange}
          size="small"
          // eslint-disable-next-line react/no-unstable-nested-components
          IconComponent={(props) => <ArrowDownwardIcon {...props} width={20} height={20} />}
          sx={{
            minWidth: 200,
            '&:hover': {
              'fieldset.MuiOutlinedInput-notchedOutline': {
                borderColor: 'divider',
              },
            },
            fieldset: {
              borderColor: 'divider',
            },
          }}>
          {(window.blocklet.languages || languages).map((x: { name: string; code: string }) => (
            <MenuItem value={x.code} key={x.code}>
              {x.name}
            </MenuItem>
          ))}
        </Select>
      </Box>
    </Box>
  );
}
