/* eslint-disable react/no-unstable-nested-components */
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { api, Table } from '@blocklet/payment-react';
import { Alert, CircularProgress, Typography } from '@mui/material';
import { useRequest } from 'ahooks';
import { Link } from 'react-router-dom';

import PassportActions from '../../../../components/passport/actions';

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

export default function PassportList() {
  const listKey = 'passports';

  const { t } = useLocaleContext();

  const { loading, error, data } = useRequest(fetchData);

  if (error) {
    return <Alert severity="error">{error.message}</Alert>;
  }

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

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

  const columns = [
    {
      label: t('common.title'),
      name: 'title',
      options: {
        sort: false,
      },
    },
    {
      label: t('common.description'),
      name: 'description',
      options: {
        sort: false,
      },
    },
    {
      label: t('admin.products'),
      name: '',
      options: {
        sort: false,
        customBodyRenderLite: (_: string, index: number) => {
          const product = data[index].extra?.payment?.product;
          if (product) {
            return <Link to={`/admin/products/${product}`}>{product}</Link>;
          }

          return (
            <Typography
              component="span"
              sx={{
                color: 'text.secondary',
              }}>
              {t('common.none')}
            </Typography>
          );
        },
      },
    },
    {
      label: t('admin.passport.payLink'),
      name: '',
      options: {
        sort: false,
        customBodyRenderLite: (_: string, index: number) => {
          const payLink = data[index].extra?.acquire?.pay;
          if (payLink) {
            if (payLink.startsWith('plink_') || payLink.startsWith('prctbl_')) {
              return <Link to={`/admin/products/${payLink}`}>{payLink}</Link>;
            }
          }

          return (
            <Typography
              component="span"
              sx={{
                color: 'text.secondary',
              }}>
              {t('common.none')}
            </Typography>
          );
        },
      },
    },
    {
      label: t('admin.passport.payPreview'),
      name: '',
      options: {
        sort: false,
        customBodyRenderLite: (_: string, index: number) => {
          const payLink = data[index].extra?.acquire?.pay;
          if (payLink) {
            if (payLink.startsWith('plink_')) {
              return (
                <Link to={`/checkout/pay/${payLink}`} target="_blank">
                  {payLink}
                </Link>
              );
            }
            if (payLink.startsWith('prctbl_')) {
              return (
                <Link to={`/checkout/pricing-table/${payLink}`} target="_blank">
                  {payLink}
                </Link>
              );
            }
          }

          return (
            <Typography
              component="span"
              sx={{
                color: 'text.secondary',
              }}>
              {t('common.none')}
            </Typography>
          );
        },
      },
    },
    {
      label: t('common.actions'),
      name: '',
      options: {
        sort: false,
        customBodyRenderLite: (_: string, index: number) => {
          return <PassportActions data={data[index]} />;
        },
      },
    },
  ].filter(Boolean);

  return (
    <Table
      durable={listKey}
      data={data}
      columns={columns}
      loading={loading}
      title={
        <Typography variant="subtitle1" sx={{ color: 'text.secondary', whiteSpace: 'break-spaces' }}>
          {t('admin.passport.intro')}
        </Typography>
      }
      options={{
        count: data.length,
        page: 1,
        rowsPerPage: 100,
      }}
    />
  );
}
