/* eslint-disable react/no-unstable-nested-components */
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import {
  Status,
  api,
  formatBNStr,
  getInvoiceStatusColor,
  Table,
  useDefaultPageSize,
  getTxLink,
  formatToDate,
} from '@blocklet/payment-react';
import type { TInvoiceExpanded } from '@blocklet/payment-types';
import { CircularProgress, Typography, Box } from '@mui/material';
import { useLocalStorageState } from 'ahooks';
import { useEffect, useState } from 'react';
import { styled } from '@mui/system';

const fetchData = (
  subscriptionId: string,
  currencyId: string,
  params: Record<string, any> = {}
): Promise<{ list: TInvoiceExpanded[]; 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));
  });

  if (subscriptionId) {
    return api.get(`/api/subscriptions/${subscriptionId}/recharge?${search.toString()}`).then((res: any) => res.data);
  }

  if (currencyId) {
    search.set('currency_id', currencyId);
    return api.get(`/api/invoices/recharge?${search.toString()}`).then((res: any) => res.data);
  }

  return Promise.resolve({ list: [], count: 0 });
};

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

type ListProps = {
  features?: {
    customer?: boolean;
    toolbar?: boolean;
    filter?: boolean;
    footer?: boolean;
  };
  currency_id?: string;
  subscription_id?: string;
  recharge_address?: string;
  customer_id?: string;
};

const getListKey = (props: ListProps) => {
  if (props.subscription_id) {
    return `subscription-recharge-${props.subscription_id}`;
  }
  if (props.currency_id) {
    return `currency-recharge-${props.currency_id}`;
  }
  return 'invoices';
};

export default function RechargeList({
  currency_id = '',
  subscription_id = '',
  recharge_address = '',
  customer_id = '',
  features = {
    customer: true,
    filter: true,
  },
}: ListProps) {
  const listKey = getListKey({ currency_id, subscription_id, recharge_address });

  const { t, locale } = useLocaleContext();
  const defaultPageSize = useDefaultPageSize(20);
  const [search, setSearch] = useLocalStorageState<SearchProps>(listKey, {
    defaultValue: {
      currency_id,
      subscription_id,
      pageSize: defaultPageSize,
      page: 1,
    },
  });

  const [data, setData] = useState<{ list?: TInvoiceExpanded[]; count?: number }>({});
  const [loading, setLoading] = useState(true);

  const refresh = async () => {
    setLoading(true);
    try {
      const res = await fetchData(subscription_id || '', currency_id || '', {
        ...search,
        recharge_address,
        customer_id,
      });
      setData(res);
    } catch (error) {
      console.error('Failed to fetch recharge records:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    refresh();
  }, [search, currency_id, subscription_id, recharge_address]);

  const getInvoiceLink = (invoice: TInvoiceExpanded) => {
    return {
      external: true,
      connect: false,
      url: getTxLink(invoice.paymentMethod, invoice.metadata?.payment_details).link,
    };
  };

  const columns = [
    {
      label: t('common.amount'),
      name: 'total',
      width: 80,
      align: 'right',
      options: {
        customBodyRenderLite: (_: string, index: number) => {
          const invoice = data?.list?.[index] as TInvoiceExpanded;
          if (!invoice) return null;

          const link = getInvoiceLink(invoice);
          return (
            <a href={link.url} target="_blank" rel="noreferrer">
              <Typography>
                {formatBNStr(invoice.total, invoice.paymentCurrency.decimal)}&nbsp;
                {invoice.paymentCurrency.symbol}
              </Typography>
            </a>
          );
        },
      },
    },
    {
      label: t('payment.customer.invoice.invoiceNumber'),
      name: 'number',
      options: {
        customBodyRenderLite: (_: string, index: number) => {
          const invoice = data?.list?.[index] as TInvoiceExpanded;
          if (!invoice) return null;

          const link = getInvoiceLink(invoice);
          return (
            <a href={link.url} target="_blank" rel="noreferrer">
              {invoice?.number}
            </a>
          );
        },
      },
    },
    {
      label: t('common.rechargeTime'),
      name: 'created_at',
      options: {
        customBodyRenderLite: (_: string, index: number) => {
          const invoice = data?.list?.[index] as TInvoiceExpanded;
          if (!invoice) return null;

          const link = getInvoiceLink(invoice);
          return (
            <a href={link.url} target="_blank" rel="noreferrer">
              {formatToDate(invoice.created_at, locale, 'YYYY-MM-DD HH:mm:ss')}
            </a>
          );
        },
      },
    },
    {
      label: t('common.status'),
      name: 'status',
      options: {
        customBodyRenderLite: (_: string, index: number) => {
          const invoice = data?.list?.[index] as TInvoiceExpanded;
          if (!invoice) return null;

          const link = getInvoiceLink(invoice);
          return (
            <a href={link.url} target="_blank" rel="noreferrer">
              <Status label={invoice.status} color={getInvoiceStatusColor(invoice.status)} />
            </a>
          );
        },
      },
    },
  ];

  const onTableChange = ({ page, rowsPerPage }: any) => {
    if (search!.pageSize !== rowsPerPage) {
      setSearch((x) => {
        const newState = { ...x };
        if (newState) {
          newState.pageSize = rowsPerPage;
          newState.page = 1;
        }
        return newState as SearchProps;
      });
    } else if (search!.page !== page + 1) {
      setSearch((x) => {
        const newState = { ...x };
        if (newState) {
          newState.page = page + 1;
        }
        return newState as SearchProps;
      });
    }
  };

  return (
    <InvoiceTableRoot>
      {loading ? (
        <Box sx={{ display: 'flex', justifyContent: 'center', p: 3 }}>
          <CircularProgress />
        </Box>
      ) : (
        <Table
          hasRowLink
          data={data.list || []}
          durable={`__${listKey}__`}
          durableKeys={['searchText']}
          columns={columns}
          loading={loading}
          onChange={onTableChange}
          mobileTDFlexDirection="row"
          options={{
            count: data.count || 0,
            page: search!.page - 1,
            rowsPerPage: search!.pageSize,
          }}
          toolbar={false}
          showMobile={false}
          footer={features?.footer}
          emptyNodeText={`${t('empty.invoices')}`}
        />
      )}
    </InvoiceTableRoot>
  );
}

const InvoiceTableRoot = 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;
      }
    }
    .invoice-summary {
      padding-right: 20px;
    }
  }
`;
