/* 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 { CircularProgress } from '@mui/material';
import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import useBus from 'use-bus';

import { useLocalStorageState } from 'ahooks';
import type { TMeter } from '@blocklet/payment-types';
import MeterActions from '../../../../components/meter/actions';

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

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

export default function MetersList() {
  const listKey = 'meters';
  const persisted = getDurableData(listKey);

  const { t } = useLocaleContext();
  const [search, setSearch] = useLocalStorageState<SearchProps>(listKey, {
    defaultValue: {
      status: '',
      pageSize: persisted.rowsPerPage || 20,
      page: persisted.page ? persisted.page + 1 : 1,
    },
  });

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

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

  useBus('meter.created', () => refresh(), []);

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

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

  const columns = [
    {
      label: t('admin.meter.name.label'),
      name: 'name',
      options: {
        filter: true,
        customBodyRenderLite: (_: string, index: number) => {
          const item = data.list[index] as TMeter;
          return <Link to={`/admin/billing/${item.id}`}>{item.name}</Link>;
        },
      },
    },
    {
      label: t('admin.meter.eventName.label'),
      name: 'event_name',
      options: {
        filter: true,
        customBodyRenderLite: (_: string, index: number) => {
          const item = data.list[index] as TMeter;
          return <Link to={`/admin/billing/${item.id}`}>{item.event_name}</Link>;
        },
      },
    },
    {
      label: t('admin.meter.unit.label'),
      name: 'unit',
      options: {
        filter: true,
        customBodyRenderLite: (_: string, index: number) => {
          const item = data.list[index] as TMeter;
          return <Link to={`/admin/billing/${item.id}`}>{item.unit}</Link>;
        },
      },
    },
    {
      label: t('admin.meter.aggregationMethod.label'),
      name: 'aggregation_method',
      options: {
        filter: true,
        customBodyRenderLite: (_: string, index: number) => {
          const item = data.list[index] as TMeter;
          return (
            <Link to={`/admin/billing/${item.id}`}>
              {t(`admin.meter.aggregationMethod.${item.aggregation_method}`)}
            </Link>
          );
        },
      },
    },
    {
      label: t('common.status'),
      name: 'status',
      options: {
        filter: true,
        customBodyRenderLite: (_: string, index: number) => {
          const item = data.list[index] as TMeter;
          return (
            <Link to={`/admin/billing/${item.id}`}>
              <Status
                label={item?.status === 'active' ? 'Active' : 'Inactive'}
                color={item?.status === 'active' ? 'success' : 'default'}
              />
            </Link>
          );
        },
      },
    },
    {
      label: t('common.createdAt'),
      name: 'created_at',
      options: {
        sort: true,
        customBodyRenderLite: (_: string, index: number) => {
          const item = data.list[index] as TMeter;
          return <Link to={`/admin/billing/${item.id}`}>{formatTime(item.created_at)}</Link>;
        },
      },
    },
    {
      label: t('common.actions'),
      name: 'id',
      width: 100,
      align: 'center',
      options: {
        sort: false,
        customBodyRenderLite: (_: string, index: number) => {
          const meter = data.list[index] as TMeter;
          return <MeterActions data={meter} onChange={refresh} />;
        },
      },
    },
  ];

  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
      durable={`__${listKey}__`}
      durableKeys={['page', 'rowsPerPage', 'searchText']}
      data={data.list}
      columns={columns}
      options={{
        count: data.count,
        page: search!.page - 1,
        rowsPerPage: search!.pageSize,
        onColumnSortChange(_: any, order: any) {
          setSearch({
            ...search!,
            q: search!.q || {},
            o: order,
          });
        },
        onSearchChange: (text: string) => {
          if (text) {
            setSearch({
              ...search!,
              q: {
                'like-name': text,
                'like-event_name': text,
              },
              pageSize: 100,
              page: 1,
            });
          } else {
            setSearch({
              ...search!,
              pageSize: 100,
              page: 1,
              q: {},
            });
          }
        },
      }}
      loading={!data.list}
      onChange={onTableChange}
    />
  );
}
