import React from 'react';
import { STRING_OPERATORS } from '@wix/bex-core';
import type { DataExtensionState } from '@wix/bex-core';
import type { FieldsSourceRendering } from '../../state/CollectionFieldsSourceState';
import type { Column } from '../../model';
import type { ToolbarCollectionState } from '../../state';
import type { DataExtensionType, DataExtensionProps } from './DataExtension';
import { toFieldType } from '../../utils/fieldTypePrefixIcons';
import { FileCardList } from '../FileCard/FileCardList';
import {
  createDataExtensionFieldActionsMenu,
  dataExtensionFieldActionHandlers,
} from './dataExtensionFieldActions';
import { FieldManagementModals } from '../CustomFieldsPanel/FieldManagementModals';
import { CustomColumnsFull } from '../CustomColumns/CustomColumnsFull';
import { CollectionToolbarFilters } from '../CollectionToolbarFilters';

/**
 * Builds the DataExtension-specific config the spine needs, shaped as a
 * FieldsSourceRendering. The spine builds the field-management panel from this;
 * pairs with the DataExtension FieldsSource (the data).
 */
export const dataExtensionRendering = ({
  dataExtension,
  toolbar,
  DataExtension,
  props,
}: {
  dataExtension: DataExtensionState;
  toolbar: ToolbarCollectionState<any, any>;
  DataExtension: DataExtensionType;
  props?: DataExtensionProps;
}): FieldsSourceRendering => {
  return {
    columnOverrides: (field, { firstBuild }): Partial<Column> => {
      const cf = dataExtension.availableCustomFields.find(
        (f) => f.id === field.id,
      );
      const overrides: Partial<Column> = {
        // Derive the icon from the source type, not the neutral type. The neutral
        // type collapses distinct source types (e.g. dropdown into short text),
        // which would change the icon.
        fieldType: cf?.type ? toFieldType(cf.type) : undefined,
        dataExtension: cf,
        defaultHidden: firstBuild || cf?.owner !== 'user',
      };
      if (field.type === 'DOCUMENT') {
        overrides.render = (row) => {
          const value =
            toolbar.collection.toExtendedFields?.(row)?.namespaces?.[
              cf?.namespace ?? ''
            ]?.[field.id];
          if (!value) {
            return null;
          }
          const files = Array.isArray(value) ? value : [value];
          return <FileCardList files={files} />;
        };
      }
      return overrides;
    },
    filterConfig: {
      textOperators: STRING_OPERATORS,
      numberIsDecimal: (field) =>
        dataExtension.availableCustomFields.find((f) => f.id === field.id)
          ?.type === 'decimal',
      // Derive the icon from the source type, not the neutral type (which would
      // collapse distinct source types) — matching the column icon.
      iconType: (field) => {
        const cf = dataExtension.availableCustomFields.find(
          (f) => f.id === field.id,
        );
        return cf?.type ? toFieldType(cf.type) : toFieldType(field.type);
      },
    },
    createFieldActionsMenu: createDataExtensionFieldActionsMenu(dataExtension),
    createFieldActionHandlers: (panel) =>
      dataExtensionFieldActionHandlers(dataExtension, panel),
    featuredPageActions: [DataExtension.manageCustomFieldsPageAction],
    props,
    components: {
      FieldManagementModals,
      CustomColumns: CustomColumnsFull,
      CollectionToolbarFilters,
    },
  };
};
