/**
 * AgendaJob List Page
 *
 * Generated using simplified pattern with @gadmin2n/react-common hooks and components.
 *
 * Flexibility Levels:
 * 1. Basic usage - Use components with defaults (this file)
 * 2. Render props - Customize specific buttons/elements
 * 3. Children function - Complete UI control
 * 4. Core hooks - No UI assumptions, full control
 *
 * See: examples/ListPageExamples.tsx for all patterns
 */
import React, { useMemo } from 'react';
import { Table } from 'antd';
import { List, useTable, useImport } from '@refinedev/antd';
import {
  HttpError,
  IResourceComponentsProps,
  parseTableParams,
  useExport,
  useTranslate,
  useApiUrl,
} from '@refinedev/core';
import { useLocation, useNavigate } from 'react-router-dom';
import {
  getColumns,
  ModelType,
  produceModel,
  tableSearchBar,
} from '@gadmin2n/react-common';

// Generated imports
import { modelsEnum, modelsMap } from 'generated/models.index';
import {
  agendaJobTableConfig as tableConfig,
  agendaJobTablePrismaSelect as prismaSelect,
} from 'generated/props/agendaJob/config';
import { agendaJobModel, useRelation } from 'generated/props/agendaJob/model';
import type { AgendaJob } from 'generated/types/prisma.types';

// Local imports
import { BulkActions, ListPageHeader, RowActions, SearchBar } from 'components';
import { getRowActionsColumnProps } from 'components/agentPanel';
import { requestHeaders } from 'helpers/login';
import { useBatchOperations } from 'hooks';
import {
  createSearchFormOnFinish,
  getSearchFormInitialValues,
  getTableColumnV2,
  TableColumnContext,
} from 'helpers';

const { placeholder: searchPlaceholder, getSearchFilters } = tableSearchBar(
  tableConfig['toolbar']['searchBar'],
  agendaJobModel,
);

