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

import DID from '@arcblock/ux/lib/DID';
import ShortenLabel from '@arcblock/ux/lib/UserCard/Content/shorten-label';
import { debounce, getAppInfo } from '../../libs/util';
import { useCacheState } from '../../hooks/cache-state';
import CustomerLink from '../customer/link';
import FilterToolbar from '../filter-toolbar';
import PayoutActions from './actions';
import InfoCard from '../info-card';

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

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

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

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

  return 'payouts';
};

export default function PayoutList({
  customer_id = '',
  payment_intent_id = '',
  status = '',
  features = {
    customer: true,
    filter: true,
  },
  isCanceledSubscription = false,
}: ListProps) {
  const { t } = useLocaleContext();
  const [searchParams] = useSearchParams();

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

  const [search, setSearch] = useCacheState<SearchProps>(listKey, {
    defaultValue: {
      status: status as string,
      customer_id,
      payment_intent_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;

  useEffect(() => {
    debounce(() => {
      fetchData(search).then((res: any) => {
        setData(res);
      });
    }, 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 TPayoutExpanded;
          return (
            <Link to={`/admin/payments/${item.id}`}>
              <Typography
                component="strong"
                sx={{
                  fontWeight: 600,
                }}>
                {formatBNStr(item.amount, 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 TPayoutExpanded;
          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 TPayoutExpanded;
          return (
            <Link to={`/admin/payments/${item.id}`}>
              <Status label={item.status} color={getPayoutStatusColor(item.status)} />
            </Link>
          );
        },
      },
    },
    {
      label: t('common.description'),
      name: 'description',
      options: {
        customBodyRenderLite: (_: string, index: number) => {
          const item = data.list[index] as TPayoutExpanded;
          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 TPayoutExpanded;
          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 TPayoutExpanded;
          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 TPayoutExpanded;
          return <PayoutActions data={item} isCanceledSubscription={isCanceledSubscription} />;
        },
      },
    },
  ];

  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 TPayoutExpanded;
          if (item.customer) {
            return <CustomerLink customer={item.customer} />;
          }
          const appInfo = getAppInfo(item.destination);
          if (appInfo) {
            return (
              <InfoCard
                name={
                  <ShortenLabel sx={{ fontWeight: 500 }} maxLength={30}>
                    {appInfo.name}
                  </ShortenLabel>
                }
                description={<DID did={item.destination} compact responsive={false} sx={{ whiteSpace: 'nowrap' }} />}
                logo={appInfo.avatar}
                size={40}
              />
            );
          }
          return item.destination;
        },
      } as any,
    });
  }

  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 (
    <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,
        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={['paid', 'pending', 'failed', 'canceled']}
            currency
          />
        )
      }
      emptyNodeText={t('empty.payouts')}
    />
  );
}
