/* eslint-disable react/no-unstable-nested-components */
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import {
  Status,
  api,
  formatBNStr,
  formatTime,
  getPaymentIntentStatusColor,
  Table,
  useDefaultPageSize,
} from '@blocklet/payment-react';
import type { TPaymentIntentExpanded } from '@blocklet/payment-types';
import { Avatar, CircularProgress, Typography } from '@mui/material';
import { useEffect, useState } from 'react';
import { Link, useSearchParams } from 'react-router-dom';

import { debounce } from '../../libs/util';
import { useCacheState } from '../../hooks/cache-state';
import CustomerLink from '../customer/link';
import FilterToolbar from '../filter-toolbar';
import PaymentIntentActions from './actions';

const fetchData = (params: Record<string, any> = {}): Promise<{ list: TPaymentIntentExpanded[]; 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/payment-intents?${search.toString()}`).then((res: any) => res.data);
};

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

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

const getListKey = (props: ListProps) => {
  if (props.customer_id) {
    return `customer-payments-${props.customer_id}`;
  }
  if (props.invoice_id) {
    return `invoice-payments-${props.invoice_id}`;
  }

  return 'payments';
};

export default function PaymentList({
  customer_id = '',
  invoice_id = '',
  features = {
    customer: true,
    filter: true,
  },
}: ListProps) {
  const { t } = useLocaleContext();
  const [searchParams] = useSearchParams();

  const listKey = getListKey({ customer_id, invoice_id });
  const defaultPageSize = useDefaultPageSize(20);

  const [search, setSearch] = useCacheState<SearchProps>(listKey, {
    defaultValue: {
      status: '',
      customer_id,
      invoice_id,
      pageSize: defaultPageSize,
      page: 1,
    },
    getUrlParams: () => {
      const params: Record<string, any> = {};
      if (searchParams.has('status')) {
        params.status = searchParams.get('status');
      }
      if (searchParams.has('currency_id')) {
        params.currency_id = searchParams.get('currency_id');
      }
      if (searchParams.has('customer_id')) {
        params.customer_id = searchParams.get('customer_id');
      }
      return params;
    },
  });

  const [data, setData] = useState({}) as any;

  const fetchListData = () => {
    fetchData(search).then((res: any) => {
      setData(res);
    });
  };

  useEffect(() => {
    debounce(() => {
      fetchListData();
    }, 300)();
  }, [search]);

  if (!data.list) {
    return <CircularProgress />;
  }

  const columns = [
    {
      label: t('common.amount'),
      name: 'id',
      align: 'right',
      width: 80,
      options: {
        customBodyRenderLite: (_: string, index: number) => {
          const item = data.list[index] as TPaymentIntentExpanded;
          const highlight = item.amount_received === '0' && item.status !== 'canceled';
          return (
            <Link to={`/admin/payments/${item.id}`}>
              <Typography
                component="strong"
                sx={{
                  fontWeight: 600,
                  color: highlight ? 'warning.main' : 'inherit',
                }}>
                {formatBNStr(
                  item.amount_received === '0' ? item.amount : item.amount_received,
                  item?.paymentCurrency.decimal
                )}
                &nbsp;
                {item?.paymentCurrency.symbol}
              </Typography>
            </Link>
          );
        },
      },
    },
    {
      label: t('common.paymentMethod'),
      name: 'paymentMethod',
      width: 120,
      options: {
        customBodyRenderLite: (_: string, index: number) => {
          const item = data.list[index] as TPaymentIntentExpanded;
          return (
            <Link to={`/admin/payments/${item.id}`}>
              <Typography sx={{ display: 'flex', alignItems: 'center', whiteSpace: 'nowrap' }}>
                <Avatar src={item.paymentMethod.logo} sx={{ width: 18, height: 18, mr: 1 }} />
                {item.paymentMethod.name}
              </Typography>
            </Link>
          );
        },
      },
    },
    {
      label: t('common.status'),
      name: 'status',
      width: 80,
      options: {
        customBodyRenderLite: (_: string, index: number) => {
          const item = data.list[index] as TPaymentIntentExpanded;
          return (
            <Link to={`/admin/payments/${item.id}`}>
              <Status label={item.status} color={getPaymentIntentStatusColor(item.status)} />
            </Link>
          );
        },
      },
    },
    {
      label: t('common.description'),
      name: 'description',
      options: {
        customBodyRenderLite: (_: string, index: number) => {
          const item = data.list[index] as TPaymentIntentExpanded;
          return <Link to={`/admin/payments/${item.id}`}>{item.description || item.id}</Link>;
        },
      },
    },
    {
      label: t('common.createdAt'),
      name: 'created_at',
      options: {
        sort: true,
        customBodyRenderLite: (_: string, index: number) => {
          const item = data.list[index] as TPaymentIntentExpanded;
          return <Link to={`/admin/payments/${item.id}`}>{formatTime(item.created_at)}</Link>;
        },
      },
    },
    {
      label: t('common.updatedAt'),
      name: 'updated_at',
      options: {
        sort: true,
        customBodyRenderLite: (_: string, index: number) => {
          const item = data.list[index] as TPaymentIntentExpanded;
          return <Link to={`/admin/payments/${item.id}`}>{formatTime(item.updated_at)}</Link>;
        },
      },
    },
    {
      label: t('common.actions'),
      name: '',
      options: {
        customBodyRenderLite: (_: string, index: number) => {
          const item = data.list[index] as TPaymentIntentExpanded;
          return <PaymentIntentActions data={item} onChange={fetchListData} />;
        },
      },
    },
  ];

  if (features?.customer) {
    columns.splice(3, 0, {
      label: t('common.customer'),
      name: 'customer_id',
      options: {
        filter: true,
        customBodyRenderLite: (_: string, index: number) => {
          const item = data.list[index] as TPaymentIntentExpanded;
          return <CustomerLink customer={item.customer} />;
        },
      } as any,
    });
  }

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

  return (
    <Table
      hasRowLink
      data={data.list || []}
      durable={`__${listKey}__`}
      durableKeys={['searchText']}
      columns={columns}
      loading={!data.list}
      onChange={onTableChange}
      options={{
        count: data.count,
        page: search!.page - 1,
        rowsPerPage: search!.pageSize,
        onSearchChange: (text: string) => {
          if (text) {
            setSearch({
              ...search!,
              q: {
                'like-description': text,
                'like-metadata': text,
              },
              pageSize: 100,
              page: 1,
            });
          } else {
            setSearch({
              ...search!,
              pageSize: 100,
              page: 1,
              q: {},
            });
          }
        },
        onColumnSortChange(_: any, order: any) {
          setSearch({
            ...search!,
            q: search!.q || {},
            o: order,
          });
        },
      }}
      toolbar={features?.toolbar}
      footer={features?.footer}
      title={
        features?.filter && (
          <FilterToolbar
            setSearch={setSearch}
            search={search}
            status={[
              'succeeded',
              'canceled',
              'processing',
              'requires_action',
              'requires_capture',
              'requires_payment_method',
              'requires_confirmation',
            ]}
            currency
          />
        )
      }
      emptyNodeText={t('empty.payments')}
    />
  );
}
