import React, { useMemo, type ReactNode } from 'react';
import type { Column } from '../../model';
import type { FieldActions } from '../../types/SchemaConfig';
import {
  buildFieldActionGroups,
  HeaderActionsPopover,
  type FieldActionColumn,
  type FieldActionHandlers,
  type FieldActionPermissions,
} from '../FieldActions';

const SIDE_PANEL_ACTION_GROUPS: Parameters<
  typeof buildFieldActionGroups
>[0]['groups'] = [
  ['editField'],
  ['makePrimary', 'duplicateField', 'duplicateFieldWithContent'],
  ['delete'],
];

function toFieldActionColumn(col: Column): FieldActionColumn & { id: string } {
  const isText =
    col.fieldType === 'SHORT_TEXT' || col.fieldType === 'LONG_TEXT';
  return {
    id: col.id,
    isPrimary: col.isPrimary,
    isSystem: col.isSystem,
    cellType: isText ? 'text' : col.fieldType,
  };
}

export function useSidePanelFieldActions(
  columns: Column[],
  fieldActions?: FieldActions,
  permissions?: FieldActionPermissions,
): Record<string, ReactNode> {
  return useMemo(() => {
    const handlers: FieldActionHandlers = {
      editField: fieldActions?.editField
        ? (id) => fieldActions.editField!(id, {})
        : undefined,
      makePrimary: (id) => fieldActions?.makePrimary?.(id),
      duplicateField: fieldActions?.duplicateField,
      duplicateFieldWithContent: fieldActions?.duplicateField,
      delete: fieldActions?.deleteField,
    };

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

    for (const col of columns) {
      const groups = buildFieldActionGroups({
        column: toFieldActionColumn(col),
        permissions,
        handlers,
        groups: SIDE_PANEL_ACTION_GROUPS,
      });

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

    return result;
  }, [columns, fieldActions, permissions]);
}
