import React, { CSSProperties } from 'react';
import { CustomFieldType, CustomField, ExtendedFields } from '@wix/bex-core';
import { Column } from '../model';
import { ExtendedColumn } from '../components/ExtendedColumn/ExtendedColumn';
import { DataTableColumnAlign } from '@wix/design-system/dist/types/Table/DataTable';
import { toFieldType } from '../utils/fieldTypePrefixIcons';

const ExtendedColumnsConfig: Record<
  CustomFieldType,
  { style?: CSSProperties; width?: string; align?: DataTableColumnAlign }
> = {
  shortText: {
    width: '150px',
    align: 'start',
  },
  dateTime: {
    width: '200px',
    align: 'center',
  },
  date: {
    width: '150px',
    align: 'center',
  },
  decimal: {
    width: '100px',
    align: 'center',
  },
  integer: {
    width: '100px',
    align: 'center',
  },
  checkbox: {
    width: '100px',
    align: 'center',
  },
  longText: {
    width: '250px',
    align: 'start',
  },
  url: {
    width: '250px',
    align: 'start',
  },
  dropdown: {
    width: '150px',
    align: 'start',
  },
  files: {
    width: '180px',
    align: 'start',
  },
  multiSelect: {
    width: '150px',
    align: 'start',
  },
};

export const prefixFieldWithNamespace = (id: string, namespace: string) =>
  `extendedFields.namespaces.${namespace}.${id}`;

export const prefixFieldWithUserFieldsNamespace = (id: string) =>
  prefixFieldWithNamespace(id, '_user_fields');

export function simplifyExtendedColumns<T>({
  fields,
  toExtendedFields,
  defaultHidden,
  getSchemaField,
}: {
  fields: CustomField[];
  toExtendedFields?: (item: T) => ExtendedFields | undefined | null;
  defaultHidden?: boolean;
  getSchemaField?: (
    namespace: string,
    fieldId: string,
  ) => Record<string, any> | undefined;
}): Column[] {
  return fields.map((field) => {
    const type = field.type;

    const id = prefixFieldWithNamespace(field.id, field.namespace);
    const schemaField = getSchemaField?.(field.namespace, field.id);
    const isPii = field.isPii ?? Boolean(schemaField?.['x-wix-pii']?.enabled);
    return {
      dataExtension: field,
      id,
      dataHook: id,
      name: field.label || field.id,
      title: field.label || field.id,
      hideable: true,
      sortable: field.filterable,
      defaultHidden: defaultHidden || field.owner !== 'user',
      fieldType: type ? toFieldType(type) : undefined,
      isPii,
      align: type ? ExtendedColumnsConfig[type].align : undefined,
      width: type ? ExtendedColumnsConfig[type].width : undefined,
      style: type ? ExtendedColumnsConfig[type].style : undefined,
      render: (row) => {
        const value =
          toExtendedFields?.(row)?.namespaces?.[field.namespace]?.[field.id];
        return <ExtendedColumn type={type} value={value} />;
      },
    };
  });
}
