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

import { useCacheState } from '../../hooks/cache-state';
import CustomerLink from '../customer/link';
import FilterToolbar from '../filter-toolbar';
import SubscriptionActions from './actions';
import SubscriptionDescription from './description';
import SubscriptionStatus from './status';

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

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

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

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

  return 'subscriptions';
};

export default function SubscriptionList({
  customer_id = '',
  features = {
    customer: true,
    filter: true,
  },
  status = '',
}: ListProps) {
  const [searchParams] = useSearchParams();
  const listKey = getListKey({ customer_id });

  const { t } = useLocaleContext();
  const defaultPageSize = useDefaultPageSize(20);

  const [search, setSearch] = useCacheState<SearchProps>(listKey, {
    defaultValue: {
      status: (status || 'active') as string,
      customer_id,
      pageSize: defaultPageSize,
      page: 1,
      price_id: '',
    },
    getUrlParams: () => {
      const params: Record<string, any> = {};
      if (searchParams.has('status')) {
        params.status = searchParams.get('status');
      }
      if (searchParams.has('customer_id')) {
        params.customer_id = searchParams.get('customer_id');
      }
      return params;
    },
  });

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

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

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

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

  const columns = [
    {
      label: t('admin.subscription.product'),
      name: 'id',
      options: {
        customBodyRenderLite: (_: string, index: number) => {
          const item = data.list[index] as TSubscriptionExpanded;
          return (
            <Link to={`/admin/billing/${item.id}`}>
              <SubscriptionDescription subscription={item} />
            </Link>
          );
        },
      },
    },
    {
      label: t('common.status'),
      name: 'status',
      options: {
        filter: true,
        customBodyRenderLite: (_: string, index: number) => {
          const item = data.list[index] as TSubscriptionExpanded;
          return (
            <Link to={`/admin/billing/${item.id}`}>
              <SubscriptionStatus subscription={item} />
            </Link>
          );
        },
      },
    },
    {
      label: t('admin.subscription.collectionMethod'),
      name: 'collection_method',
      options: {
        customBodyRenderLite: (_: string, index: number) => {
          const item = data.list[index] as TSubscriptionExpanded;
          return (
            <Link to={`/admin/billing/${item.id}`}>
              <Status
                label={item.collection_method === 'charge_automatically' ? 'Auto' : 'Manual'}
                color={item.collection_method === 'charge_automatically' ? 'default' : 'warning'}
              />
            </Link>
          );
        },
      },
    },
    {
      label: t('admin.subscription.channel'),
      name: 'channel',
      options: {
        filter: true,
        customBodyRenderLite: (_: string, index: number) => {
          const item = data.list[index] as TSubscriptionExpanded;
          const channel = (item as any).channel || (item as any).paymentMethod?.type;
          if (!channel) return null;
          let color: 'primary' | 'secondary' | 'default' = 'default';
          if (channel === 'google_play' || channel === 'app_store') color = 'primary';
          else if (channel === 'stripe') color = 'secondary';
          return (
            <Link to={`/admin/billing/${item.id}`}>
              <Status label={channel} color={color as any} />
            </Link>
          );
        },
      },
    },
    {
      label: t('common.createdAt'),
      name: 'created_at',
      options: {
        sort: true,
        customBodyRenderLite: (_: string, index: number) => {
          const item = data.list[index] as TSubscriptionExpanded;
          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 item = data.list[index] as TSubscriptionExpanded;
          return <SubscriptionActions data={item} onChange={refresh} />;
        },
      },
    },
  ];

  if (features?.customer) {
    columns.splice(3, 0, {
      label: t('common.customer'),
      name: 'customer_id',
      options: {
        filter: true,
        // @ts-ignore
        customBodyRenderLite: (_: string, index: number) => {
          const item = data.list[index] as TSubscriptionExpanded;
          return <CustomerLink customer={item.customer} />;
        },
      },
    });
  }

  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
      data={data.list}
      columns={columns}
      loading={!data.list}
      onChange={onTableChange}
      durable={`__${listKey}__`}
      durableKeys={['searchText']}
      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-metadata': text,
                'like-description': text,
                'like-id': text,
              },
              pageSize: 100,
              page: 1,
            });
          } else {
            setSearch({
              ...search!,
              pageSize: 100,
              page: 1,
              q: {},
            });
          }
        },
      }}
      toolbar={features?.toolbar}
      footer={features?.footer}
      title={
        features?.filter && (
          <FilterToolbar
            setSearch={setSearch}
            search={search}
            status={['active', 'trialing', 'paused', 'past_due', 'canceled', 'incomplete', 'incomplete_expired']}
            formatStatus={(x) => (x === 'canceled' ? 'ended' : x)}
          />
        )
      }
    />
  );
}
