import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import Toast from '@arcblock/ux/lib/Toast';
import { api, formatError } from '@blocklet/payment-react';
import type { TCustomerExpanded } from '@blocklet/payment-types';
import { useSetState } from 'ahooks';
import type { LiteralUnion } from 'type-fest';

import Actions from '../actions';
import ClickBoundary from '../click-boundary';
import EditCustomer from './edit';

type Props = {
  data: TCustomerExpanded;
  onChange: (action: string) => void;
  variant?: LiteralUnion<'compact' | 'normal', string>;
};

export default function CustomerActions({ data, onChange, variant = 'compact' }: Props) {
  const { t } = useLocaleContext();
  const [state, setState] = useSetState({
    action: '',
    loading: false,
  });

  const onUpdateInfo = async (updates: TCustomerExpanded) => {
    try {
      setState({ loading: true });
      await api.put(`/api/customers/${data.id}`, updates).then((res: any) => res.data);
      Toast.success(t('common.saved'));
      onChange('update');
    } catch (err) {
      console.error(err);
      Toast.error(formatError(err));
    } finally {
      setState({ loading: false, action: '' });
    }
  };

  return (
    <ClickBoundary>
      <Actions
        variant={variant}
        actions={[
          // {
          //   label: t('admin.payments'),
          //   handler: () => setState({ action: 'refund' }),
          //   color: 'primary',
          //   disabled: true,
          // },
          {
            label: t('admin.customer.edit'),
            handler: () => setState({ action: 'edit' }),
            color: 'primary',
          },
        ]}
      />
      {state.action === 'edit' && (
        <EditCustomer
          data={data}
          loading={state.loading}
          onSave={onUpdateInfo}
          onCancel={() => setState({ action: '' })}
        />
      )}
    </ClickBoundary>
  );
}
