/* eslint-disable react/no-unstable-nested-components */
import { getDurableData } from '@arcblock/ux/lib/Datatable';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { Status, api, formatTime, Table } from '@blocklet/payment-react';
import type { TWebhookEndpoint } from '@blocklet/payment-types';
import { Alert, CircularProgress, Typography } from '@mui/material';
import { useLocalStorageState, useRequest } from 'ahooks';
import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';

import { useTransitionContext } from '../../../../components/progress-bar';
import { getWebhookStatusColor } from '../../../../libs/util';

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

export default function WebhooksList() {
  const listKey = 'webhooks';
  const persisted = getDurableData(listKey);

  const { t } = useLocaleContext();
  const navigate = useNavigate();
  const { startTransition } = useTransitionContext();
  const [search, setSearch] = useLocalStorageState<{ active: string; pageSize: number; page: number }>(listKey, {
    defaultValue: {
      active: '',
      pageSize: persisted.rowsPerPage || 20,
      page: persisted.page ? persisted.page + 1 : 1,
    },
  });

  const { loading, error, data, refresh } = useRequest(() => fetchData(search));
  useEffect(() => {
    refresh();
  }, [search, refresh]);

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

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

  const columns = [
    {
      label: t('admin.webhookEndpoint.url.label'),
      name: 'url',
    },
    {
      label: t('common.status'),
      name: 'status',
      options: {
        customBodyRenderLite: (_: string, index: number) => {
          const item = data.list[index] as TWebhookEndpoint;
          return <Status label={item?.status} color={getWebhookStatusColor(item?.status)} />;
        },
      },
    },
    {
      label: t('common.updatedAt'),
      name: 'updated_at',
      options: {
        customBodyRender: (e: string) => {
          return formatTime(e);
        },
      },
    },
  ];

  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
      durable={listKey}
      durableKeys={['page', 'rowsPerPage']}
      data={data.list}
      columns={columns}
      options={{
        count: data.count,
        page: search!.page - 1,
        rowsPerPage: search!.pageSize,
        onRowClick: (_: any, { dataIndex }: any) => {
          const item = data.list[dataIndex] as TWebhookEndpoint;
          startTransition(() => {
            navigate(`/admin/developers/${item.id}`);
          });
        },
      }}
      loading={loading}
      onChange={onTableChange}
      title={<Typography variant="h6">{t('admin.webhookEndpoint.hosted')}</Typography>}
      emptyNodeText={t('empty.webhooks')}
    />
  );
}
