import { PageAction } from '@/config';
import { PaginationKey } from '@/config/settings';
import type { PageActionType } from '@/config/types';
import useTableFetch from '@/hooks/use-table-fetch';
import useQueryUserList from '@/pages/users/services/use-query-user-list';
import { getGPUStackPlugin } from '@/plugins';
import { useModel } from '@@/plugin-model';
import { DeleteModal, FilterBar, IconFont, NoResult } from '@gpustack/core-ui';
import { useIntl } from '@umijs/max';
import useMemoizedFn from 'ahooks/lib/useMemoizedFn';
import { ConfigProvider, Table } from 'antd';
import _ from 'lodash';
import { useEffect, useState } from 'react';
import PageBox from '../_components/page-box';
import { deleteApisKey, queryApisKeysList } from './apis';
import AddAPIKeyModal from './components/add-apikey-modal';
import { ListItem } from './config/types';
import useKeysColumns from './hooks/use-keys-columns';

const APIKeys: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const currentUser = initialState?.currentUser;
  const {
    TABLE_SORT_DIRECTIONS,
    dataSource,
    rowSelection,
    queryParams,
    sortOrder,
    modalRef,
    handleDelete,
    handleDeleteBatch,
    fetchData,
    handlePageChange,
    handleTableChange,
    handleQueryChange,
    handleSearch,
    handleNameChange
  } = useTableFetch<ListItem>({
    key: PaginationKey.APIKeys,
    fetchAPI: queryApisKeysList,
    deleteAPI: deleteApisKey,
    contentForDelete: 'apikeys.table.apikeys',
    defaultQueryParams: {
      user_id: currentUser?.is_admin ? '*' : undefined
    }
  });
  const {
    dataList: userList,
    fetchData: fetchUserData,
    cancelRequest: cancelUserRequest
  } = useQueryUserList({
    getLabel: (item) => item.username,
    getValue: (item) => item.id
  });

  const intl = useIntl();

  const apiKeyIPConfig = getGPUStackPlugin()?.APIKeyIPConfig;
  const APIKeyIPConfigForm = apiKeyIPConfig?.form;
  const { openIPConfigModalStatus, openIPConfigModal, closeIPConfigModal } =
    apiKeyIPConfig?.useCreateIPConfig?.() || {};

  const [openAddModal, setOpenAddModal] = useState<{
    open: boolean;
    action: PageActionType;
    title: string;
    currentData?: Partial<ListItem> | null;
  }>({
    open: false,
    action: PageAction.CREATE,
    title: '',
    currentData: null
  });

  useEffect(() => {
    fetchUserData({
      page: -1
    });
    return () => {
      cancelUserRequest();
    };
  }, []);

  const handleAddKey = () => {
    setOpenAddModal({
      open: true,
      title: intl.formatMessage({ id: 'apikeys.button.create' }),
      action: PageAction.CREATE,
      currentData: null
    });
  };

  const handleEditKey = (record: ListItem) => {
    setOpenAddModal({
      open: true,
      title: intl.formatMessage({ id: 'apikeys.button.edit' }),
      action: PageAction.EDIT,
      currentData: record
    });
  };

  const handleModalOk = async () => {
    try {
      await fetchData();
      setOpenAddModal({
        open: false,
        title: '',
        action: PageAction.CREATE,
        currentData: null
      });
    } catch (error) {
      // do nothing
    }
  };

  const handleModalCancel = () => {
    setOpenAddModal({
      open: false,
      title: '',
      action: PageAction.CREATE,
      currentData: null
    });
  };

  const onSelect = useMemoizedFn(
    async (
      val: string,
      record: ListItem,
      item?: { onClick?: (r: ListItem) => void }
    ) => {
      if (item?.onClick) {
        item.onClick(record);
        return;
      }
      if (val === 'delete') {
        handleDelete(record);
      } else if (val === 'edit') {
        handleEditKey(record);
      }
    }
  );

  const handleUserChange = (val: string) => {
    handleQueryChange({
      user_id: val || '*'
    });
  };

  const renderEmpty = (type?: string) => {
    if (type !== 'Table') return;
    return (
      <NoResult
        loading={dataSource.loading}
        loadend={dataSource.loadend}
        dataSource={dataSource.dataList}
        image={<IconFont type="icon-key" />}
        filters={_.omit(queryParams, ['sort_by'])}
        noFoundText={intl.formatMessage({
          id: 'noresult.keys.nofound'
        })}
        title={intl.formatMessage({ id: 'noresult.keys.title' })}
        subTitle={intl.formatMessage({ id: 'noresult.keys.subTitle' })}
        onClick={handleAddKey}
        buttonText={intl.formatMessage({ id: 'noresult.button.add' })}
      ></NoResult>
    );
  };

  const columns = useKeysColumns({
    handleSelect: onSelect,
    sortOrder,
    is_admin: currentUser?.is_admin,
    onIPConfig: openIPConfigModal
  });

  return (
    <>
      <PageBox>
        <FilterBar
          marginBottom={22}
          marginTop={30}
          showSelect={currentUser?.is_admin}
          selectOptions={userList}
          select={{ showSearch: { optionFilterProp: 'label' } }}
          selectHolder={intl.formatMessage({ id: 'models.table.filterByName' })}
          buttonText={intl.formatMessage({ id: 'apikeys.button.create' })}
          handleSearch={handleSearch}
          handleDeleteByBatch={handleDeleteBatch}
          handleClickPrimary={handleAddKey}
          handleSelectChange={handleUserChange}
          handleInputChange={handleNameChange}
          rowSelection={rowSelection}
          widths={{ input: 300 }}
        ></FilterBar>
        <ConfigProvider renderEmpty={renderEmpty}>
          <Table
            columns={columns}
            dataSource={dataSource.dataList}
            rowSelection={rowSelection}
            loading={{
              spinning: dataSource.loading,
              size: 'middle'
            }}
            sortDirections={TABLE_SORT_DIRECTIONS}
            showSorterTooltip={false}
            rowKey="id"
            onChange={handleTableChange}
            pagination={{
              size: 'middle',
              showSizeChanger: true,
              pageSize: queryParams.perPage,
              current: queryParams.page,
              total: dataSource.total,
              hideOnSinglePage: queryParams.perPage === 10,
              onChange: handlePageChange
            }}
          ></Table>
        </ConfigProvider>
      </PageBox>
      <AddAPIKeyModal
        open={openAddModal.open}
        action={openAddModal.action}
        title={openAddModal.title}
        currentData={openAddModal.currentData}
        onCancel={handleModalCancel}
        onOk={handleModalOk}
      ></AddAPIKeyModal>
      {APIKeyIPConfigForm && (
        <APIKeyIPConfigForm
          open={openIPConfigModalStatus.open}
          apiKey={openIPConfigModalStatus.currentData}
          onClose={closeIPConfigModal}
        />
      )}
      <DeleteModal ref={modalRef}></DeleteModal>
    </>
  );
};

export default APIKeys;
