/* eslint-disable react/no-unstable-nested-components */
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import {
  Status,
  formatPrice,
  formatTime,
  Table,
  getQueryParams,
  usePaymentContext,
  findCurrency,
} from '@blocklet/payment-react';
import { LockOutlined } from '@mui/icons-material';
import { Stack, Tooltip, Typography, useTheme } from '@mui/material';
import { Link } from 'react-router-dom';

import Copyable from '../../../../components/copyable';
import type { Product } from '../../../../components/product/form';
import PriceActions from './actions';

export default function PricesList({ product, onChange }: { product: Product; onChange: Function }) {
  const { t, locale } = useLocaleContext();
  const { settings } = usePaymentContext();
  const theme = useTheme();
  const query = getQueryParams(window.location.href);

  const columns = [
    {
      label: t('admin.price.name'),
      name: 'name',
      minWidth: 180,
      options: {
        sort: false,
        customBodyRenderLite: (_: any, index: number) => {
          const price = product.prices[index] as any;
          const showHighlight = query.price_id === price.id && query.currency_id;
          const priceCurrency = showHighlight
            ? findCurrency(settings.paymentMethods, query.currency_id || '')
            : price.currency;
          const highlightColor = theme.palette.mode === 'dark' ? '#2e3035' : '#FFF9C4';
          return (
            <Link to={`/admin/products/${price.id}`} color="text.primary">
              <Stack
                direction="row"
                spacing={1}
                sx={{
                  alignItems: 'center',
                }}>
                {price.locked && (
                  <Tooltip title={t('admin.price.locked')}>
                    <LockOutlined sx={{ color: 'text.secondary' }} />
                  </Tooltip>
                )}
                <Typography
                  component="span"
                  sx={{
                    backgroundColor: showHighlight ? highlightColor : 'transparent',
                    whiteSpace: 'nowrap',
                  }}>
                  {formatPrice(price, priceCurrency || price.currency, '', 1, true, locale)}
                </Typography>
                <Typography component="span">
                  {price.id === product.default_price_id && <Status label="default" color="info" sx={{ height: 18 }} />}
                </Typography>
              </Stack>
            </Link>
          );
        },
      },
    },
    {
      label: t('common.id'),
      name: 'id',
      options: {
        sort: false,
        customBodyRender: (id: string) => {
          return <Copyable text={id} />;
        },
      },
    },
    {
      label: t('common.createdAt'),
      name: 'created_at',
      minWidth: 120,
      options: {
        sort: true,
        customBodyRender: (e: string) => {
          return formatTime(e);
        },
      },
    },
    {
      label: t('common.updatedAt'),
      name: 'updated_at',
      minWidth: 120,
      options: {
        customBodyRender: (e: string) => {
          return formatTime(e);
        },
      },
    },
    {
      label: t('admin.price.inventory'),
      name: 'id',
      minWidth: 120,
      options: {
        sort: false,
        customBodyRenderLite: (_: any, index: number) => {
          const price = product.prices[index] as any;
          let additional = '';
          if (price.nickname) {
            additional = `${price.nickname}：`;
          }
          additional += `${price.quantity_available ? t('admin.price.quantityAvailable.format', { num: price.quantity_available }) : t('admin.price.quantityAvailable.noLimit')}`;
          additional += ` / ${t('admin.price.quantitySold.format', {
            num: price.quantity_sold,
          })}`;
          additional += ` / ${price.quantity_limit_per_checkout ? t('admin.price.quantityLimitPerCheckout.format', { num: price.quantity_limit_per_checkout }) : t('admin.price.quantityLimitPerCheckout.noLimit')}`;
          return additional;
        },
      },
    },
    {
      label: t('common.actions'),
      name: 'id',
      width: 100,
      align: 'center',
      options: {
        sort: false,
        customBodyRenderLite: (_: any, index: number) => {
          const price = product.prices[index] as any;
          return (
            <PriceActions
              data={price}
              onChange={onChange}
              setAsDefault={price.id === product.default_price_id}
              product={product as any}
            />
          );
        },
      },
    },
  ];

  return (
    <Table
      toolbar={false}
      footer={false}
      data={product.prices}
      columns={columns}
      options={{
        count: product.prices.length,
        page: 0,
        rowsPerPage: 20,
      }}
      emptyNodeText={t('empty.pricing')}
    />
  );
}
