import {
  TableSearchContext,
  createPageContext,
  useContextSection,
  useExportFile,
  usePage,
} from '@hooks';
import {ListParams, OriginalListParams} from '@models';
import {useCallback} from 'react';
import {Context} from 'use-context-selector';

// type UseTableExportEventOptions<T extends ListParams> = {
//   pageContext: ReturnType<typeof createPageContext>;
//   context: Context<TableSearchContext<OriginalListParams<T>>>;
//   fn: (params: T) => Promise<any>;
// };

// type UseTableExportEventOptionsWithSelector<T extends ListParams, S> = {
//   pageContext: ReturnType<typeof createPageContext>;
//   context: Context<TableSearchContext<S>>;
//   fn: (params: T) => Promise<any>;
//   selector: (state: S) => T;
// };

// export function useTableExportEvent<T extends ListParams>(
//   options: UseTableExportEventOptions<T>,
// ): [boolean, () => void];
// export function useTableExportEvent<T extends ListParams, S extends ListParams>(
//   options: UseTableExportEventOptionsWithSelector<T, S>,
// ): [boolean, () => void];

export function useTableExportEvent<
  P extends ListParams,
  C extends TableSearchContext<any>,
>({
  pageContext,
  context,
  fn,
  parseParams,
}: {
  pageContext: ReturnType<typeof createPageContext>;
  context: Context<C>;
  fn: (params: P) => Promise<any>;
  parseParams?: (state: C[0]) => OriginalListParams<P>;
}): [boolean, () => void] {
  const [{page, pageSize}] = usePage(pageContext);
  const params = useContextSection(context, function ([state]) {
    return parseParams ? parseParams(state) : state;
  });
  const [isExporting, mutate] = useExportFile(fn);

  const onExport = useCallback(
    function () {
      mutate({
        ...params,
        page: String(page),
        limit: String(pageSize),
      } as unknown as P);
    },
    [mutate, page, pageSize, params],
  );

  return [isExporting, onExport];
}
