import { injectNotifier } from '@dvn/alaca/global/notifier';
import { NumberField } from '@dvn/core/doldurma/src/fields/number';
import { TextField } from '@dvn/core/doldurma/src/fields/text';
import { AppViewType, DvnAppViewConfig } from '@dvn/core/models/view-config';
import { Component, h, Host, Prop, State } from '@stencil/core';
import { createMentornityApiInstance } from '../../../../mentornity-js-client';
import { Collection, MentornityViewConfigViewName, ModelReference, ViewConfigWrapper } from '../../../../mentornity-js-client/models';
import { mentornityApiEndpoint } from '../../constants/env';
import { getSessionDetails } from '../../util/session';
import { convertFieldsToFieldReferences } from '../common-wrapper-util';
import { getAvailableMembershipFormFields } from '../mentornity-membership-settings-wrapper/wrapper-util';
import { PreviewFormHandler } from './PreviewFormHandler';
function getViewConfigWrapperForCreation(organisationId, viewName, fields) {
  return {
    dvnAppViewConfig: DvnAppViewConfig.decode({
      type: AppViewType.FormView,
      ui: {
        fields,
      },
    }),
    organisation: new ModelReference(organisationId, Collection.Organisations),
    viewName,
  };
}
const i18n = {
  formFields: {
    firstName: 'First name',
    lastName: 'Last name',
    title: 'Title',
    bio: 'Bio',
    skills: 'Skills',
    pairLimit: 'Pair limit',
  },
  formTitle: 'My info'
};
export class MentornityMembershipInfoSettingsWrapper {
  constructor() {
    this.setViewConfigWrapper = (viewConfigWrapper) => {
      // API doesn't add firstName, lastName and subscriptionLimit to the table fields
      viewConfigWrapper.dvnAppViewConfig.table.fields.push(new TextField('firstName', 'First Name').require(), new TextField('lastName', 'Last Name').require(), new NumberField('subscriptionLimit', i18n.formFields.pairLimit));
      viewConfigWrapper.dvnAppViewConfig.title = i18n.formTitle;
      this.viewConfigWrapper = viewConfigWrapper;
    };
    this.onSelectedFieldsChange = (e) => {
      const selectedFields = e.detail;
      const viewConfigWrapper = ViewConfigWrapper.decode(JSON.parse(JSON.stringify(this.viewConfigWrapper)));
      viewConfigWrapper.dvnAppViewConfig.ui.fields = selectedFields.map(sfid => ({ fieldId: sfid }));
      this.viewConfigWrapper = viewConfigWrapper;
    };
    this.onClickSaveChanges = () => {
      const { dvnAppViewConfig } = this.viewConfigWrapper;
      this.api.updateViewConfig(this.viewConfigWrapper._id, { dvnAppViewConfig })
        .then(() => this.notifier.congratulate('Changes are saved.'))
        .catch(() => this.notifier.alert('Saving changes failed.'));
    };
  }
  async componentWillLoad() {
    this.previewFormHandler = new PreviewFormHandler(() => {
      this.notifier.warn('Action unavailable in preview.', 'Preview Mode');
    });
    const { formTarget, organisationId } = this;
    const { headers } = getSessionDetails();
    this.api = createMentornityApiInstance(mentornityApiEndpoint, headers);
    const config = await this.api.getOrganisationConfig(organisationId)
      .catch(error => this.error = error);
    if (!config)
      return;
    this.organisationConfig = config;
    this.availableFields = getAvailableMembershipFormFields(i18n, formTarget, this.organisationConfig);
    const viewName = formTarget === 'mentor'
      ? MentornityViewConfigViewName.MentorInfoForm
      : MentornityViewConfigViewName.MenteeInfoForm;
    this.api.getViewConfig(organisationId, viewName)
      .then(viewConfigWrapper => {
      this.setViewConfigWrapper(viewConfigWrapper);
    })
      .catch(error => {
      if (error.status === 404) {
        // create the view config
        const fieldRefs = convertFieldsToFieldReferences(this.availableFields);
        const viewConfigWrapper = getViewConfigWrapperForCreation(organisationId, viewName, fieldRefs);
        this.api.createViewConfig(viewConfigWrapper)
          .then(() => {
          // fetch the created config because API generates table.fields on the fly while getting it
          this.api.getViewConfig(organisationId, viewName)
            .then(viewConfigWrapper => {
            this.setViewConfigWrapper(viewConfigWrapper);
          }).catch(error => this.error = error);
        })
          .catch(error => this.error = error);
      }
      else {
        this.error = error;
      }
    });
  }
  render() {
    const { viewConfigWrapper, availableFields, organisationConfig, } = this;
    if (!organisationConfig || !viewConfigWrapper) {
      return (h("div", { class: "d-flex justify-content-center pt-3" },
        h("dvn-progress", { indefinite: true })));
    }
    const view = Object.assign(Object.assign({}, viewConfigWrapper.dvnAppViewConfig), { handler: this.previewFormHandler });
    const selectedFields = view.ui.fields.map(field => field.fieldId);
    const options = availableFields.map(field => ({
      label: field.title,
      value: field.id,
      disabled: ['firstName', 'lastName'].includes(field.id)
    }));
    return (h(Host, null,
      h("mentornity-root-wrapper", null,
        h("div", { class: "columns-container d-flex" },
          h("div", { class: "controls-container d-flex flex-column" },
            h("div", { class: "form-controls-container" },
              h("div", { class: "d-flex flex-column p-3" },
                h("dvn-alert", { message: "The preview on the right will be updated when there is a change on the controls." }),
                h("dvn-checkbox-group", { options: options, value: selectedFields, onChange: this.onSelectedFieldsChange }))),
            h("div", { class: "controls-footer p-3" },
              h("dvn-button", { leaned: true, tint: "primary", onClick: this.onClickSaveChanges }, "Save Changes"))),
          h("div", { class: "preview-container" },
            h("dvn-card", null,
              h("dvn-app-view-form-view", { view: view })))))));
  }
  static get is() { return "mentornity-membership-info-settings-wrapper"; }
  static get originalStyleUrls() { return {
    "$": ["mentornity-membership-info-settings-wrapper.scss"]
  }; }
  static get styleUrls() { return {
    "$": ["mentornity-membership-info-settings-wrapper.css"]
  }; }
  static get properties() { return {
    "language": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "language",
      "reflect": false
    },
    "organisationId": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "organisation-id",
      "reflect": false
    },
    "formTarget": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "'mentee' | 'mentor'",
        "resolved": "\"mentee\" | \"mentor\"",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "form-target",
      "reflect": false
    },
    "organisationDomain": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "organisation-domain",
      "reflect": false
    },
    "wlDomain": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "wl-domain",
      "reflect": false
    },
    "notifier": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "Notifier",
        "resolved": "Notifier",
        "references": {
          "Notifier": {
            "location": "import",
            "path": "@dvn/alaca/global/notifier/models"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    }
  }; }
  static get states() { return {
    "viewConfigWrapper": {},
    "organisationConfig": {},
    "availableFields": {},
    "error": {}
  }; }
}
injectNotifier(MentornityMembershipInfoSettingsWrapper);
