import React, { useMemo, type ReactNode } from 'react';
import type { 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';

const FIELD_ACTION_GROUPS: FieldActionKey[][] = [
  ['editField'],
  ['makePrimary', 'hideColumn', 'duplicateField', 'duplicateFieldWithContent'],
  ['sortAscending', 'sortDescending', 'filter'],
  ['delete'],
];

export function useHeaderActions<T, F extends FiltersMap>(
  state: EditableTableState<T, F>,
  columns: EditableColumn<T>[],
  disabled?: boolean,
): Record<string, ReactNode> {
  const { toolbar } = state;
  const { customColumnsState, panels, toolbarFiltersState } = toolbar;
  const { handlers: fieldActionHandlers, permissions: fieldActionPermissions } =
    state.fieldActions;
  const { isMakingPrimary, isDuplicating, isDuplicatingWithContent } =
    state.fieldActions;

  return useMemo(() => {
    if (disabled) {
      return {};
    }

    const result: Record<string, ReactNode> = {};

    const loading: Partial<Record<FieldActionKey, boolean>> = {
      makePrimary: isMakingPrimary,
      duplicateField: isDuplicating,
      duplicateFieldWithContent: isDuplicatingWithContent,
    };

    for (const col of columns) {
      const handlers: FieldActionHandlers = {};

      if (fieldActionHandlers?.makePrimary) {
        handlers.makePrimary = (id) => state.fieldActions.makePrimary(id);
      }

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

      if (fieldActionHandlers?.duplicateField) {
        handlers.duplicateField = (id) => state.fieldActions.duplicate(id);
      }

      if (fieldActionHandlers?.duplicateFieldWithContent) {
        handlers.duplicateFieldWithContent = (id) =>
          state.fieldActions.duplicateWithContent(id);
      }

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

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

      if (fieldActionHandlers?.deleteField) {
        handlers.delete = (id) => state.fieldActions.confirmDelete(id);
      }

      const groups = buildFieldActionGroups({
        column: col,
        permissions: fieldActionPermissions,
        handlers,
        loading,
        groups: FIELD_ACTION_GROUPS,
      });

      if (groups.length > 0) {
        result[col.id] = (
          <HeaderActionsPopover
            actions={groups}
            dataHook={`header-actions-${col.id}`}
          />
        );
      }
    }

    return result;
  }, [
    state,
    columns,
    toolbar,
    customColumnsState,
    panels,
    toolbarFiltersState,
    disabled,
    fieldActionHandlers,
    fieldActionPermissions,
    isDuplicating,
    isDuplicatingWithContent,
    isMakingPrimary,
  ]);
}
