/* eslint-disable react/no-unstable-nested-components */
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import type { Paginated, TPaymentIntentExpanded } from '@blocklet/payment-types';
import { Box, Button, CircularProgress, Stack, Typography } from '@mui/material';
import { useInfiniteScroll } from 'ahooks';

import TxLink from '../../components/blockchain/tx';
import Status from '../../components/status';
import api from '../../libs/api';
import { formatBNStr, formatToDate, getPaymentIntentStatusColor } from '../../libs/util';

const groupByDate = (items: TPaymentIntentExpanded[]) => {
  const grouped: { [key: string]: TPaymentIntentExpanded[] } = {};
  items.forEach((item) => {
    const date = new Date(item.created_at).toLocaleDateString();
    if (!grouped[date]) {
      grouped[date] = [];
    }
    grouped[date]?.push(item);
  });
  return grouped;
};

const fetchData = (params: Record<string, any> = {}): Promise<Paginated<TPaymentIntentExpanded>> => {
  const search = new URLSearchParams();
  Object.keys(params).forEach((key) => {
    search.set(key, String(params[key]));
  });
  return api.get(`/api/payment-intents?${search.toString()}`).then((res: any) => res.data);
};

type Props = {
  customer_id: string;
};

const pageSize = 10;

export default function CustomerPaymentList({ customer_id }: Props) {
  const { t } = useLocaleContext();

  const { data, loadMore, loadingMore, loading } = useInfiniteScroll<Paginated<TPaymentIntentExpanded>>(
    (d) => {
      const page = d ? Math.ceil(d.list.length / pageSize) + 1 : 1;
      return fetchData({ page, pageSize, customer_id });
    },
    {
      reloadDeps: [customer_id],
    }
  );

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

  if (data && data.list.length === 0) {
    return (
      <Typography
        sx={{
          color: 'text.secondary',
        }}>
        {t('payment.customer.payment.empty')}
      </Typography>
    );
  }

  const hasMore = data && data.list.length < data.count;

  const grouped = groupByDate(data.list);

  return (
    <Stack
      direction="column"
      sx={{
        gap: 1,
        mt: 1,
      }}>
      {Object.entries(grouped).map(([date, payments]) => (
        <Box key={date}>
          <Typography sx={{ fontWeight: 'bold', color: 'text.secondary', mt: 2, mb: 1 }}>{date}</Typography>
          {payments.map((item: TPaymentIntentExpanded) => (
            <Stack
              key={item.id}
              direction={{
                xs: 'column',
                sm: 'row',
              }}
              sx={{
                gap: {
                  xs: 0.5,
                  sm: 1.5,
                  md: 3,
                },

                flexWrap: 'nowrap',
                my: 1,
              }}>
              <Box
                sx={{
                  flex: 3,
                }}>
                <Typography>{formatToDate(item.created_at)}</Typography>
              </Box>
              <Box
                sx={{
                  flex: 2,
                }}>
                <Typography
                  sx={{
                    textAlign: 'right',
                  }}>
                  {formatBNStr(item.amount_received, item.paymentCurrency.decimal)}&nbsp;
                  {item.paymentCurrency.symbol}
                </Typography>
              </Box>
              <Box
                sx={{
                  flex: 3,
                }}>
                <Status label={item.status} color={getPaymentIntentStatusColor(item.status)} />
              </Box>
              <Box
                sx={{
                  flex: 3,
                }}>
                <Typography>{item.description || '-'}</Typography>
              </Box>
              <Box
                sx={{
                  flex: 3,
                  minWidth: '220px',
                }}>
                {(item.payment_details?.arcblock?.tx_hash ||
                  item.payment_details?.ethereum?.tx_hash ||
                  item.payment_details?.base?.tx_hash) && (
                  <TxLink details={item.payment_details} method={item.paymentMethod} mode="customer" />
                )}
              </Box>
            </Stack>
          ))}
        </Box>
      ))}
      <Box>
        {hasMore && (
          <Button variant="text" type="button" color="inherit" onClick={loadMore} disabled={loadingMore}>
            {loadingMore
              ? t('common.loadingMore', { resource: t('payment.customer.payments') })
              : t('common.loadMore', { resource: t('payment.customer.payments') })}
          </Button>
        )}
        {!hasMore && data.count > pageSize && (
          <Typography
            sx={{
              color: 'text.secondary',
            }}>
            {t('common.noMore', { resource: t('payment.customer.payments') })}
          </Typography>
        )}
      </Box>
    </Stack>
  );
}
