import { injectNotifier } from '@dvn/alaca/global/notifier';
import { SozlukApi } from '@dvn/sozluk/api';
import { Component, h, Host, Prop, State } from '@stencil/core';
import { createMentornityApiInstance } from '../../../../mentornity-js-client';
import { FormStatus } from '../../../../mentornity-js-client/models';
import { convertMentornityFieldToDevingenField } from '../../api/mentorinty-bridge-api';
import { mentornityApiEndpoint } from '../../constants/env';
import { getSessionDetails } from '../../util/session';
import { sozlukEntries } from '../sozluk-entries';
import { mentornityMembershipApplicationSettingsI18nDefault, MentornityMembershipApplicationSettingsI18nKey } from './i18n';
// removes the HTML entities like &nbsp; from the input
const htmlDecode = (input) => new DOMParser().parseFromString(input, 'text/html').documentElement.textContent;
function getFormDataForCreation(organisationId, formTarget) {
  return {
    title: 'Application Form',
    description: 'Application form for new members.',
    target: formTarget,
    type: 'application',
    form: {
      'fields': [],
      'version': 0.1
    },
    organisation: {
      '_id': organisationId,
      '_class': 'organisations',
      '_type': 'reference'
    },
    status: FormStatus.Unpublished,
  };
}
export class MentornityMembershipApplicationSettingsWrapper {
  constructor() {
    this.step = 'description';
    this.editorValue = [
      {
        type: 'h3',
        id: 'form-title',
        value: {
          placeholder: 'Form title',
          text: '',
        },
      },
      {
        type: 'text',
        id: 'form-content',
        value: {
          placeholder: 'Form description',
          text: '',
        },
      },
    ];
    this.setDictionaryLanguage = async () => {
      const apiSozluk = new SozlukApi().setLanguage(this.language).setContents(sozlukEntries);
      this.strings = await apiSozluk.getContent(MentornityMembershipApplicationSettingsI18nKey, mentornityMembershipApplicationSettingsI18nDefault);
    };
    this.setApplicationForm = (form) => {
      this.applicationForm = form;
      const fieldIdsToUse = {};
      (this.targetFields || []).forEach(usableField => {
        fieldIdsToUse[usableField.id] = true;
      });
      this.applicationForm.form.fields = (this.applicationForm.form.fields || []).filter(field => fieldIdsToUse[field.id]);
      // @ts-ignore
      this.applicationForm.description = new showdown.Converter().makeHtml(form.description);
      const editorValue = JSON.parse(JSON.stringify(this.editorValue));
      editorValue[0].value.text = this.applicationForm.title;
      editorValue[1].value.text = this.applicationForm.description;
      this.editorValue = editorValue;
    };
    this.onSelectedFieldsChange = (e) => {
      const selectedFields = e.detail.filter(f => !['email', 'firstName', 'lastName'].includes(f));
      const applicationForm = JSON.parse(JSON.stringify(this.applicationForm));
      applicationForm.form.fields = selectedFields.map(sfid => this.availableFields.find(af => af.id === sfid));
      this.applicationForm = applicationForm;
    };
    this.getApplicationLink = () => {
      const { organisationDomain, wlDomain } = this;
      const domain = wlDomain || 'mentornity.com';
      const rootUrl = `https://${domain}/${organisationDomain}/`;
      return this.formTarget === 'mentee' ? `${rootUrl}/mentees/application` : `${rootUrl}/mentors/application`;
    };
    this.onClickSaveChanges = () => {
      const { status, form: { fields: applicationFormFields }, title, description } = this.applicationForm;
      const fields = applicationFormFields.map(f => ({ id: f.id }));
      const data = { form: { fields }, status, title, description };
      this.api.update('forms', this.applicationForm._id, data)
        .then(() => this.notifier.congratulate('Changes are saved.'))
        .catch(() => this.notifier.alert('Saving changes failed.'));
    };
  }
  async componentWillLoad() {
    const { formTarget, organisationId } = this;
    const { headers } = getSessionDetails();
    this.api = createMentornityApiInstance(mentornityApiEndpoint, headers);
    // setup strings
    this.setDictionaryLanguage();
    const config = await this.api.getOrganisationConfig(organisationId)
      .catch(error => this.error = error);
    if (!config)
      return;
    this.organisationConfig = config;
    this.availableFields = config.metadatas[formTarget];
    this.targetFields = config.metadatas[formTarget].map(convertMentornityFieldToDevingenField);
    const collection = formTarget === 'mentor' ? 'mentors' : 'mentees';
    this.api.getMembershipApplicationForm(organisationId, collection)
      .then(form => this.setApplicationForm(form))
      .catch(error => {
      if (error.status === 404) {
        const formData = getFormDataForCreation(organisationId, formTarget);
        this.api.createForm(formData)
          .then(createFormResponse => this.setApplicationForm(Object.assign(Object.assign({}, formData), createFormResponse)))
          .catch(error => this.error = error);
      }
      else {
        this.error = error;
      }
    });
  }
  render() {
    const { applicationForm, availableFields, organisationConfig, organisationId, step, strings } = this;
    if (!organisationConfig || !applicationForm) {
      return (h("div", { class: "d-flex justify-content-center pt-3" },
        h("dvn-progress", { indefinite: true })));
    }
    const selectedFields = ['firstName', 'lastName', 'email', ...applicationForm.form.fields.map(field => field.id)];
    const options = [
      { label: 'First name', value: 'firstName', disabled: true },
      { label: 'Last name', value: 'lastName', disabled: true },
      { label: 'Email', value: 'email', disabled: true },
      ...(availableFields).map(field => ({
        label: field.title,
        value: 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: strings.previewWhenUpdate }),
                h("dvn-card", { outlined: true, reverseTint: true, leaned: true },
                  h("div", { class: "d-flex align-items-center" },
                    h("dvn-switch", { scale: "small", shape: "rounded", checked: applicationForm.status === 'published', onChange: () => {
                        const applicationForm = JSON.parse(JSON.stringify(this.applicationForm));
                        applicationForm.status = applicationForm.status === 'published' ? 'unpublished' : 'published';
                        this.applicationForm = applicationForm;
                      } }),
                    h("div", { class: "ml-3" }, applicationForm.status === 'published'
                      // flex-row-reverse
                      ? h("div", { class: `d-flex ${this.language === 'tr' && 'flex-row-reverse'}` },
                        h("span", { class: "mr-1" }, strings.appOpenAndAccessible),
                        h("a", { class: "mr-1", href: this.getApplicationLink(), target: "_blank" }, strings.onThisUrl))
                      : strings.appsAreClosed))),
                h("div", { class: "mt-3" },
                  h("dvn-content-switcher", { options: [
                      {
                        label: strings.description,
                        value: 'description',
                      },
                      {
                        label: strings.fields,
                        value: 'fields',
                      },
                    ], onChange: e => this.step = e.detail, value: step, shape: "rounded", leaned: true })),
                step === 'description' &&
                  h("div", { class: "ml-2 mr-2" },
                    h("dvn-rich-editor", { key: "editor", onChange: (e) => {
                        var _a, _b;
                        const editorValue = e.detail;
                        const applicationForm = JSON.parse(JSON.stringify(this.applicationForm));
                        applicationForm.title = htmlDecode((_a = editorValue[0]) === null || _a === void 0 ? void 0 : _a.value.text);
                        applicationForm.description = (_b = editorValue[1]) === null || _b === void 0 ? void 0 : _b.value.text;
                        this.applicationForm = applicationForm;
                        this.editorValue = editorValue;
                      }, editorSettings: {
                        enableDrag: false,
                        enableBlockCreation: false,
                        enableBlockDeletion: false,
                        hideDragControls: true,
                        blockTypes: [],
                        blockSettings: {
                          text: {
                            textSelectionOptions: ['bold', 'link']
                          }
                        }
                      }, value: this.editorValue })),
                step === 'fields' &&
                  h("div", { class: "mt-3" },
                    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 }, strings.saveChanges))),
          h("div", { class: "preview-container d-flex justify-content-center" },
            h("mentornity-membership-application-wrapper", { formFromEditor: applicationForm, configFromEditor: organisationConfig, formTarget: this.formTarget, organisationId: organisationId, onAction: () => this.notifier.warn('Action unavailable in preview.', 'Preview Mode') }))))));
  }
  static get is() { return "mentornity-membership-application-settings-wrapper"; }
  static get originalStyleUrls() { return {
    "$": ["mentornity-membership-application-settings-wrapper.scss"]
  }; }
  static get styleUrls() { return {
    "$": ["mentornity-membership-application-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 {
    "applicationForm": {},
    "targetFields": {},
    "organisationConfig": {},
    "availableFields": {},
    "error": {},
    "step": {},
    "strings": {},
    "editorValue": {}
  }; }
}
injectNotifier(MentornityMembershipApplicationSettingsWrapper);
