import { ResponsiveSize, ResponsiveUIHelper } from '@dvn/alaca/utils/ui';
import { getDataModelField } from '@dvn/core/models/data-model';
import { ListFetchState } from '@dvn/core/models/list-fetch-state';
import { getPairConfigSelectionConfigForRole, PairConfig } from '@dvn/core/models/pair-config';
import CalendarUtils from '@dvn/core/util/calendar';
import { getUserFullName } from '@dvn/kimlik/api/models/User';
import { Component, Element, h, Host, Listen, Prop, State } from '@stencil/core';
import { getLabelForStatus, getTintForStatus } from '../../utils/pair-request';
import { generateActionConfig } from './action-utils';
import { filterList } from './data-util';
function getDescriptionForError(error) {
  switch (error.message) {
    case 'same-subscription-exists':
      return 'You already sent request to this user.';
    case 'selection-limit-reached':
      return 'You reached the selection limit.';
    case 'subscription-limit-reached':
      return 'You reached your pair limit.';
    default:
      return 'Could not create pair.';
  }
}
export class DvnAppViewAtamaMemberPairSelectionView {
  constructor() {
    this.isSendingRequest = false;
    this.list = ListFetchState.init();
    this.sentRequestList = ListFetchState.init();
    this.textFilter = '';
    this.shownTab = 'list-to-select';
    this.onSizeChange = (size) => {
      this.size = size;
    };
  }
  onAction(event) {
    const action = event.detail;
    if (action.name === 'select-pair') {
      this.selectedUser = action.params.item;
    }
  }
  componentDidLoad() {
    this.fetchMembershipConfigOfMemberToShow();
    this.fetchSentRequestList();
    this.fetchSelectionList();
    this.uiHelper = new ResponsiveUIHelper(this.el, this.onSizeChange);
  }
  fetchMembershipConfigOfMemberToShow() {
    var _a;
    const { notifier, view: { table, ui: { i18n } } } = this;
    const { memberToViewRefFieldId } = this.params;
    const memberToShowTableName = (_a = table.fields.find(f => f.type === 'reference' && f.id === memberToViewRefFieldId)) === null || _a === void 0 ? void 0 : _a.otherCollection;
    this.apiUye.getMembershipConfigWithName(memberToShowTableName).then(response => {
      this.membershipConfigToShow = response;
    }, error => notifier.alert(i18n.fetchConfigurationError || 'Getting configuration failed.', error.status));
  }
  fetchSelectionList() {
    var _a;
    const { list } = this;
    if (list.isPending) {
      return;
    }
    const { notifier, view: { table, ui: { i18n } } } = this;
    const { memberToViewRefFieldId, userRefFieldValue } = this.params;
    const memberToShowTableName = (_a = table.fields.find(f => f.type === 'reference' && f.id === memberToViewRefFieldId)) === null || _a === void 0 ? void 0 : _a.otherCollection;
    this.list = list.beforeFetch();
    this.apiAtama.getSelectionList(table.base, memberToShowTableName, table._id, userRefFieldValue, memberToViewRefFieldId)
      .then(response => {
      this.list = list.afterFetch(response, false);
    }, error => {
      this.list = list.afterFetchError(error);
      notifier.alert(i18n.fetchSelectionListError || 'Getting selection list failed.', error.status);
    });
  }
  fetchSentRequestList() {
    const { sentRequestList } = this;
    if (sentRequestList.isPending) {
      return;
    }
    const { notifier, view: { table, ui: { i18n } } } = this;
    const { userRefFieldValue } = this.params;
    this.sentRequestList = sentRequestList.beforeFetch();
    this.apiAtama.getSentRequests(table.base, `${table._id}-requests`, userRefFieldValue)
      .then(response => {
      this.sentRequestList = sentRequestList.afterFetch(response, false);
    }, error => {
      this.sentRequestList = sentRequestList.afterFetchError(error);
      notifier.alert(i18n.fetchSentRequestListError || 'Getting sent requests failed.', error.status);
    });
  }
  onConfirm() {
    const { params, view: { table, ui: { i18n } } } = this;
    const { memberToViewRefFieldId, userRefFieldId, userRefFieldValue } = params;
    const pairConfig = PairConfig.decode(table.toObject());
    const selectionConfig = getPairConfigSelectionConfigForRole(pairConfig, userRefFieldId);
    if (selectionConfig.initiation === 'approvingly') {
      this.isSendingRequest = true;
      this.apiAtama.sendPairRequest(table.base, `${table._id}-requests`, userRefFieldId, userRefFieldValue, memberToViewRefFieldId, this.selectedUser).then(() => {
        this.isSendingRequest = false;
        this.selectedUser = undefined;
        this.fetchSelectionList();
        this.fetchSentRequestList();
        this.componentDidLoad();
        this.notifier.congratulate(i18n.pairRequestIsSent || 'Request is sent');
      }).catch(e => {
        this.isSendingRequest = false;
        this.selectedUser = undefined;
        this.notifier.alert(getDescriptionForError(e.data));
      });
    }
  }
  render() {
    var _a, _b;
    const { list, membershipConfigToShow, params, sentRequestList, shownTab, size, textFilter, view } = this;
    const { userRefFieldId } = params;
    const { ui: { i18n } } = view;
    if (!membershipConfigToShow) {
      return (h("div", { class: "d-flex justify-content-center pt-3" },
        h("dvn-progress", { indefinite: true })));
    }
    const pairConfig = PairConfig.decode(view.table);
    const selectionConfig = getPairConfigSelectionConfigForRole(pairConfig, userRefFieldId);
    const cardUIConfig = {
      main: {
        cardViewConfig: Object.assign(Object.assign({}, view.ui.main.cardViewConfig), { footer: {
            actions: generateActionConfig(i18n, selectionConfig),
          } })
      }
    };
    const items = filterList(cardUIConfig.main.cardViewConfig, membershipConfigToShow.fields, list.data, textFilter);
    const showMobileUI = size < ResponsiveSize.Medium;
    const showHeaders = !showMobileUI;
    const showSelectionList = shownTab === 'list-to-select' || !showMobileUI;
    const showPairRequests = shownTab === 'pair-requests' || !showMobileUI;
    return (h(Host, { class: "row" },
      showMobileUI &&
        h("div", { class: "col-sm-12 d-flex justify-content-center mt-3" },
          h("dvn-content-switcher", { options: [
              {
                label: i18n.listToSelect || 'List to Select',
                value: 'list-to-select',
              },
              {
                label: i18n.sentRequests || 'Sent Requests',
                value: 'pair-requests',
              },
            ], onChange: (event) => this.shownTab = event.detail, value: this.shownTab })),
      showSelectionList &&
        h("div", { class: {
            ['col-sm-12 col-md-8 pt-3']: !showMobileUI,
            ['col-sm-12 pt-2']: showMobileUI,
          } },
          h("div", { class: "ml-2 mb-2 d-flex align-items-center" },
            showHeaders && h("small", null,
              h("b", null, ((_a = i18n.listToSelect) === null || _a === void 0 ? void 0 : _a.toLocaleUpperCase()) || 'LIST TO SELECT'),
              "\u00A0"),
            (list.isPending && list.data) &&
              h("dvn-progress", { indefinite: true, size: 14, strokeWidth: 2, tint: "primary" })),
          (list.isPending && !list.data) &&
            h("div", { class: "d-flex justify-content-center" },
              h("dvn-progress", { indefinite: true })),
          list.data &&
            h("div", null,
              h("div", { class: "mb-3" },
                h("dvn-input", { leaned: true, onChange: (e) => this.textFilter = e.detail, placeholder: i18n.searchPlaceholder || 'Search by any info', width: "100%" })),
              items.length > 0
                ? h("dvn-card-list-view", { config: cardUIConfig, fields: membershipConfigToShow.fields, items: items })
                : h("dvn-card", { elevation: 0, leaned: true, tint: "warning" }, textFilter ? i18n.noItemMatchesFilter : i18n.noItemToSelect))),
      showPairRequests &&
        h("div", { class: {
            ['col-sm-12 col-md-4 pt-3']: !showMobileUI,
            ['col-sm-12 pt-2']: showMobileUI,
          } },
          h("div", { class: "ml-2 mb-2 d-flex align-items-center" },
            showHeaders && h("small", null,
              h("b", null, ((_b = i18n.sentRequests) === null || _b === void 0 ? void 0 : _b.toLocaleUpperCase()) || 'SENT REQUESTS'),
              "\u00A0"),
            (sentRequestList.isPending && sentRequestList.data) &&
              h("dvn-progress", { indefinite: true, size: 14, strokeWidth: 2, tint: "primary" })),
          h("dvn-card", { elevation: 0, leaned: true, tint: "warning" }, (i18n.maxLimitMessage || 'You can send max {selectionLimit} requests at a time.')
            .replace(/{selectionLimit}/g, `${selectionConfig.selectionLimit}`)),
          (sentRequestList.isPending && !sentRequestList.data) &&
            h("div", { class: "d-flex justify-content-center mt-3" },
              h("dvn-progress", { indefinite: true })),
          sentRequestList.data &&
            h("div", null, sentRequestList.data.length > 0
              ? sentRequestList.data
                .sort((a, b) => b.requestedAt - a.requestedAt)
                .map((request) => (h("dvn-card", { key: request._id, elevation: 0, leaned: true, bodyLeaned: true, style: { margin: '1rem 0 0 0' } },
                h("div", { class: "d-flex justify-content-between align-items-center pr-2" },
                  h("dvn-info-summary", { title: getUserFullName(getDataModelField(request, 'sentTo')), subTitle: CalendarUtils.format(new Date(request.requestedAt * 1000), i18n.sentOnDateFormat || 'DD MMM YYYY, HH:mm') },
                    h("dvn-image", { slot: "media", src: getDataModelField(request, 'sentTo').imageUrl, shape: "circle" })),
                  h("dvn-button", { leaned: true, scale: "small", shape: "rounded", tagMode: true, tint: getTintForStatus(request), view: "ghost" }, getLabelForStatus(i18n.statusLabels, request))))))
              : h("div", { class: "mt-3" },
                h("dvn-card", { elevation: 0, leaned: true, tint: "neutral" }, i18n.noSentRequests)))),
      this.selectedUser &&
        h("dvn-dialog", { title: i18n.selectionConfirmationDialogTitle || 'Are you sure to select this user?', shown: !!this.selectedUser, onDismiss: () => this.selectedUser = undefined },
          selectionConfig.initiation === 'approvingly'
            ? (i18n.selectionConfirmationDialogMessageForApproval || 'The user will receive a notification and the process will start after the user approves the request. Requests can only be canceled by the program administration.')
            : (i18n.selectionConfirmationDialogMessage || 'The user will receive a notification and the process will start immediately. Pairs can only be canceled by the program administration.'),
          h("div", { slot: "actions" },
            h("dvn-button", { disabled: this.isSendingRequest, onClick: () => this.selectedUser = undefined, tint: "danger", view: "flat" }, i18n.cancel || 'Cancel'),
            h("dvn-button", { disabled: this.isSendingRequest, progressing: this.isSendingRequest, onClick: () => this.onConfirm(), tint: "secondary", view: "flat" }, i18n.yes || 'Yes')))));
  }
  static get is() { return "dvn-app-view-atama-member-pair-selection-view"; }
  static get properties() { return {
    "apiAtama": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "AtamaApi",
        "resolved": "AtamaApi",
        "references": {
          "AtamaApi": {
            "location": "import",
            "path": "../../api/atamaApi"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "apiUye": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "UyeApi",
        "resolved": "UyeApi",
        "references": {
          "UyeApi": {
            "location": "import",
            "path": "@dvn/uye/api"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "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": ""
      }
    },
    "params": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "DvnAppViewAtamaMemberPairSelectionViewParams",
        "resolved": "DvnAppViewAtamaMemberPairSelectionViewParams",
        "references": {
          "DvnAppViewAtamaMemberPairSelectionViewParams": {
            "location": "import",
            "path": "./params"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "view": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "AtamaMemberPairsSelectionViewConfig",
        "resolved": "AtamaMemberPairsSelectionViewConfig",
        "references": {
          "AtamaMemberPairsSelectionViewConfig": {
            "location": "import",
            "path": "../atama-member-pair-selection-view-config"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    }
  }; }
  static get states() { return {
    "selectedUser": {},
    "isSendingRequest": {},
    "list": {},
    "sentRequestList": {},
    "membershipConfigToShow": {},
    "textFilter": {},
    "size": {},
    "shownTab": {}
  }; }
  static get elementRef() { return "el"; }
  static get listeners() { return [{
      "name": "action",
      "method": "onAction",
      "target": undefined,
      "capture": false,
      "passive": false
    }]; }
}
