/* eslint-disable react/no-unstable-nested-components */
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import {
  findCurrency,
  formatPrice,
  formatTime,
  Table,
  TruncatedText,
  useMobile,
  usePaymentContext,
} from '@blocklet/payment-react';
import type { TProductExpanded } from '@blocklet/payment-types';
import { Avatar, Stack, Typography, Box } from '@mui/material';
import { Link } from 'react-router-dom';

interface Props {
  products: any[];
}

export default function ApplicableProductsList({ products }: Props) {
  const { t } = useLocaleContext();
  const { isMobile } = useMobile();
  const { settings } = usePaymentContext();

  const getPriceDisplay = (product: TProductExpanded) => {
    if (!product.prices || product.prices.length === 0) {
      return null;
    }

    if (product.prices.length === 1) {
      const price = product.prices[0];
      if (price) {
        const currency = findCurrency(settings.paymentMethods, price.currency_id ?? '') || settings.baseCurrency;
        return formatPrice(price, currency!);
      }
    }

    return t('admin.price.count', { count: product.prices.length });
  };

  const size = isMobile ? { width: 24, height: 24 } : { width: 48, height: 48 };

  const columns = [
    {
      label: t('admin.subscription.product'),
      name: 'name',
      options: {
        customBodyRenderLite: (_: string, index: number) => {
          const product = products[index];
          return (
            <Stack
              sx={{
                flexDirection: 'row',
                flexWrap: 'wrap',
                alignItems: 'center',
                gap: {
                  xs: 1,
                  sm: 2,
                },
              }}>
              <Box>
                {product.images && product.images.length > 0 ? (
                  <Avatar key={product.id} src={product.images[0]} alt={product.name} variant="rounded" sx={size} />
                ) : (
                  <Avatar key={product.id} variant="rounded" sx={size}>
                    {product.name.slice(0, 1)}
                  </Avatar>
                )}
              </Box>
              <Box>
                <Typography
                  sx={{
                    color: 'text.primary',
                    fontWeight: 600,
                  }}>
                  <Link to={`/admin/products/${product.id}`}>
                    <TruncatedText text={product.name} maxLength={isMobile ? 20 : 50} useWidth />
                  </Link>
                </Typography>
                {!isMobile && (
                  <Typography
                    sx={{
                      color: 'text.secondary',
                      whiteSpace: 'nowrap',
                    }}>
                    {getPriceDisplay(product)}
                  </Typography>
                )}
              </Box>
            </Stack>
          );
        },
      },
    },
    isMobile && {
      label: t('admin.product.pricing'),
      name: 'prices',
      options: {
        customBodyRenderLite: (_: string, index: number) => {
          const product = products[index];
          return <Link to={`/admin/products/${product.id}`}>{getPriceDisplay(product)}</Link>;
        },
      },
    },
    {
      label: t('admin.product.type.label'),
      name: 'type',
      options: {
        customBodyRenderLite: (_: string, index: number) => {
          const product = products[index];
          return t(`admin.product.type.${product.type}`);
        },
      },
    },
    {
      label: t('common.created'),
      name: 'created_at',
      options: {
        customBodyRenderLite: (_: string, index: number) => {
          const product = products[index];
          return formatTime(product.created_at);
        },
      },
    },
  ].filter(Boolean);

  return (
    <Table
      data={products}
      columns={columns}
      loading={false}
      footer={false}
      toolbar={false}
      components={{
        TableToolbar: () => null,
        TableFooter: () => null,
      }}
      mobileTDFlexDirection="row"
      options={{
        count: products.length,
        page: 0,
        rowsPerPage: 100,
        selectableRows: 'none',
        pagination: false,
      }}
      emptyNodeText={t('admin.coupon.noApplicableProducts')}
    />
  );
}
