import React from 'react';
import { Button, Popconfirm, Space } from 'antd';
import { agentAttrs } from './agentPanel/agentAttributes';
import { useAgent } from './agentPanel/AgentContext';
import { ExportButton } from '@refinedev/antd';
import { RowAction } from '../hooks/types';

export interface BulkActionsRenderContext {
  /** Number of selected items */
  selectedCount: number;
  /** Selected row keys */
  selectedRowKeys: React.Key[];
  /** Handler for update action */
  onUpdate: (values: any) => Promise<void>;
  /** Handler for delete action */
  onDelete: () => Promise<void>;
  /** Handler for export action */
  onExport?: () => void;
  /** Loading states */
  updateLoading: boolean;
  deleteLoading: boolean;
  exportLoading: boolean;
  /** Translation function */
  t: (key: string, defaultValue?: string) => string;
  /** Resource name */
  resourceName: string;
}

export interface BulkActionsProps {
  /** Array of selected row keys */
  selectedRowKeys: React.Key[];
  /** Row selection actions from config */
  actions?: RowAction[];
  /** Handler for status change actions */
  onUpdateSelected?: (values: any) => Promise<void>;
  /** Handler for delete action */
  onDeleteSelected?: () => Promise<void>;
  /** Handler for export action */
  onExportSelected?: () => void;
  /** Loading states */
  updateLoading?: boolean;
  deleteLoading?: boolean;
  exportLoading?: boolean;
  /** Translation function */
  t?: (key: string, defaultValue?: string) => string;
  /** Resource name for i18n keys */
  resourceName?: string;
  /** Show delete button */
  showDelete?: boolean;
  /** Show export button */
  showExport?: boolean;
  /** Custom children - if provided, replaces entire default UI */
  children?:
    | React.ReactNode
    | ((context: BulkActionsRenderContext) => React.ReactNode);

  // Render props for fine-grained customization
  /** Custom render for update buttons */
  renderUpdateButton?: (
    action: RowAction,
    onClick: () => void,
    loading: boolean,
  ) => React.ReactNode;
  /** Custom render for delete button */
  renderDeleteButton?: (
    onClick: () => void,
    loading: boolean,
  ) => React.ReactNode;
  /** Custom render for export button */
  renderExportButton?: (
    onClick: () => void,
    loading: boolean,
  ) => React.ReactNode;
  /** Custom render for selection count */
  renderSelectionCount?: (count: number) => React.ReactNode;
  /** Additional actions to render after default actions */
  extraActions?: React.ReactNode;
}

/**
 * Bulk actions component for selected rows
 *
 * @example
 * // Basic usage
 * <BulkActions
 *   selectedRowKeys={selectedRowKeys}
 *   onUpdateSelected={updateSelectedItems}
 *   onDeleteSelected={deleteSelectedItems}
 *   t={t}
 *   resourceName="audit"
 * />
 *
 * @example
 * // With custom render props
 * <BulkActions
 *   {...props}
 *   renderDeleteButton={(onClick, loading) => (
 *     <MyCustomDeleteButton onClick={onClick} loading={loading} />
 *   )}
 *   renderSelectionCount={(count) => (
 *     <Badge count={count} />
 *   )}
 * />
 *
 * @example
 * // Completely custom UI using children
 * <BulkActions
 *   selectedRowKeys={selectedRowKeys}
 *   onUpdateSelected={updateSelectedItems}
 *   onDeleteSelected={deleteSelectedItems}
 * >
 *   {({ selectedCount, onDelete, updateLoading }) => (
 *     <MyCustomBulkActionsUI
 *       count={selectedCount}
 *       onDelete={onDelete}
 *       loading={updateLoading}
 *     />
 *   )}
 * </BulkActions>
 */
