import { DateField } from '@dvn/core/doldurma/src/fields/date';
import { DateDataType } from '@dvn/core/doldurma/src/fields/date/date';
import { SingleChoiceField, SingleChoiceFieldOption } from '@dvn/core/doldurma/src/fields/single-choice';
import { TextField } from '@dvn/core/doldurma/src/fields/text';
import { TableListViewConfig } from '@dvn/core/models/table-list-view-config';
import { AppViewType } from '@dvn/core/models/view-config';
import { Component, h, Host, Listen, Prop, State } from '@stencil/core';
import { damgaSpace } from '../../../../devingen/products/damga/configs/data-configs';
import * as tableListViewDomain from '../../../../devingen/products/damga/configs/view-configs/table-list-view-domain';
import { ID } from '../../../../devingen/products/damga/configs/view-configs/table-list-view-domain';
import { createMentornityApiInstance } from '../../../../mentornity-js-client';
import { MentornityViewConfigViewName } from '../../../../mentornity-js-client/models';
import { mentornityApiEndpoint } from '../../constants/env';
import { getSessionDetails } from '../../util/session';
import { getViewConfigForViewName } from '../common-wrapper-util';
import { en, tr } from './i18n';
import { MembershipApplicationWrapperBridgeApi } from './membership-application-wrapper-bridge-api';
export class MentornityMembershipApplicationListWrapper {
  constructor() {
    this.isProgressing = false;
    this.onRoleChange = (role) => {
      this.formViewConfig = undefined;
      const viewName = role === 'mentors'
        ? MentornityViewConfigViewName.MentorApplicationForm
        : MentornityViewConfigViewName.MenteeApplicationForm;
      const viewConfigWrapper = getViewConfigForViewName(this.viewConfigs, viewName);
      if (viewConfigWrapper) {
        this.formViewConfig = viewConfigWrapper.dvnAppViewConfig;
      }
    };
  }
  /**
   * Called by mentornity-accept-application-button when an application is accepted.
   * Invalidates the table view to refresh its data.
   * @param event
   */
  onAction(event) {
    this.listView.invalidate(event);
  }
  async componentWillLoad() {
    const { context: { organisationId }, headers } = getSessionDetails();
    this.api = new MembershipApplicationWrapperBridgeApi(organisationId, this.language, mentornityApiEndpoint, headers, this.onRoleChange);
    const getViewConfigsResponse = await createMentornityApiInstance(mentornityApiEndpoint, headers)
      .getViewConfigs(organisationId)
      .catch(error => this.error = error);
    if (!getViewConfigsResponse)
      return;
    this.viewConfigs = getViewConfigsResponse.results;
    // mentor application form is shown by default
    const viewConfigWrapper = getViewConfigForViewName(this.viewConfigs, MentornityViewConfigViewName.MentorApplicationForm);
    if (viewConfigWrapper) {
      this.formViewConfig = viewConfigWrapper.dvnAppViewConfig;
    }
  }
  render() {
    const { api, formViewConfig, language } = this;
    const i18n = language === 'tr' ? tr : en;
    return (h(Host, { class: "d-flex flex-grow-1" },
      h("mentornity-root-wrapper", { class: "d-flex pl-3 pr-3" },
        h("dvn-app-view-list-view-table", { ref: (el) => this.listView = el, id: tableListViewDomain.ID, apiData: api, view: viewConfig(i18n, formViewConfig) }))));
  }
  static get is() { return "mentornity-membership-application-list-wrapper"; }
  static get properties() { return {
    "language": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Used to show proper translations, passed by the parent component."
      },
      "attribute": "language",
      "reflect": false
    }
  }; }
  static get states() { return {
    "formViewConfig": {},
    "viewConfigs": {},
    "error": {},
    "isProgressing": {}
  }; }
  static get listeners() { return [{
      "name": "acceptApplication",
      "method": "onAction",
      "target": undefined,
      "capture": false,
      "passive": false
    }]; }
}
const viewConfig = (i18n, formViewConfig) => {
  const columns = {
    'createdAt': {
      width: 150,
    },
    'email': {
      width: 250,
    },
    'firstName': {
      width: 150,
    },
    'lastName': {
      width: 150,
    },
    'actions': {
      width: 120,
    },
  };
  if (formViewConfig) {
    formViewConfig.ui.fields.forEach((fieldRef) => {
      columns[fieldRef.fieldId] = {
        width: 250,
      };
    });
  }
  return TableListViewConfig.decode({
    _id: ID,
    type: AppViewType.ListViewTable,
    base: 'mentornity',
    title: 'Applications',
    space: damgaSpace,
    table: {
      fields: [
        new TextField('firstName', i18n.firstName),
        new TextField('lastName', i18n.lastName),
        new TextField('email', i18n.email),
        ...(formViewConfig ? formViewConfig.table.fields : []),
        new DateField('createdAt', i18n.date).setDataType(DateDataType.Unix).setDateFormat('DD MMM YYYY'),
      ],
    },
    query: {},
    ui: TableListViewConfig.decode({
      main: {
        fields: [
          { fieldDisplay: { id: 'actions' }, componentTag: 'mentornity-accept-application-button' },
          { fieldId: 'createdAt' },
          { fieldId: 'email' },
          { fieldId: 'firstName' },
          { fieldId: 'lastName' },
          ...(formViewConfig ? formViewConfig.ui.fields : []),
        ],
        columns,
      },
      quickSearch: {
        fields: [
          {
            field: new SingleChoiceField('role', 'Role', [
              new SingleChoiceFieldOption('Mentor applications', 'mentors'),
              new SingleChoiceFieldOption('Mentee applications', 'mentees'),
            ]).setValue('mentors'),
          }
        ],
        fieldUIConfigs: [
          {
            fieldId: 'role',
            width: '200px',
          },
        ],
      },
    }),
  });
};
