import { TextField } from '@dvn/core/doldurma/src/fields/text';
import { ValidatorEmail } from '@dvn/core/doldurma/src/interceptors/validators/ValidatorEmail';
import { Component, h, Prop, State } from '@stencil/core';
import { createMentornityApiInstance } from '../../../../mentornity-js-client';
import { convertMentornityFieldToDevingenField } from '../../api/mentorinty-bridge-api';
import { mentornityApiEndpoint } from '../../constants/env';
import { getSessionDetails } from '../../util/session';
import { ImagePosition } from '@dvn/alaca/components/dvn-card-header/models';
import { mentornityMembershipApplicationSettingsI18nDefault, MentornityMembershipApplicationSettingsI18nKey } from '../mentornity-membership-application-settings-wrapper/i18n';
import { SozlukApi } from '@dvn/sozluk/api';
import { sozlukEntries } from '../sozluk-entries';
const formFields = (i18n, config, form) => {
  let extraFields = [];
  if (form) {
    const fieldsFromConfig = config.metadatas[form.target];
    extraFields = form.form.fields.map(fieldInForm => {
      // get the field from config because it contains the most up to date info and the form field only contains the ids
      const fieldFromConfig = fieldsFromConfig.find(f => f.id === fieldInForm.id);
      if (fieldFromConfig) {
        // field may have been deleted from the config. ignore it if deleted
        return convertMentornityFieldToDevingenField(fieldFromConfig);
      }
      return undefined;
    }).filter(f => !!f);
  }
  return [
    new TextField('firstName', i18n.firstName, '', '').setErrorTitle(i18n.firstName)
      .require(),
    new TextField('lastName', i18n.lastName, '', '').setErrorTitle(i18n.lastName)
      .require(),
    new TextField('email', i18n.email, '', '', 'email').setErrorTitle(i18n.email)
      .addInterceptor('onSubmit', new ValidatorEmail())
      .require(),
    ...extraFields,
    {
      id: 'mentornityApplicationLegalFooter',
      customViewTag: 'mentornity-application-legal-footer',
      i18n
    }
  ];
};
export class MentornityMembershipApplicationWrapper {
  constructor() {
    this.isProgressing = false;
    this.isComplete = false;
    this.onSubmit = (event) => {
      if (this.onAction) {
        // the page is used in builder
        this.onAction('submit');
        return;
      }
      const { context } = getSessionDetails();
      const data = event.detail.values;
      this.isProgressing = true;
      const collection = this.formTarget === 'mentor' ? 'mentors' : 'mentees';
      this.api.createMembershipApplication(context.organisationId, collection, data).then(this.onSucceed, this.onError);
    };
    this.onSucceed = () => {
      this.isProgressing = false;
      this.isComplete = true;
    };
    this.onError = (error) => {
      this.error = error;
      this.isProgressing = false;
    };
  }
  async componentWillLoad() {
    const { headers } = getSessionDetails();
    this.api = createMentornityApiInstance(mentornityApiEndpoint, headers);
    // Setup configuration
    const apiSozluk = new SozlukApi().setLanguage(this.language).setContents(sozlukEntries);
    this.strings = await apiSozluk.getContent(MentornityMembershipApplicationSettingsI18nKey, mentornityMembershipApplicationSettingsI18nDefault);
    const organisation = await this.api.getOrganisation(this.organisationId)
      .catch(error => this.error = error);
    if (!organisation)
      return;
    this.organisation = organisation;
    if (this.configFromEditor) {
      this.organisationConfig = this.configFromEditor;
    }
    else {
      const config = await this.api.getOrganisationConfig(organisation._id)
        .catch(error => this.error = error);
      if (!config)
        return;
      this.organisationConfig = config;
    }
    if (this.formFromEditor) {
      this.form = this.formFromEditor;
    }
    else {
      const collection = this.formTarget === 'mentor' ? 'mentors' : 'mentees';
      this.api.getMembershipApplicationForm(organisation._id, collection)
        .then(form => this.form = form)
        .catch(error => this.error = error);
    }
  }
  render() {
    const { error, form, formFromEditor, organisation, organisationConfig, isComplete, isProgressing, strings } = this;
    const formToUse = formFromEditor || form;
    if (!formToUse && error && error.status === 404) {
      return (h("mentornity-root-wrapper", { class: "d-flex flex-column align-items-center" },
        h("p", { class: "p-3" }, strings.appsAreNotOpen)));
    }
    if (!formToUse || !organisation || !strings) {
      return (h("mentornity-root-wrapper", null,
        h("div", { class: "d-flex justify-content-center pt-3" },
          h("dvn-progress", { indefinite: true }))));
    }
    if (formToUse.status === 'unpublished') {
      return (h("mentornity-root-wrapper", { class: "d-flex flex-column align-items-center" },
        h("p", { class: "p-3" }, strings.appsAreNotOpen)));
    }
    return (h("mentornity-root-wrapper", { class: "d-block p-3" },
      h("div", { style: { margin: '0 auto', maxWidth: `600px` } },
        h("dvn-card", { leanedSides: true },
          h("dvn-card-header", { title: formToUse.title, slot: "header", showCover: true, coverSrc: organisation.coverUrl || 'https://bit.ly/36goixD', showImage: true, imageSrc: organisation.logoUrl, imageShape: "rounded", imageBorder: true, imagePosition: ImagePosition.BelowCover },
            h("div", { slot: "subtitle" }, this.organisation.title)),
          h("dvn-markdown", { content: formToUse.description })),
        !isComplete &&
          h("dvn-card", { leanedSides: true },
            h("doldurma-form", { fields: formFields(strings, organisationConfig, formToUse), onSubmit: this.onSubmit, submitButtonLabel: strings.sendApplication, progressing: isProgressing || isComplete, formErrors: [] })),
        isComplete &&
          h("dvn-card", { leanedSides: true, tint: "secondary" }, strings.applicationIsSent),
        error &&
          h("dvn-card", { leanedSides: true, tint: "danger" }, strings.applicationFailed))));
  }
  static get is() { return "mentornity-membership-application-wrapper"; }
  static get properties() { return {
    "onAction": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "(name: string, data?: any) => void",
        "resolved": "(name: string, data?: any) => void",
        "references": {}
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "configFromEditor": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "Config",
        "resolved": "Config",
        "references": {
          "Config": {
            "location": "import",
            "path": "../../../../mentornity-js-client/models"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "formFromEditor": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "FormModel",
        "resolved": "FormModel",
        "references": {
          "FormModel": {
            "location": "import",
            "path": "../../../../mentornity-js-client/models"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "language": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Context props."
      },
      "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
    }
  }; }
  static get states() { return {
    "organisation": {},
    "organisationConfig": {},
    "form": {},
    "strings": {},
    "error": {},
    "isProgressing": {},
    "isComplete": {}
  }; }
}
