/* eslint-disable react/no-unstable-nested-components */
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { formatPrice, Table, TruncatedText, useMobile } from '@blocklet/payment-react';
import type { TPaymentCurrency, TSubscriptionItemExpanded } from '@blocklet/payment-types';
import { Avatar, Stack, Typography, Box } from '@mui/material';
import { styled } from '@mui/system';

import { Link } from 'react-router-dom';
import Copyable from '../../copyable';
import LineItemActions from './actions';
import UsageRecords from './usage-records';

type ListProps = {
  data: TSubscriptionItemExpanded[];
  currency: TPaymentCurrency;
  mode?: 'admin' | 'customer';
};

const size = { width: 48, height: 48 };

export default function SubscriptionItemList({ data, currency, mode = 'customer' }: ListProps) {
  const { t } = useLocaleContext();
  const { isMobile } = useMobile();
  const isAdmin = mode === 'admin';

  const columns = [
    {
      label: t('admin.subscription.product'),
      name: 'price_id',
      options: {
        customBodyRenderLite: (_: string, index: number) => {
          const item = data[index] as TSubscriptionItemExpanded;
          return (
            <Stack
              sx={{
                flexDirection: 'row',
                flexWrap: 'wrap',
                alignItems: 'center',

                gap: {
                  xs: 1,
                  sm: 2,
                },
              }}>
              <Box
                sx={{
                  order: isMobile ? 2 : 1,
                }}>
                {item.price.product.images.length > 0 ? (
                  // @ts-ignore
                  <Avatar
                    key={item.price.product_id}
                    src={item.price.product.images[0]}
                    alt={item.price.product.name}
                    variant="rounded"
                    sx={size}
                  />
                ) : (
                  <Avatar key={item.price.product_id} variant="rounded" sx={size}>
                    {item.price.product.name.slice(0, 1)}
                  </Avatar>
                )}
              </Box>
              <Box
                sx={{
                  order: isMobile ? 1 : 2,
                }}>
                {isAdmin ? (
                  <>
                    <Typography
                      sx={{
                        color: 'text.primary',
                        fontWeight: 600,
                      }}>
                      <Link to={`/admin/products/${item?.price.product_id}`}>
                        <TruncatedText text={item?.price.product.name} maxLength={isMobile ? 20 : 50} useWidth />
                      </Link>
                    </Typography>
                    <Typography
                      sx={{
                        color: 'text.secondary',
                        whiteSpace: 'nowrap',
                      }}>
                      <Link to={`/admin/products/${item?.price.id}`}>
                        {formatPrice(item.price, currency, item?.price.product.unit_label)}
                      </Link>
                    </Typography>
                  </>
                ) : (
                  <Box
                    sx={
                      isMobile
                        ? {
                            display: 'flex',
                            flexDirection: 'column',
                            alignItems: 'flex-end',
                            gap: 0.5,
                            flex: 1,
                          }
                        : {}
                    }>
                    <Typography
                      sx={{
                        color: 'text.primary',
                        fontWeight: 600,
                      }}>
                      <TruncatedText text={item?.price.product.name} maxLength={isMobile ? 20 : 50} useWidth />
                    </Typography>
                    <Typography
                      sx={{
                        color: 'text.secondary',
                        whiteSpace: 'nowrap',
                      }}>
                      {formatPrice(item.price, currency, item?.price.product.unit_label)}
                    </Typography>
                  </Box>
                )}
              </Box>
            </Stack>
          );
        },
      },
    },
    {
      label: t('admin.subscription.itemId'),
      name: 'id',
      options: {
        customBodyRenderLite: (_: string, index: number) => {
          const item = data[index] as TSubscriptionItemExpanded;
          return <Copyable text={item.id} />;
        },
      },
    },
    currency.type !== 'credit' && {
      label: t('common.quantity'),
      name: 'quantity',
      options: {
        customBodyRenderLite: (_: string, index: number) => {
          const item = data[index] as TSubscriptionItemExpanded;
          return item.price.recurring?.usage_type === 'metered' ? (
            <UsageRecords subscriptionId={item.subscription_id} id={item.id} />
          ) : (
            item.quantity
          );
        },
      },
    },
    {
      label: t('common.total'),
      name: 'id',
      align: 'right',
      options: {
        sort: false,
        customBodyRenderLite: (_: string, index: number) => {
          const item = data[index] as TSubscriptionItemExpanded;
          return item.price.recurring?.usage_type === 'metered'
            ? t('admin.subscription.usage.vary')
            : formatPrice(item.price, currency, item?.price.product.unit_label, item?.quantity);
        },
      },
    },
    mode === 'admin' && {
      label: t('common.actions'),
      name: '',
      align: 'center',
      options: {
        sort: false,
        customBodyRenderLite: (_: string, index: number) => {
          const item = data[index] as TSubscriptionItemExpanded;

          return <LineItemActions data={item as any} />;
        },
      },
    },
  ].filter(Boolean);

  return (
    <InvoiceTableRoot>
      <Table
        data={data}
        columns={columns}
        loading={false}
        footer={false}
        toolbar={false}
        components={{
          TableToolbar: () => null,
          TableFooter: () => null,
        }}
        mobileTDFlexDirection="row"
        options={{
          count: data.length,
          page: 0,
          rowsPerPage: 100,
        }}
        emptyNodeText={t('customer.product.empty')}
      />
    </InvoiceTableRoot>
  );
}

const InvoiceTableRoot = styled(Box)`
  @media (max-width: ${({ theme }) => theme.breakpoints.values.md}px) {
    .MuiTable-root > .MuiTableBody-root > .MuiTableRow-root > td.MuiTableCell-root {
      align-items: center;
      padding: 4px 0;
      > div {
        width: fit-content;
        flex: inherit;
        font-size: 14px;
      }
    }
    .invoice-summary {
      padding-right: 20px;
    }
  }
`;
