/* eslint-disable react/no-unstable-nested-components */
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { api, formatBNStr, formatTime, Table, useDefaultPageSize, useMobile } from '@blocklet/payment-react';
import type { TCustomer, TPaymentIntentExpanded, TPayoutExpanded } from '@blocklet/payment-types';
import { Box, Typography } from '@mui/material';
import { useLocalStorageState } from 'ahooks';
import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';

import { styled } from '@mui/system';
import { debounce } from '../../../libs/util';
import CustomerLink from '../../customer/link';
import { useConditionalSection } from '../../conditional-section';

const fetchData = (
  params: Record<string, any> = {}
): Promise<{
  list: TPayoutExpanded &
    {
      paymentIntent: TPaymentIntentExpanded & { customer: TCustomer };
    }[];
  count: number;
}> => {
  const search = new URLSearchParams();
  Object.keys(params).forEach((key) => {
    let v = params[key];
    if (key === 'q') {
      v = Object.entries(v)
        .map((x) => x.join(':'))
        .join(' ');
    }
    search.set(key, String(v));
  });
  return api.get(`/api/payouts/mine?${search.toString()}`).then((res: any) => res.data);
};

type SearchProps = {
  status?: string;
  pageSize: number;
  page: number;
  currency_id?: string;
  customer_id?: string;
  q?: any;
  o?: any;
};

type ListProps = {
  status?: string;
  customer_id?: string;
  currency_id?: string;
};

const getListKey = (props: ListProps) => {
  if (props.customer_id) {
    return `customer-payouts-${props.customer_id}`;
  }
  return 'payouts-mine';
};

export default function CustomerRevenueList({ currency_id = '', status = '', customer_id = '' }: ListProps) {
  const { t } = useLocaleContext();
  const { isMobile } = useMobile('sm');
  const conditionalSection = useConditionalSection();

  const listKey = getListKey({ customer_id });
  const defaultPageSize = useDefaultPageSize(10);
  const [search, setSearch] = useLocalStorageState<SearchProps>(listKey, {
    defaultValue: {
      status: status as string,
      customer_id,
      currency_id,
      pageSize: defaultPageSize,
      page: 1,
    },
  });

  const [data, setData] = useState({
    list: [],
    count: 0,
  }) as any;

  useEffect(() => {
    debounce(() => {
      fetchData(search).then((res: any) => {
        setData(res);
        const hasData = res.count > 0;
        conditionalSection?.hideRender(!hasData);
      });
    }, 300)();
  }, [search, conditionalSection]);

  const columns = [
    {
      label: t('common.amount'),
      name: 'id',
      align: 'right',
      width: 80,
      options: {
        customBodyRenderLite: (_: string, index: number) => {
          const item = data.list[index] as TPayoutExpanded;
          return (
            <Link to={`/customer/payout/${item.id}`}>
              <Typography
                component="strong"
                sx={{
                  fontWeight: 600,
                }}>
                {formatBNStr(item.amount, item?.paymentCurrency.decimal)}
                &nbsp;
                {item?.paymentCurrency.symbol}
              </Typography>
            </Link>
          );
        },
      },
    },
    {
      label: t('customer.payout.payer'),
      name: 'customer_id',
      options: {
        customBodyRenderLite: (_: string, index: number) => {
          const item = data.list[index] as TPayoutExpanded & {
            paymentIntent: TPaymentIntentExpanded & { customer: TCustomer };
          };
          // @ts-ignore
          return item?.paymentIntent?.customer ? (
            <CustomerLink
              customer={item.paymentIntent.customer}
              linkTo={`/customer/payout/${item.id}`}
              size={isMobile ? 'small' : 'default'}
            />
          ) : (
            t('common.none')
          );
        },
      } as any,
    },
    {
      label: t('common.createdAt'),
      name: 'created_at',
      options: {
        customBodyRenderLite: (_: string, index: number) => {
          const item = data.list[index] as TPayoutExpanded;
          return <Link to={`/customer/payout/${item.id}`}>{formatTime(item.created_at)}</Link>;
        },
      },
    },
  ];

  const onTableChange = ({ page, rowsPerPage }: any) => {
    if (search!.pageSize !== rowsPerPage) {
      setSearch((x) => ({ ...x, pageSize: rowsPerPage, page: 1 }));
    } else if (search!.page !== page + 1) {
      // @ts-ignore
      setSearch((x) => ({ ...x, page: page + 1 }));
    }
  };

  return (
    <Root>
      <Table
        hasRowLink
        durable={`__${listKey}__`}
        data={data.list || []}
        columns={columns}
        loading={!data.list}
        onChange={onTableChange}
        options={{
          count: data.count,
          page: search!.page - 1,
          rowsPerPage: search!.pageSize,
        }}
        toolbar={false}
        showMobile={false}
        mobileTDFlexDirection="row"
        emptyNodeText={t('customer.payout.empty')}
        sx={{ mt: 2 }}
      />
    </Root>
  );
}

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