// https://refine.dev/docs/api-reference/antd/hooks/table/useTable/
export const AgendaJobList: React.FC<IResourceComponentsProps> = () => {
  const resourceName = 'agendaJob';
  const t = useTranslate();
  const apiUrl = useApiUrl();
  const navigate = useNavigate();
  const { search } = useLocation();
  const { parsedSorter, parsedFilters } = parseTableParams(search);

  // Relations
  const relationSelectProps = useRelation(modelsMap);

  // Model with customizations
  const [columns, model] = useMemo(() => {
    const model: ModelType = produceModel(agendaJobModel, {
      // Custom column renderers can be added here
      // cron: { render: (value) => humanizeCronInChinese(value) },
    });

    const columns = getColumns('AgendaJob', tableConfig.fields, {
      ...modelsMap,
      AgendaJob: { model, meta: modelsMap['AgendaJob'].meta },
    });

    return [columns, model] as const;
  }, []);

  // Table hook
  const {
    tableProps,
    sorters: sorter,
    setCurrent,
    setFilters,
    filters,
    tableQueryResult,
    searchFormProps,
  } = useTable<AgendaJob, HttpError>({
    meta: {
      transformQFn: getSearchFilters,
      select: prismaSelect,
      model: agendaJobModel,
    },
    filters: { initial: parsedFilters, defaultBehavior: 'merge' },
    sorters: { initial: parsedSorter },
  });

  // initialValues: 从 URL 的 parsedFilters 中恢复 q（搜索关键词）和 createdAt（日期范围）
  // onFinish: 将表单值转换为 CrudFilters 并更新筛选条件
  // 有 createdAt 字段的模型（默认）
  searchFormProps.initialValues = getSearchFormInitialValues(parsedFilters);
  searchFormProps.onFinish = createSearchFormOnFinish(setCurrent, setFilters);

  // 没有 createdAt 字段的模型
  // searchFormProps.initialValues = getSearchFormInitialValues(parsedFilters, { dateField: null });
  // searchFormProps.onFinish = createSearchFormOnFinish(setCurrent, setFilters, { dateField: null });

  // 使用其他日期字段（如 updatedAt）
  // searchFormProps.initialValues = getSearchFormInitialValues(parsedFilters, { dateField: 'updatedAt' });
  // searchFormProps.onFinish = createSearchFormOnFinish(setCurrent, setFilters, { dateField: 'updatedAt' });

  // Batch operations (selection, update, delete)
  const batchOps = useBatchOperations({
    resourceName,
    apiUrl,
    requestHeaders,
    onSuccess: () => tableQueryResult.refetch(),
    t,
  });

  // Export all
  const { triggerExport, isLoading: exportLoading } = useExport<AgendaJob>({
    maxItemCount: 200,
    pageSize: 100,
  });

  // Export selected
  const {
    triggerExport: triggerExportSelected,
    isLoading: exportSelectedLoading,
  } = useExport<AgendaJob>({
    pageSize: 100,
    meta: { where: { id: { in: batchOps.selectedRowKeys.map(Number) } } },
  });

  // Import
  const importProps = useImport<AgendaJob>({
    mapData: (item: any) => ({
      ...item,
    }),
    batchSize: 1,
  });

  // Context for table columns
  const columnContext: TableColumnContext = {
    resourceName,
    t,
    model,
    modelsEnum,
    modelsMap,
    tableConfig,
    sorter,
    filters,
    relationSelectProps,
  };

  return (
    <List
      headerProps={{
        onBack: () => navigate('/admin/agenda-jobs'),
        subTitle: (
          <BulkActions
            selectedRowKeys={batchOps.selectedRowKeys}
            actions={tableConfig.rowSelection.actions}
            onUpdateSelected={batchOps.updateSelectedItems}
            onDeleteSelected={batchOps.deleteSelectedItems}
            onExportSelected={triggerExportSelected}
            updateLoading={batchOps.updateManyIsLoading}
            deleteLoading={batchOps.deleteManyIsLoading}
            exportLoading={exportSelectedLoading}
            t={t}
            resourceName={resourceName}
            showDelete={false}
            // Render props examples (uncomment to customize):
            // renderDeleteButton={(onClick, loading) => <Button danger onClick={onClick} loading={loading}>Delete</Button>}
            // renderSelectionCount={(count) => <Badge count={count}><Tag>Selected</Tag></Badge>}
            // extraActions={<Button>Custom Action</Button>}
          />
        ),
        extra: (
          <ListPageHeader
            importProps={importProps}
            onExport={triggerExport}
            exportLoading={exportLoading}
            resourceName={resourceName}
            showCreate={false}
            showImport={false}
          />
        ),
      }}
    >
      {/* Search Bar */}
      <SearchBar
        formProps={searchFormProps}
        t={t}
        resourceName={resourceName}
        searchPlaceholder={searchPlaceholder}
        // Render props examples (uncomment to customize):
        // renderKeywordInput={(field, defaultInput) => <Input.Search placeholder={field.placeholder} />}
        // renderSubmitButton={(defaultButton) => <Space>{defaultButton}<Button>Reset</Button></Space>}
        // extraActions={<Button type="link">Advanced</Button>}
      />

      {/* Data Table */}
      <Table {...tableProps} rowKey="id" rowSelection={batchOps.rowSelection}>
        {columns.map((col) =>
          getTableColumnV2({ col, context: columnContext }),
        )}

        {/* Actions Column */}
        <Table.Column<AgendaJob>
          title={t('table.actions')}
          dataIndex="actions"
          {...getRowActionsColumnProps(resourceName)}
          render={(_, record) => (
            <RowActions
              record={record}
              actions={tableConfig.rowActions.actions}
              onUpdate={batchOps.updateOne}
              updateLoading={batchOps.updateManyIsLoading}
              t={t}
              resourceName={resourceName}
              showEdit={false}
              showDelete={false}
              showClone={false}
              // Render props examples (uncomment to customize):
              // showClone={false}
              // showDelete={false}
              // renderEditButton={(id) => <Button type="link" size="small">Quick Edit</Button>}
              // renderDeleteButton={(id) => <Popconfirm title="Sure?"><Button danger size="small">Remove</Button></Popconfirm>}
              // extraPrimaryActions={<Button type="text" size="small">Quick View</Button>}
            />
          )}
        />
      </Table>
    </List>
  );
};

export default AgendaJobList;
