import { Component, Event, h, State, Listen, Build, } from "@stencil/core";
import { modalController, popoverController } from "@ionic/core";
import state from "../../../store";
import isAdmin from "../../../helpers/auth/isAdmin";
import isInternalTeam from "../../../helpers/auth/isInternalTeam";
export class AppUserList {
  constructor() {
    var _a, _b;
    this.users = [];
    this.user = {};
    this.selectedUsers = [];
    this.selectedIds = [];
    this.selectedEmails = [];
    this.options = [];
    this.selectAll = false;
    this.fetchData = {
      locationId: (_b = (_a = state === null || state === void 0 ? void 0 : state.profile) === null || _a === void 0 ? void 0 : _a.location) === null || _b === void 0 ? void 0 : _b.id,
    };
  }
  onSearchInput(event) {
    if (!this.paginationEl)
      return;
    this.paginationEl.query = event.target.value;
  }
  onSuccess(event) {
    var _a, _b;
    if (["addUser", "editUser"].includes((_a = event === null || event === void 0 ? void 0 : event.detail) === null || _a === void 0 ? void 0 : _a.endpoint))
      setTimeout(() => this.paginationEl.getResults(), 200);
    if (event.detail.endpoint === "bulkUpdateUsers") {
      this.paginationEl.getResults();
    }
    if (((_b = event === null || event === void 0 ? void 0 : event.detail) === null || _b === void 0 ? void 0 : _b.endpoint) !== "listUsers")
      return;
    setTimeout(() => {
      var _a;
      this.users = ((_a = this.paginationEl) === null || _a === void 0 ? void 0 : _a.results) || [];
    }, 200);
  }
  async openPopover(event, user) {
    event.preventDefault();
    event.stopPropagation();
    const popover = await popoverController.create({
      component: "popover-user",
      cssClass: "popover-user-wrapper",
      componentProps: { user },
      event,
    });
    return await popover.present();
  }
  async openEditUsersModal() {
    this.editUserModalEl = await modalController.create({
      component: "modal-edit-users",
      cssClass: "modal-edit-users",
      componentProps: {
        users: this.selectedUsers,
      },
    });
    return await this.editUserModalEl.present();
  }
  async sendEmail(_event) {
    var _a, _b, _c;
    const filters = {};
    if ((_c = (_b = (_a = this.filterBarEl) === null || _a === void 0 ? void 0 : _a.filter) === null || _b === void 0 ? void 0 : _b.controls) === null || _c === void 0 ? void 0 : _c.length) {
      for (const control of this.filterBarEl.filter.controls) {
        filters[control.name] = control.value;
      }
    }
    this.sendEmailModalEl = await modalController.create({
      component: "modal-send-email",
      cssClass: "modal-send-email-wrapper",
      componentProps: {
        to: this.selectedEmails.filter((email) => email === null || email === void 0 ? void 0 : email.includes("@")),
        filters,
      },
    });
    return await this.sendEmailModalEl.present();
  }
  toggleSelect(event, user) {
    event.stopPropagation();
    event.preventDefault();
    this.selectedUsers = this.selectedUsers.includes(user)
      ? this.selectedUsers.filter((selectedUser) => user.id !== selectedUser.id)
      : [...new Set([...this.selectedUsers, user])];
    this.selectedEmails = this.selectedEmails.includes(user.email)
      ? this.selectedEmails.filter((selectedEmail) => user.email !== selectedEmail)
      : [...new Set([...this.selectedEmails, user.email])];
    this.selectedIds = this.selectedIds.includes(user.id)
      ? this.selectedIds.filter((selectedId) => user.id !== selectedId)
      : [...new Set([...this.selectedIds, user.id])];
  }
  toggleSelectAll() {
    var _a, _b, _c;
    if ((_a = this.selectedIds) === null || _a === void 0 ? void 0 : _a.length) {
      this.selectedUsers = [];
      this.selectedIds = [];
      this.selectedEmails = [];
      this.selectAll = false;
    }
    else {
      if ((_c = (_b = this.paginationEl) === null || _b === void 0 ? void 0 : _b.results) === null || _c === void 0 ? void 0 : _c.length) {
        this.selectedUsers = this.paginationEl.results;
        this.selectedIds = this.paginationEl.results.map((result) => result.id);
        this.selectedEmails = this.paginationEl.results.map((result) => result.email);
      }
    }
  }
  componentDidLoad() {
    if (!(Build === null || Build === void 0 ? void 0 : Build.isBrowser))
      return;
  }
  render() {
    var _a, _b, _c, _d, _e;
    return [
      h("ion-content", { class: "ion-padding" },
        h("floodteam-title-bar", null,
          h("ion-router-link", { href: "/users" }, "Users"),
          h("ion-buttons", { slot: "end" },
            h("ion-button", { fill: "solid", color: "primary", href: "/users/new" }, "Add"))),
        h("fireenjin-search-bar", { ref: (el) => (this.filterBarEl = el), paginationEl: this.paginationEl, filters: [
            {
              name: "companyId",
              label: "Company",
              endpoint: "listCompanies",
              icon: "business",
              resultsKey: "companies",
            },
            {
              name: "tags",
              label: "Tags",
              icon: "pricetags",
              multiple: true,
              options: [
                {
                  label: "Imported",
                  value: "imported",
                },
                {
                  label: "Referral",
                  value: "referral",
                },
                {
                  label: "Plumber",
                  value: "plumber",
                },
                {
                  label: "Staff",
                  value: "staff",
                },
                {
                  label: "Agent",
                  value: "agent",
                },
                {
                  label: "Property Manager",
                  value: "property manager",
                },
                {
                  label: "PEU",
                  value: "peu",
                },
                {
                  label: "CSV Import",
                  value: "csvImport",
                },
              ],
            },
            ...(isAdmin()
              ? [
                {
                  name: "locationId",
                  label: "Location",
                  icon: "business",
                  options: ((_a = state === null || state === void 0 ? void 0 : state.locations) === null || _a === void 0 ? void 0 : _a.length)
                    ? state.locations.map((location) => ({
                      label: location.name,
                      value: location.id,
                    }))
                    : [],
                  value: ((_b = state === null || state === void 0 ? void 0 : state.claims) === null || _b === void 0 ? void 0 : _b.tester) && ((_d = (_c = state === null || state === void 0 ? void 0 : state.profile) === null || _c === void 0 ? void 0 : _c.location) === null || _d === void 0 ? void 0 : _d.id)
                    ? state.profile.location.id
                    : null,
                },
              ]
              : []),
          ] }),
        h("fireenjin-pagination", { disableFetch: !isInternalTeam(), display: "list", ref: (el) => (this.paginationEl = el), disableVirtualScroll: true, listEl: ({ result: user }) => (h("ion-item", { href: `/users/${user.id}`, detail: true },
            h("ion-checkbox", { slot: "start", checked: this.selectedIds.includes(user.id), onClick: (event) => this.toggleSelect(event, user) }),
            h("fireenjin-avatar", { src: user.photo, style: { marginRight: "15px" }, initials: `${(user === null || user === void 0 ? void 0 : user.firstName) ? user.firstName.charAt(0) : ""}${(user === null || user === void 0 ? void 0 : user.lastName) ? user.lastName.charAt(0) : ""}` }),
            h("ion-label", null,
              h("h4", null,
                user.firstName ? user.firstName : "",
                " ",
                user.lastName ? user.lastName : ""),
              (user === null || user === void 0 ? void 0 : user.tags)
                ? user.tags.map((tag) => h("ion-chip", null, tag))
                : null),
            h("ion-button", { fill: "clear", slot: "end", color: "medium", onClick: (event) => this.openPopover(event, user) },
              h("ion-icon", { name: "ellipsis-vertical", slot: "icon-only" })))), endpoint: "listUsers", fetchData: this.fetchData, limit: 20, resultsKey: "users", removeDuplicates: true })),
      h("floodteam-navigation-footer", null, isAdmin() && (h("fireenjin-chip-bar", null,
        h("ion-chip", { onClick: () => this.fireenjinTrigger.emit({
            name: "import",
            type: "users",
          }) },
          h("ion-icon", { class: "ft-icon-style", name: "cloud-upload" }),
          h("ion-label", null, "Import from CSV")),
        h("ion-chip", { onClick: () => {
            this.fireenjinTrigger.emit({
              name: "export",
              payload: (this.users || []).map((user) => {
                var _a;
                return ({
                  id: (user === null || user === void 0 ? void 0 : user.id) || null,
                  firstName: (user === null || user === void 0 ? void 0 : user.firstName) || null,
                  lastName: (user === null || user === void 0 ? void 0 : user.lastName) || null,
                  email: (user === null || user === void 0 ? void 0 : user.email) || null,
                  address: ((_a = user === null || user === void 0 ? void 0 : user.address) === null || _a === void 0 ? void 0 : _a.full) || null,
                  type: (user === null || user === void 0 ? void 0 : user.type) || null,
                  phone: (user === null || user === void 0 ? void 0 : user.phone) || null,
                });
              }),
            });
          } },
          h("ion-icon", { class: "ft-icon-style", name: "cloud-download" }),
          h("ion-label", null, "Export to CSV")),
        h("ion-chip", { onClick: () => this.toggleSelectAll() },
          h("ion-icon", { name: "checkbox", class: "ft-icon-style" }),
          h("ion-label", null, ((_e = this.selectedIds) === null || _e === void 0 ? void 0 : _e.length) ? "Deselect All" : "Select All"))))),
    ];
  }
  static get is() { return "app-user-list"; }
  static get originalStyleUrls() { return {
    "$": ["app-user-list.css"]
  }; }
  static get styleUrls() { return {
    "$": ["app-user-list.css"]
  }; }
  static get states() { return {
    "users": {},
    "paginationEl": {},
    "user": {},
    "selectedUsers": {},
    "selectedIds": {},
    "selectedEmails": {},
    "options": {},
    "selectAll": {},
    "fetchData": {}
  }; }
  static get events() { return [{
      "method": "fireenjinTrigger",
      "name": "fireenjinTrigger",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "FireEnjinTriggerInput",
        "resolved": "FireEnjinTriggerInput",
        "references": {
          "FireEnjinTriggerInput": {
            "location": "import",
            "path": "@fireenjin/sdk"
          }
        }
      }
    }]; }
  static get listeners() { return [{
      "name": "ionInput",
      "method": "onSearchInput",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "fireenjinSuccess",
      "method": "onSuccess",
      "target": "body",
      "capture": false,
      "passive": false
    }]; }
}
//# sourceMappingURL=app-user-list.js.map