import { Box, Typography } from '@mui/material';
import Switch from '@arcblock/ux/lib/Switch';
import { ChangeEvent, useState } from 'react';
import { useMemoizedFn } 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 type { AxiosError } from 'axios';

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

type PrivacyConfig = {
  key: string;
  name: string;
  value: boolean;
  isPrivate?: boolean;
};

export default function Privacy({
  configList,
  onSave,
}: {
  configList: PrivacyConfig[];
  onSave: (type: 'privacy') => void;
}) {
  const [dataList, setDataList] = useState(configList);
  const { locale } = useLocaleContext();
  const t = useMemoizedFn((key, data = {}) => {
    return translate(translations, key, locale, 'en', data);
  });
  const handleChangeSwitch = useMemoizedFn(async (type: string, value: boolean) => {
    try {
      const result = await client.user.saveUserPrivacyConfig({
        [type]: !value,
      });

      setDataList(
        dataList.map((item) => {
          return {
            ...item,
            value: result?.[item.key] ?? item.value,
          };
        })
      );
      Toast.success(t('saveSuccess'));
      onSave('privacy');
    } catch (err) {
      Toast.error(formatAxiosError(err as AxiosError));
    }
  });

  return (
    <Box
      sx={{
        display: 'flex',
        flexDirection: 'column',
        gap: 1,
        alignItems: 'start',
        '.MuiFormControlLabel-root': {
          gap: 1,
          m: 0,
          flexDirection: {
            xs: 'row-reverse',
            md: 'row',
          },
          width: {
            xs: '100%',
            md: 'unset',
          },
        },

        '.MuiSwitch-track': {
          borderRadius: '100vw',
        },
        '.MuiSwitch-thumb': {
          borderRadius: '100%',
        },
        '.MuiSwitch-root.MuiSwitch-sizeSmall': {
          height: '20px',
          width: '36px',
          '.MuiSwitch-thumb': {
            width: '16px',
            height: '16px',
          },
        },
      }}>
      {dataList.map((item) => {
        if (item.isPrivate) {
          return null;
        }
        return (
          <Switch
            key={item.key}
            checked={!item.value}
            labelProps={{
              label: (
                <Typography
                  sx={{
                    color: 'text.primary',
                    fontSize: 14,
                    display: 'flex',
                    flexFlow: 'wrap',
                    columnGap: 1,
                    flex: 1,
                  }}>
                  {t('toPublic', { name: item.name })}
                </Typography>
              ),
            }}
            size="small"
            onChange={(event: ChangeEvent<HTMLInputElement>) => handleChangeSwitch(item.key, event.target.checked)}
          />
        );
      })}
    </Box>
  );
}
