import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import Toast from '@arcblock/ux/lib/Toast';
import { api, findCurrency, formatError, usePaymentContext } from '@blocklet/payment-react';
import type { TProductExpanded } from '@blocklet/payment-types';
import { DeleteOutlineOutlined } from '@mui/icons-material';
import { CircularProgress, Grid, IconButton, Stack, Typography } from '@mui/material';
import { useSetState } from 'ahooks';
import { useState } from 'react';
import { ProductsProvider, useProductsContext } from '../../contexts/products';
import { formatProductPrice, isProductCurrenciesMatched } from '../../libs/util';
import InfoCard from '../info-card';
import CrossSellSelect from './cross-sell-select';

export function CrossSellForm({ data, onChange }: { data: TProductExpanded; onChange: Function }) {
  const { locale, t } = useLocaleContext();
  const { settings } = usePaymentContext();
  const [state, setState] = useSetState({
    loading: false,
  });
  const { products } = useProductsContext();
  const [crossSellErr, setCrossSellErr] = useState(false);

  const onRemoveUpsell = async () => {
    try {
      setState({ loading: true });
      await api.put(`/api/products/${data.id}`, { cross_sell: { cross_sells_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 {
      const upsellProduct = products.find((x) => x.id === id);
      if (!upsellProduct) {
        throw new Error('no product found');
      }
      if (!isProductCurrenciesMatched(upsellProduct, data)) {
        setCrossSellErr(true);
        return;
      }
      setState({ loading: true });
      await api.put(`/api/products/${data.id}`, { cross_sell: { cross_sells_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?.default_price?.currency_id || '') || settings.baseCurrency;

  if (data.cross_sell?.cross_sells_to_id) {
    const to = data.cross_sell.cross_sells_to;
    return (
      <Stack
        spacing={1}
        direction="row"
        sx={{
          alignItems: 'center',
        }}>
        <InfoCard
          name={to.name}
          description={formatProductPrice(to as any, defaultCurrency, locale)}
          logo={to.images[0]}
        />
        <IconButton size="small" sx={{ ml: 1 }} onClick={onRemoveUpsell}>
          <DeleteOutlineOutlined color="error" sx={{ opacity: 0.75 }} />
        </IconButton>
      </Stack>
    );
  }

  return (
    <>
      <CrossSellSelect data={data} onSelect={onSelectUpsell} valid={!crossSellErr} />
      {crossSellErr && <Typography color="error">{t('admin.product.currencyNotAligned')}</Typography>}
    </>
  );
}

export default function ProductCrossSell({ data, onChange }: { data: TProductExpanded; onChange: Function }) {
  // const { t } = useLocaleContext();

  return (
    <ProductsProvider>
      <Grid container>
        <Grid size={{ xs: 12 }}>
          <CrossSellForm data={data} onChange={onChange} />
        </Grid>
      </Grid>
    </ProductsProvider>
  );
}
