import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import Toast from '@arcblock/ux/lib/Toast';
import { api, formatError, formatPrice } from '@blocklet/payment-react';
import type { TPriceExpanded } from '@blocklet/payment-types';
import { AddOutlined } from '@mui/icons-material';
import { Alert, CircularProgress, MenuItem, Select, Stack, Typography } from '@mui/material';
import { useRequest, useSetState } from 'ahooks';

import { useMemo } from 'react';
import AddPrice from '../product/add-price';

type Props = {
  price: TPriceExpanded;
  onSelect: Function;
  onAdd: Function;
};

const fetchData = (id: string): Promise<TPriceExpanded[]> => {
  return api.get(`/api/prices/${id}/upsell`).then((res: any) => res.data);
};

export default function UpsellSelect({ price, onSelect, onAdd }: Props) {
  const { t } = useLocaleContext();
  const [state, setState] = useSetState({ loading: false, adding: false, action: '' });

  const { loading, error, data } = useRequest(() => fetchData(price.id));

  const filteredData = useMemo(() => {
    if (!data || data.length === 0) {
      return [];
    }
    const priceCurrencies = price.currency_options?.map((x) => x.currency_id) || [];
    const priceLength = priceCurrencies.length;
    return data.filter((x) => {
      return (
        x.currency_options.length === priceLength &&
        x.currency_options.every((y) => priceCurrencies.includes(y.currency_id))
      );
    });
  }, [data, price.id]);

  if (error) {
    return <Alert severity="error">{error.message}</Alert>;
  }

  if (loading || !data) {
    return <CircularProgress />;
  }

  const onSelectPrice = (e: any) => {
    if (e.target.value && e.target.value !== 'empty') {
      if (e.target.value === 'add') {
        setState({ action: 'add' });
      } else {
        onSelect(e.target.value);
      }
    }
  };

  const onAddPrice = async (formData: any) => {
    try {
      setState({ adding: true });
      await api.post('/api/prices', { ...formData, product_id: price.product_id });
      Toast.success(t('common.saved'));
      onAdd();
    } catch (err) {
      console.error(err);
      Toast.error(formatError(err));
      throw err;
    } finally {
      setState({ adding: false });
    }
  };

  return (
    <>
      <Select
        value="empty"
        sx={{ width: 300 }}
        size="small"
        onChange={onSelectPrice}
        MenuProps={{ style: { maxHeight: 480 } }}>
        <MenuItem value="empty">
          <Stack
            direction="row"
            sx={{
              alignItems: 'center',
            }}>
            <Typography>{t('admin.price.find')}</Typography>
          </Stack>
        </MenuItem>
        <MenuItem value="add">
          <Stack
            direction="row"
            sx={{
              alignItems: 'center',
            }}>
            <AddOutlined />
            <Typography>{t('admin.price.add')}</Typography>
          </Stack>
        </MenuItem>
        {filteredData.map((x) => (
          <MenuItem key={x.id} value={x.id}>
            {formatPrice(x, price.currency || x.currency)}
          </MenuItem>
        ))}
      </Select>
      {state.action === 'add' && (
        <AddPrice loading={state.adding} onSave={onAddPrice} onCancel={() => setState({ action: '' })} />
      )}
    </>
  );
}
