/* 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, usePaymentContext, Table, findCurrency } from '@blocklet/payment-react';
import type { TProductExpanded } from '@blocklet/payment-types';
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 FilterToolbar from '../../../../components/filter-toolbar';
import InfoCard from '../../../../components/info-card';
import ProductActions from '../../../../components/product/actions';
import { formatProductPrice } from '../../../../libs/util';

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

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

export default function ProductsList() {
  const listKey = 'products';
  const persisted = getDurableData(listKey);

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

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

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

  useBus('product.created', () => refresh(), []);
  useBus('product.updated', () => refresh(), []);
  useBus('product.deleted', () => refresh(), []);

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

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

  const columns = [
    {
      label: t('admin.product.name.label'),
      name: 'name',
      options: {
        filter: true,
        customBodyRenderLite: (_: string, index: number) => {
          const item = data.list[index] as TProductExpanded;
          const currency =
            findCurrency(settings.paymentMethods, item.prices[0]?.currency_id ?? '') || settings.baseCurrency;
          return (
            <Link to={`/admin/products/${item.id}`}>
              <InfoCard
                name={item.name}
                description={formatProductPrice(item as any, currency!, locale)}
                logo={item.images[0]}
              />
            </Link>
          );
        },
      },
    },
    {
      label: t('common.status'),
      name: 'active',
      options: {
        filter: true,
        customBodyRenderLite: (_: string, index: number) => {
          const item = data.list[index] as TProductExpanded;
          return (
            <Link to={`/admin/products/${item.id}`}>
              <Status label={item?.active ? 'Active' : 'Archived'} color={item?.active ? 'success' : 'default'} />
            </Link>
          );
        },
      },
    },
    {
      label: t('common.createdAt'),
      name: 'created_at',
      options: {
        sort: true,
        customBodyRenderLite: (_: string, index: number) => {
          const item = data.list[index] as TProductExpanded;
          return <Link to={`/admin/products/${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 TProductExpanded;
          return <Link to={`/admin/products/${item.id}`}>{formatTime(item.updated_at)}</Link>;
        },
      },
    },
    {
      label: t('common.actions'),
      name: 'id',
      width: 100,
      align: 'center',
      options: {
        sort: false,
        customBodyRenderLite: (_: string, index: number) => {
          const product = data.list[index] as TProductExpanded;
          return <ProductActions data={product} 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']}
      title={
        <FilterToolbar
          setSearch={setSearch}
          search={search}
          status={['active', 'archived']}
          // donation={['hide', 'show']}
        />
      }
      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-description': text,
                'like-name': text,
              },
              pageSize: 100,
              page: 1,
            });
          } else {
            setSearch({
              ...search!,
              pageSize: 100,
              page: 1,
              q: {},
            });
          }
        },
      }}
      loading={!data.list}
      onChange={onTableChange}
    />
  );
}
