import CalendarUtils from '@dvn/core/util/calendar';
import { capitalize } from '@dvn/core/util/string';
import { Component, Event, h, Host, Prop, State } from '@stencil/core';
import { convertMentornityFieldToDevingenField } from '../../api/mentorinty-bridge-api';
import { mentornityPastMeetingWidgetI18nDefault, MentornityPastMeetingWidgetI18nKey } from './i18n';
const formErrors = (error) => {
  if (!error)
    return [];
  // TODO show proper error messages from apiSozluk
  return [
    capitalize(`${error.data.message.split('-').join(' ')}.`, false),
  ];
};
export class MentornityPastMeetingsWidget {
  constructor() {
    this.toggleSeeAllButton = false;
    this.isProgressing = false;
    this.createResponseFormError = undefined;
    this.isPending = true;
    this.goToMeetingDetails = (meeting) => this.action.emit({
      name: 'go-to-meeting-page',
      params: { meetingId: meeting._id }
    });
    this.formFields = () => {
      var _a;
      const fields = (_a = this.feedbackConfig) === null || _a === void 0 ? void 0 : _a.fields.map(field => convertMentornityFieldToDevingenField(field));
      return { fields };
    };
    this.onSubmitForm = async (event) => {
      const data = event.detail.values;
      if (Object.keys(data).length === 0) {
        return;
      }
      const formResponse = {
        data: Object.assign({}, data),
        event: { _type: 'reference', _class: 'events', _id: this.selectedForm._id },
        organisation: { _type: 'reference', _class: 'organisations', _id: this.selectedForm.organisation._id },
        type: 'feedback',
      };
      if (this.groupId) {
        formResponse.group = { _type: 'reference', _class: 'groups', _id: this.groupId };
      }
      this.isProgressing = true;
      this.createResponseFormError = undefined;
      this.api.createFormResponse(formResponse)
        .then(async () => {
        // fetch the meetings again
        const data = await this.fetchPastMeetings(this.context);
        this.isProgressing = false;
        this.meetings = data.meetings;
        this.unfilledFormCount = data.unfilledFormCount;
        // to close modal
        this.selectedForm = null;
      })
        .catch(err => this.createResponseFormError = err);
    };
    this.generatePastmeetingView = (meetings, account, groupId, timeFormat, meetingGoalConfig, meetingsLength, expandMeetings, strings, goToMeetingDetails) => {
      var _a;
      const hasMeetingGoal = meetingGoalConfig && ((_a = meetingGoalConfig.meetingGoals) === null || _a === void 0 ? void 0 : _a.length) > 0;
      // filter nearest meetings
      meetings = meetings.sort((a, b) => {
        return b.startDate * 1000 - a.startDate * 1000;
      });
      const generatedMeetings = generateMeetings(meetings, expandMeetings);
      return (h("div", null, generatedMeetings.map((meeting, i) => {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
        const meetingDayAndMonth = CalendarUtils.format(new Date(meeting.startDate * 1000), 'MMM DD');
        const meetingYear = CalendarUtils.format(new Date(meeting.startDate * 1000), 'YYYY');
        const startDate = CalendarUtils.format(new Date(meeting.startDate * 1000), `ddd HH:mm ${timeFormat === '12-hour' ? 'A' : ''}`);
        const endDate = CalendarUtils.format(new Date(meeting.endDate * 1000), `HH:mm ${timeFormat === '12-hour' ? 'A' : ''}`);
        const guests = meeting.guests;
        const mentor = guests[0];
        const mentee = guests[1];
        const isAccountMentor = mentor._id === account._id;
        const isMenteeUser = mentee._class === 'users' || mentee.firstName;
        const isMenteeGroup = mentee._class === 'groups' || !mentee.firstName;
        const isAccountMenteeInMeeting = isMenteeUser && !!guests.find(m => m._id === account._id);
        const isGroupMenteeInMeeting = isMenteeGroup && groupId && !!guests.find(m => m._id === groupId); // eslint-disable-line max-len
        let fullName = '';
        if (account && isAccountMentor) {
          if (isMenteeUser) {
            fullName = `${mentee.firstName} ${mentee.lastName}`;
          }
          else if (isMenteeGroup) {
            if (((_a = meeting.guests) === null || _a === void 0 ? void 0 : _a.length) > 2) {
              for (let i = 1; i < ((_b = meeting.guests) === null || _b === void 0 ? void 0 : _b.length); i++) {
                fullName += meeting.guests[i].title;
                fullName = ((_c = meeting.guests) === null || _c === void 0 ? void 0 : _c.length) - 1 !== i
                  ? fullName.concat(', ')
                  : fullName;
              }
              fullName = truncate(fullName, 40);
            }
            else {
              fullName = mentee.title;
            }
          }
        }
        else if (account && (isAccountMenteeInMeeting || isGroupMenteeInMeeting)) {
          fullName = `${mentor.firstName} ${mentor.lastName}`;
        }
        const meetingTime = startDate + ' - ' + endDate;
        const displayBreakLine = i < meetingsLength - 1;
        const meetingLocation = `${((_e = (_d = meeting.location) === null || _d === void 0 ? void 0 : _d.type) === null || _e === void 0 ? void 0 : _e.charAt(0).toUpperCase()) + ((_g = (_f = meeting.location) === null || _f === void 0 ? void 0 : _f.type) === null || _g === void 0 ? void 0 : _g.slice(1))} ${strings.meet}`;
        const ownSession = hasMeetingGoal && (meetingGoalConfig === null || meetingGoalConfig === void 0 ? void 0 : meetingGoalConfig.meetingGoals.find(session => session.identifier === meeting.meetingGoalIdentifier));
        const hasFeedback = !!((_h = meeting === null || meeting === void 0 ? void 0 : meeting.feedback) === null || _h === void 0 ? void 0 : _h._id) || ((_j = meeting === null || meeting === void 0 ? void 0 : meeting.feedback) === null || _j === void 0 ? void 0 : _j.length) > 0;
        // check if session has a questions
        let sessionHasQuestions = false;
        if (hasMeetingGoal) {
          const session = ownSession === null || ownSession === void 0 ? void 0 : ownSession.specifications[this.userType];
          sessionHasQuestions = ((_l = (_k = session === null || session === void 0 ? void 0 : session.postMeetingForm) === null || _k === void 0 ? void 0 : _k.fields) === null || _l === void 0 ? void 0 : _l.length) > 0 || ((_o = (_m = session === null || session === void 0 ? void 0 : session.preMeetingForm) === null || _m === void 0 ? void 0 : _m.fields) === null || _o === void 0 ? void 0 : _o.length) > 0;
        }
        return (h("div", null,
          hasMeetingGoal &&
            h("div", { class: "meeting-goal-title" },
              h("h3", null,
                " ", ownSession === null || ownSession === void 0 ? void 0 :
                ownSession.meetingTitle,
                " ")),
          h("div", { class: "d-flex justify-content-between align-items-center mt-2" },
            h("div", { class: "d-flex meeting-data" },
              h("p", { class: "meeting-date", onClick: () => goToMeetingDetails(meeting) },
                " ",
                h("span", { class: "meeting-year" }, meetingYear),
                " ",
                h("span", null, meetingDayAndMonth),
                " "),
              h("div", { class: "flex-column ml-3" },
                ((hasMeetingGoal && sessionHasQuestions && !hasFeedback) || (!hasMeetingGoal && !hasFeedback)) &&
                  h("div", { class: "d-flex align-items-center clickable fill-error", onClick: () => {
                      if (!hasMeetingGoal)
                        this.selectedForm = Object.assign(Object.assign({}, meeting), { index: i });
                      else
                        goToMeetingDetails(meeting);
                    } },
                    h("p", null, strings.fillForm),
                    h("dvn-icon", { iconName: `uil uil-edit-alt`, scale: "large" })),
                h("div", { class: "full-name" },
                  h("p", null,
                    " ",
                    fullName,
                    " ")),
                h("div", { class: "meeting-time" },
                  h("p", null,
                    " ",
                    meetingTime,
                    " ")),
                h("div", { class: "d-flex align-items-center text-primary" }, meeting.location.type === 'custom' || meeting.location.type === undefined ?
                  h("p", { class: "custom-address" },
                    " ",
                    truncate(meeting.location.address, 30),
                    " ")
                  :
                    h("div", { class: "d-flex align-items-center" },
                      h("dvn-icon", { "icon-name": "uil uil-video", scale: "large", size: 20, class: "video-icon" }),
                      h("a", { class: "ml-2", target: '_blank', href: meeting.location.address },
                        " ",
                        meetingLocation,
                        " "))))),
            h("dvn-icon", { onClick: () => goToMeetingDetails(meeting), class: "clickable", "icon-name": "uil uil-angle-right-b", size: 35 })),
          displayBreakLine &&
            h("hr", { class: "break-line" })));
      })));
    };
  }
  async componentWillLoad() {
    this.strings = await this.apiSozluk.getContent(MentornityPastMeetingWidgetI18nKey, mentornityPastMeetingWidgetI18nDefault);
  }
  render() {
    var _a, _b;
    const { meetings, timeFormat, strings, isPending, meetingGoalConfig, account, groupId, isProgressing, createResponseFormError, unfilledFormCount, unfilledSessionFormCount } = this;
    const { fields: meetingDetailsFormFields } = this.formFields();
    const hasMeetings = (meetings === null || meetings === void 0 ? void 0 : meetings.length) > 0;
    const hasMeetingGoal = meetingGoalConfig && ((_a = meetingGoalConfig.meetingGoals) === null || _a === void 0 ? void 0 : _a.length) > 0;
    if (isPending) {
      return (h(Host, null,
        h("b", { class: "pl-3", style: { fontSize: '1.1rem' } }, strings.pastMeetings),
        h("dvn-card", { elevation: 1 },
          h("div", { class: "d-flex justify-content-center" },
            h("dvn-progress", { indefinite: true, tint: "primary" })))));
    }
    const meetingsCount = hasMeetingGoal ? unfilledSessionFormCount : unfilledFormCount;
    return (h(Host, null,
      h("b", { class: "pl-3", style: { fontSize: '1.1rem' } }, strings.pastMeetings),
      h("dvn-card", { elevation: 1 },
        ((hasMeetingGoal && unfilledSessionFormCount > 0) || (!hasMeetingGoal && unfilledFormCount > 0)) &&
          h("dvn-alert", { message: meetingsCount > 1 ?
              `${String(meetingsCount)} ${strings.formsAreWaiting}`
              :
                `${String(meetingsCount)} ${strings.formsIsWaiting}`, tint: "danger" }),
        meetings &&
          this.generatePastmeetingView(meetings, account, groupId, timeFormat, meetingGoalConfig, meetings === null || meetings === void 0 ? void 0 : meetings.length, this.toggleSeeAllButton, strings, this.goToMeetingDetails),
        (meetings === null || meetings === void 0 ? void 0 : meetings.length) > 3 && !this.toggleSeeAllButton &&
          h("dvn-card-footer", { class: "mt-3", slot: "footer", alignRight: true },
            h("dvn-button", { leaned: true, view: "flat", onClick: () => {
                this.toggleSeeAllButton = true;
              } },
              strings.seeAll,
              "(",
              meetings.length,
              ")")),
        !hasMeetings &&
          h("div", { class: "col-md-12" },
            h("p", null,
              " ",
              strings.listMeetingsHere,
              " "),
            h("p", null,
              " ",
              strings.emptyMeetings,
              " "))),
      !hasMeetingGoal &&
        h("dvn-dialog", { title: strings.meetingQuestions, shown: !!this.selectedForm, onDismiss: () => {
            this.selectedForm = null;
            this.createResponseFormError = undefined;
          } },
          h("doldurma-form", { key: (_b = this.selectedForm) === null || _b === void 0 ? void 0 : _b.index, fields: meetingDetailsFormFields, onSubmit: this.onSubmitForm, submitButtonLabel: strings.submit, progressing: isProgressing, formErrors: formErrors(createResponseFormError), width: '100%' }))));
  }
  static get is() { return "mentornity-past-meetings-widget"; }
  static get originalStyleUrls() { return {
    "$": ["mentornity-past-meetings-widget.scss"]
  }; }
  static get styleUrls() { return {
    "$": ["mentornity-past-meetings-widget.css"]
  }; }
  static get properties() { return {
    "meetings": {
      "type": "any",
      "mutable": false,
      "complexType": {
        "original": "any",
        "resolved": "any",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "meetings",
      "reflect": false
    },
    "account": {
      "type": "any",
      "mutable": false,
      "complexType": {
        "original": "any",
        "resolved": "any",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "account",
      "reflect": false
    },
    "userType": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "user-type",
      "reflect": false
    },
    "unfilledFormCount": {
      "type": "number",
      "mutable": false,
      "complexType": {
        "original": "number",
        "resolved": "number",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "unfilled-form-count",
      "reflect": false
    },
    "unfilledSessionFormCount": {
      "type": "number",
      "mutable": false,
      "complexType": {
        "original": "number",
        "resolved": "number",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "unfilled-session-form-count",
      "reflect": false
    },
    "groupId": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "group-id",
      "reflect": false
    },
    "isPending": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "Boolean",
        "resolved": "Boolean",
        "references": {
          "Boolean": {
            "location": "global"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "defaultValue": "true"
    },
    "meetingGoalConfig": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "MeetingGoalConfig",
        "resolved": "MeetingGoalConfig",
        "references": {
          "MeetingGoalConfig": {
            "location": "import",
            "path": "src/modules/mentornity-js-client/models"
          }
        }
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "timeFormat": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "String",
        "resolved": "String",
        "references": {
          "String": {
            "location": "global"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "apiSozluk": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "SozlukApi",
        "resolved": "SozlukApi",
        "references": {
          "SozlukApi": {
            "location": "import",
            "path": "@dvn/sozluk/api"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "feedbackConfig": {
      "type": "any",
      "mutable": false,
      "complexType": {
        "original": "any",
        "resolved": "any",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "feedback-config",
      "reflect": false
    },
    "context": {
      "type": "any",
      "mutable": false,
      "complexType": {
        "original": "any",
        "resolved": "any",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "context",
      "reflect": false
    },
    "api": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "MentornityApi",
        "resolved": "MentornityApi",
        "references": {
          "MentornityApi": {
            "location": "import",
            "path": "src/modules/mentornity-js-client"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "fetchPastMeetings": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "(context: any) => PastMeetingsData",
        "resolved": "(context: any) => PastMeetingsData",
        "references": {
          "PastMeetingsData": {
            "location": "global"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    }
  }; }
  static get states() { return {
    "toggleSeeAllButton": {},
    "selectedForm": {},
    "strings": {},
    "isProgressing": {},
    "createResponseFormError": {}
  }; }
  static get events() { return [{
      "method": "action",
      "name": "action",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "any",
        "resolved": "any",
        "references": {}
      }
    }]; }
}
const generateMeetings = (meetings, toggleSeeAllButton) => {
  if (!meetings)
    return [];
  // display only first 3 items
  if (!toggleSeeAllButton) {
    return meetings.slice(0, 3);
  }
  // display all item
  return meetings;
};
const truncate = (text, limit) => {
  if (text.length > limit) {
    return text.substring(0, limit) + '...';
  }
  return text;
};
