import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import Toast from '@arcblock/ux/lib/Toast';
import { api, formatError } from '@blocklet/payment-react';
import type { PricingTableItem, TProduct, TProductExpanded } from '@blocklet/payment-types';
import { Box, Stack } from '@mui/material';
import { useSetState } from 'ahooks';

import { dispatch } from 'use-bus';
import { useProductsContext } from '../../contexts/products';
import { getPriceFromProducts } from '../../libs/util';
import Actions from '../actions';
import ClickBoundary from '../click-boundary';
import InfoCard from '../info-card';
import EditProduct from '../product/edit';
import PriceItem from './price-item';

type Props = {
  product: TProductExpanded;
  prices: PricingTableItem[];
  valid: boolean;
  onUpdate: () => void;
  onRemove: (i: number) => void;
};

export default function ProductItem({ product, prices, valid, onUpdate, onRemove }: Props) {
  const { t } = useLocaleContext();
  const { products } = useProductsContext();
  const [state, setState] = useSetState({ editing: false, loading: false });

  const onSave = async (updates: TProduct) => {
    try {
      setState({ loading: true });
      await api.put(`/api/products/${product.id}`, updates).then((res: any) => res.data);
      Toast.success(t('common.saved'));
      onUpdate();
    } catch (err) {
      console.error(err);
      Toast.error(formatError(err));
    } finally {
      setState({ loading: false });
    }
  };

  return (
    <Box
      sx={{
        p: 2,
        borderWidth: valid ? 1 : 2,
        borderStyle: 'solid',
        borderColor: valid ? 'divider' : 'error.main',
        borderRadius: 2,
        position: 'relative',
      }}>
      <ClickBoundary>
        <Actions
          sx={{ position: 'absolute', top: 8, right: 16 }}
          actions={[
            {
              label: t('admin.product.edit'),
              handler: () => setState({ editing: true }),
              color: 'primary',
            },
          ]}
        />
      </ClickBoundary>
      <InfoCard logo={product.images[0]} name={product.name} description={product.description} />
      <Stack
        direction="column"
        spacing={2}
        sx={{
          alignItems: 'flex-start',
        }}>
        {prices.map((x: any) => (
          <PriceItem
            key={x.index}
            prefix={`items.${x.index}`}
            price={getPriceFromProducts(products, x.price_id) as any}
            onRemove={() => {
              onRemove(x.index);
              dispatch({
                type: 'product.select.price.removed',
                priceId: x.price_id,
              });
            }}
          />
        ))}
      </Stack>
      {state.editing && (
        <EditProduct
          product={product}
          loading={state.loading}
          onSave={onSave}
          onCancel={() => setState({ editing: false })}
        />
      )}
    </Box>
  );
}
