import { useState } from 'react';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { findCurrency, usePaymentContext } from '@blocklet/payment-react';
import type { TProductExpanded } from '@blocklet/payment-types';
import { FormControl, MenuItem, Select, Stack, Typography } from '@mui/material';

import { useProductsContext } from '../../contexts/products';
import { formatProductPrice, isProductCurrenciesMatched } from '../../libs/util';
import InfoCard from '../info-card';

type Props = {
  data: TProductExpanded;
  onSelect: Function;
  valid: boolean;
};

export default function CrossSellSelect({ data, onSelect, valid }: Props) {
  const { t, locale } = useLocaleContext();
  const { products } = useProductsContext();
  const { settings } = usePaymentContext();
  const [value, setValue] = useState('empty');

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

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

  return (
    <FormControl error={!valid} sx={{ width: '100%' }}>
      <Select
        value={value}
        sx={{ minWidth: 300 }}
        size="small"
        onChange={onSelectPrice}
        MenuProps={{ style: { maxHeight: 480 } }}>
        <MenuItem value="empty">
          <Stack
            direction="row"
            sx={{
              alignItems: 'center',
            }}>
            <Typography>{t('admin.product.find')}</Typography>
          </Stack>
        </MenuItem>
        {products
          .filter((x) => x.id !== data.id && isProductCurrenciesMatched(x, data))
          .map((x: TProductExpanded) => (
            <MenuItem key={x.id} value={x.id}>
              <InfoCard
                name={x.name}
                description={formatProductPrice(x as any, defaultCurrency, locale)}
                logo={x.images[0]}
              />
            </MenuItem>
          ))}
      </Select>
    </FormControl>
  );
}