export const BulkActions: React.FC<BulkActionsProps> = ({
  selectedRowKeys,
  actions = [],
  onUpdateSelected,
  onDeleteSelected,
  onExportSelected,
  updateLoading = false,
  deleteLoading = false,
  exportLoading = false,
  t = (key, defaultValue) => defaultValue || key,
  resourceName = '',
  showDelete = true,
  showExport = true,
  children,
  renderUpdateButton,
  renderDeleteButton,
  renderExportButton,
  renderSelectionCount,
  extraActions,
}) => {
  const agent = useAgent();
  const inspecting = agent?.inspecting ?? false;

  if (selectedRowKeys.length === 0 && !inspecting) {
    return null;
  }

  // Inspect-mode preview: render a placeholder when no rows are selected
  if (selectedRowKeys.length === 0 && inspecting) {
    return (
      <Space
        {...agentAttrs({ type: 'list-bulk-actions', resource: resourceName })}
        style={{
          opacity: 0.6,
          border: '1px dashed #1890ff',
          padding: '4px 8px',
          borderRadius: 4,
        }}
      >
        <Button disabled>导出</Button>
        <Button danger disabled>
          删除
        </Button>
        <span style={{ marginLeft: 8 }}>批量操作（检查模式预览）</span>
      </Space>
    );
  }

  const context: BulkActionsRenderContext = {
    selectedCount: selectedRowKeys.length,
    selectedRowKeys,
    onUpdate: onUpdateSelected || (async () => {}),
    onDelete: onDeleteSelected || (async () => {}),
    onExport: onExportSelected,
    updateLoading,
    deleteLoading,
    exportLoading,
    t,
    resourceName,
  };

  // If children is a function, call it with context
  if (typeof children === 'function') {
    return <>{children(context)}</>;
  }

  // If children is provided as ReactNode, render it directly
  if (children) {
    return <>{children}</>;
  }

  // Default rendering
  const statusActions = actions.filter(
    (action) => action.action === 'CHANGE_STATUS',
  );

  const defaultUpdateButton = (
    action: RowAction,
    onClick: () => void,
    loading: boolean,
  ) => (
    <Popconfirm
      key={action.desc}
      placement="top"
      onConfirm={onClick}
      title={t('buttons.confirm', 'Are you sure?')}
      okText={t('buttons.sure', 'Yes')}
      cancelText={t('buttons.cancel', 'No')}
    >
      <Button type="default" loading={loading}>
        {t(`resources.${resourceName}.actions.${action.desc}`, action.desc)}
      </Button>
    </Popconfirm>
  );

  const defaultDeleteButton = (onClick: () => void, loading: boolean) => (
    <Popconfirm
      placement="top"
      onConfirm={onClick}
      title={t('buttons.confirm', 'Are you sure?')}
      okText={t('buttons.sure', 'Yes')}
      cancelText={t('buttons.cancel', 'No')}
    >
      <Button danger loading={loading}>
        {t('buttons.delete', 'Delete')}
      </Button>
    </Popconfirm>
  );

  const defaultExportButton = (onClick: () => void, loading: boolean) => (
    <ExportButton onClick={onClick} loading={loading} icon={<></>} />
  );

  const defaultSelectionCount = (count: number) => (
    <span style={{ marginLeft: 8 }}>
      {t('table.selected', 'Selected') +
        ' ' +
        count +
        ' ' +
        t('table.items', 'items')}
    </span>
  );

  return (
    <Space
      {...agentAttrs({ type: 'list-bulk-actions', resource: resourceName })}
    >
      {statusActions.map((action) =>
        renderUpdateButton
          ? renderUpdateButton(
              action,
              () => onUpdateSelected?.(action.values),
              updateLoading,
            )
          : defaultUpdateButton(
              action,
              () => onUpdateSelected?.(action.values),
              updateLoading,
            ),
      )}

      {/* Export selected */}
      {showExport &&
        onExportSelected &&
        (renderExportButton
          ? renderExportButton(onExportSelected, exportLoading)
          : defaultExportButton(onExportSelected, exportLoading))}

      {/* Delete selected */}
      {showDelete &&
        onDeleteSelected &&
        (renderDeleteButton
          ? renderDeleteButton(onDeleteSelected, deleteLoading)
          : defaultDeleteButton(onDeleteSelected, deleteLoading))}

      {/* Extra actions */}
      {extraActions}

      {/* Selection count */}
      {renderSelectionCount
        ? renderSelectionCount(selectedRowKeys.length)
        : defaultSelectionCount(selectedRowKeys.length)}
    </Space>
  );
};

export default BulkActions;
