import React from 'react';
import { observer } from 'mobx-react-lite';
import type { Field, FiltersMap } from '@wix/bex-core';
import type { EditableTableState } from '../../state/EditableTable';
import type { EditableColumn } from '../../state/EditableTable/types';
import {
  buildFieldActionGroups,
  type FieldActionHandlers,
  type FieldActionKey,
} from '../FieldActions';
import { HeaderActionsPopover } from './HeaderActionsPopover';

// Field-management (from the source) first, then the table-intrinsic groups,
// then the destructive action. Only keys with a handler render, so each source
// shows just its own actions (CMS: make-primary / duplicate / delete;
// DataExtension: archive).
const HEADER_ACTION_GROUPS: FieldActionKey[][] = [
  ['editField'],
  ['makePrimary', 'hideColumn', 'duplicateField', 'duplicateFieldWithContent'],
  ['sortAscending', 'sortDescending', 'filter'],
  ['archive', 'delete'],
];

const HEADER_LOCATION = 'EditableTable header action cell';

interface HeaderFieldActionsProps<T, F extends FiltersMap> {
  state: EditableTableState<T, F>;
  column: EditableColumn<T>;
}

function _HeaderFieldActions<T, F extends FiltersMap>({
  state,
  column,
}: HeaderFieldActionsProps<T, F>) {
  const { toolbar } = state;
  const { customColumnsState, panels, toolbarFiltersState } = toolbar;
  const source = toolbar.collectionFieldsSource;

  // Source-backed columns (their id maps to a source field) get the source's
  // field-management; vertical-brought or consumer columns get only the
  // table-intrinsic actions below.
  const field: Field | undefined = source?.fieldsSource.fields.find(
    (f) => source.fieldsSource.columnIdForField(f) === column.id,
  );
  const sourceConfig =
    field && source?.fieldActionHandlers
      ? source.fieldActionHandlers({
          fieldId: field.id,
          origin: 'external',
          location: HEADER_LOCATION,
        })
      : null;

  const handlers: FieldActionHandlers = { ...sourceConfig?.handlers };

  if (column.hideable !== false && customColumnsState) {
    const toolbarColumn = toolbar.columns.find((c) => c.id === column.id);
    if (toolbarColumn) {
      handlers.hideColumn = () =>
        customColumnsState.onColumnCheckboxToggle(toolbarColumn);
    }
  }

  if (column.sortable) {
    handlers.sortAscending = (id) => state.sort(id, { forceDirection: 'asc' });
    handlers.sortDescending = (id) =>
      state.sort(id, { forceDirection: 'desc' });
  }

  const hasFilter =
    toolbarFiltersState &&
    state.collection.query.customFilters[column.id] != null;
  if (hasFilter) {
    handlers.filter = () => panels.openSidePanel('filters');
  }

  const groups = buildFieldActionGroups({
    columnId: column.id,
    handlers,
    loading: sourceConfig?.loading,
    disabledTooltips: sourceConfig?.disabledTooltips,
    groups: HEADER_ACTION_GROUPS,
    translate: toolbar.container.translate,
    bi: source
      ? {
          reportBi: toolbar.reportBi,
          location: HEADER_LOCATION,
          listSize: source.fieldsSource.manageableFields.length,
        }
      : undefined,
  });

  if (groups.length === 0) {
    return null;
  }

  return (
    <HeaderActionsPopover
      actions={groups}
      dataHook={`header-actions-${column.id}`}
    />
  );
}

export const HeaderFieldActions = observer(_HeaderFieldActions);
