import Toast from '@arcblock/ux/lib/Toast';
import { api, findCurrency, formatError, formatPrice, usePaymentContext } from '@blocklet/payment-react';
import type { TPriceExpanded } from '@blocklet/payment-types';
import { DeleteOutlineOutlined } from '@mui/icons-material';
import { CircularProgress, Grid, IconButton, Stack, Typography } from '@mui/material';
import { useSetState } from 'ahooks';

import InfoRow from '../info-row';
import UpsellSelect from './upsell-select';

export function UpsellForm({ data, onChange }: { data: TPriceExpanded; onChange: Function }) {
  const { settings } = usePaymentContext();
  const [state, setState] = useSetState({
    loading: false,
  });

  const onRemoveUpsell = async () => {
    try {
      setState({ loading: true });
      await api.put(`/api/prices/${data.id}`, { upsell: { upsells_to_id: '' } }).then((res: any) => res.data);
      setState({ loading: false });
      onChange();
    } catch (err) {
      console.error(err);
      Toast.error(formatError(err));
      setState({ loading: false });
    }
  };

  const onSelectUpsell = async (id: string) => {
    try {
      setState({ loading: true });
      await api.put(`/api/prices/${data.id}`, { upsell: { upsells_to_id: id } }).then((res: any) => res.data);
      setState({ loading: false });
      onChange();
    } catch (err) {
      console.error(err);
      Toast.error(formatError(err));
      setState({ loading: false });
    }
  };

  if (state.loading) {
    return <CircularProgress />;
  }

  const defaultCurrency = findCurrency(settings.paymentMethods, data?.currency_id || '') || settings.baseCurrency;

  if (data.upsell?.upsells_to_id) {
    return (
      <Stack
        spacing={1}
        direction="row"
        sx={{
          alignItems: 'center',
        }}>
        <Typography>{formatPrice(data.upsell.upsells_to, defaultCurrency)}</Typography>
        <IconButton size="small" sx={{ ml: 1 }} onClick={onRemoveUpsell}>
          <DeleteOutlineOutlined color="error" sx={{ opacity: 0.75 }} />
        </IconButton>
      </Stack>
    );
  }

  return <UpsellSelect price={data} onSelect={onSelectUpsell} onAdd={onChange} />;
}

export default function PriceUpsell({ data, onChange }: { data: TPriceExpanded; onChange: Function }) {
  return (
    <Grid container>
      <Grid size={{ xs: 12, md: 12 }}>
        <InfoRow label="" value={<UpsellForm data={data} onChange={onChange} />} showLabel={false} />
      </Grid>
    </Grid>
  );
}
