import { Build, h, } from "@stencil/core";
import state from "../../../store";
import pick from "../../../helpers/pick";
import isAdmin from "../../../helpers/auth/isAdmin";
import isInternalTeam from "../../../helpers/auth/isInternalTeam";
import isLoggedIn from "../../../helpers/auth/isLoggedIn";
import moveItemInArray from "../../../helpers/moveItemInArray";
import { modalController } from "@ionic/core";
import { getDownloadURL, getStorage, ref, uploadBytes } from "firebase/storage";
export class NavigationMenu {
  constructor() {
    this.items = [
      {
        id: "alerts",
        href: "/alerts",
        icon: "notifications",
        name: "Alerts",
        permissionCheck: isAdmin.bind(this),
      },
      {
        id: "appointments",
        href: "/appointments",
        icon: "calendar",
        name: "Appointments",
        permissionCheck: isAdmin.bind(this),
      },
      {
        id: "atmospherics",
        href: "/atmospherics",
        icon: "cloud-circle-outline",
        name: "Atmospheric Readings",
        permissionCheck: isAdmin.bind(this),
      },
      {
        id: "campaigns",
        href: "/campaigns",
        icon: "magnet",
        name: "Campaigns",
        permissionCheck: isAdmin.bind(this),
      },
      {
        id: "companies",
        href: "/companies",
        icon: "briefcase",
        name: "Companies",
        add: "/companies/new",
        permissionCheck: isInternalTeam.bind(this),
      },
      {
        id: "contracts",
        href: "/contracts",
        icon: "create",
        name: "Contracts",
        permissionCheck: isInternalTeam.bind(this),
      },
      {
        id: "dots",
        href: "/dots",
        icon: "ellipse",
        name: "Dots",
        permissionCheck: isAdmin.bind(this),
      },
      {
        id: "exhausts",
        href: "/exhausts",
        icon: "exit",
        name: "Exhaust Readings",
        permissionCheck: isAdmin.bind(this),
      },
      {
        id: "jobs",
        href: "/jobs",
        icon: "water",
        name: "Jobs",
        add: "/jobs/refer",
        permissionCheck: isLoggedIn.bind(this),
      },
      {
        id: "import",
        href: "/import",
        icon: "download",
        name: "Import",
        permissionCheck: isAdmin.bind(this),
      },
      {
        id: "inventory",
        href: "/inventory",
        icon: "barcode-outline",
        name: "Inventory",
        permissionCheck: isInternalTeam.bind(this),
      },
      {
        id: "locations",
        href: "/locations",
        icon: "business",
        name: "Locations",
        add: "/locations/new",
        permissionCheck: isInternalTeam.bind(this),
      },
      {
        id: "logs",
        href: "/logs",
        icon: "journal",
        name: "Logs",
        permissionCheck: isAdmin.bind(this),
      },
      {
        id: "moisturecontents",
        href: "/moisturecontents",
        icon: "water",
        name: "MC Readings",
        permissionCheck: isAdmin.bind(this),
      },
      {
        id: "paymodels",
        href: "/paymodels",
        icon: "pie-chart",
        name: "Pay Models",
        permissionCheck: isAdmin.bind(this),
      },
      {
        id: "payments",
        href: "/payments",
        icon: "cash",
        name: "Payments",
        permissionCheck: isAdmin.bind(this),
      },
      {
        id: "phonenumbers",
        href: "/phonenumbers",
        icon: "call",
        name: "Phone Numbers",
        permissionCheck: isAdmin.bind(this),
      },
      {
        id: "pins",
        href: "/pins",
        icon: "pin",
        name: "Pins",
        permissionCheck: isAdmin.bind(this),
      },
      {
        id: "services",
        href: "/services",
        icon: "reader",
        name: "Services",
        permissionCheck: isInternalTeam.bind(this),
      },
      {
        id: "templates",
        href: "/templates",
        icon: "create",
        name: "Templates",
        add: "/templates/new",
        permissionCheck: isAdmin.bind(this),
      },
      {
        id: "totallers",
        href: "/totallers",
        icon: "calculator",
        name: "Totallers",
        permissionCheck: isAdmin.bind(this),
      },
      {
        id: "triggers",
        href: "/triggers",
        icon: "flash",
        name: "Triggers",
        add: "/triggers/new",
        permissionCheck: isAdmin.bind(this),
      },
      {
        id: "users",
        href: "/users",
        icon: "people",
        name: "Users",
        add: "/users/new",
        permissionCheck: isInternalTeam.bind(this),
      },
      {
        id: "vehicles",
        href: "/vehicles",
        icon: "car",
        name: "Vehicles",
        permissionCheck: isInternalTeam.bind(this),
      },
      {
        id: "weather",
        href: "/weather",
        icon: "rainy",
        name: "Weather",
        permissionCheck: isAdmin.bind(this),
      },
    ];
    this.activityFilters = ["me"];
  }
  onTrigger(event) {
    var _a, _b, _c, _d, _e;
    if (((_c = (_b = (_a = event === null || event === void 0 ? void 0 : event.detail) === null || _a === void 0 ? void 0 : _a.event) === null || _b === void 0 ? void 0 : _b.detail) === null || _c === void 0 ? void 0 : _c.type) === "feedType") {
      this.activityFilters = ((_e = (_d = event.detail) === null || _d === void 0 ? void 0 : _d.payload) === null || _e === void 0 ? void 0 : _e.value) || ["me"];
    }
  }
  onSearchInput(event) {
    var _a, _b, _c, _d, _e;
    if (((_a = event === null || event === void 0 ? void 0 : event.target) === null || _a === void 0 ? void 0 : _a.name) === "sendAlert") {
      state.draftNote.sendAlert = !!((_b = event === null || event === void 0 ? void 0 : event.detail) === null || _b === void 0 ? void 0 : _b.checked);
      state.draftNote = { ...state.draftNote };
    }
    else if (((_c = event === null || event === void 0 ? void 0 : event.target) === null || _c === void 0 ? void 0 : _c.name) === "tags") {
      state.draftNote.tags = ((_d = event === null || event === void 0 ? void 0 : event.target) === null || _d === void 0 ? void 0 : _d.value) ? event.target.value : [];
      state.draftNote = { ...state.draftNote };
    }
    else {
      this.feedPaginationEl.query = ((_e = event === null || event === void 0 ? void 0 : event.target) === null || _e === void 0 ? void 0 : _e.value) || null;
    }
  }
  async onFormFinish(event) {
    var _a, _b, _c;
    if (((_a = event === null || event === void 0 ? void 0 : event.detail) === null || _a === void 0 ? void 0 : _a.endpoint) !== "addNote")
      return;
    state.draftNote = {};
    (_c = (_b = this.editorEl) === null || _b === void 0 ? void 0 : _b.clear) === null || _c === void 0 ? void 0 : _c.call(_b);
  }
  async onEditorChange() {
    var _a, _b;
    if (!((_a = this.editorEl) === null || _a === void 0 ? void 0 : _a.exportHTML))
      return;
    const html = await this.editorEl.exportHTML();
    const editor = await this.editorEl.exportJSON();
    if ((_b = editor === null || editor === void 0 ? void 0 : editor.blocks) === null || _b === void 0 ? void 0 : _b.length)
      state.draftNote = {
        ...state.draftNote,
        html,
        editor,
      };
  }
  async toggleNavPin(event, item) {
    event.preventDefault();
    event.stopPropagation();
    this.fireenjinTrigger.emit({
      name: "pin",
      payload: pick(item, ["icon", "name", "href"]),
    });
  }
  async doReorder(event) {
    var _a;
    const pinIds = state.pins.map((pin) => pin.id);
    const reorderedPinIds = moveItemInArray(pinIds, event.detail.from, event.detail.to);
    const pins = ((state === null || state === void 0 ? void 0 : state.pins) || [])
      .map((pin) => ({
      ...pin,
      order: reorderedPinIds.findIndex((p) => p === (pin === null || pin === void 0 ? void 0 : pin.id)),
    }))
      .sort((a, b) => a.order - b.order);
    this.fireenjinSubmit.emit({
      endpoint: "reorderPins",
      data: {
        userId: (_a = state === null || state === void 0 ? void 0 : state.session) === null || _a === void 0 ? void 0 : _a.uid,
        pins,
      },
    });
    state.pins = event.detail.complete(state.pins);
  }
  async openNoteModal() {
    var _a, _b;
    this.noteModalEl = await modalController.create({
      cssClass: "modal-note",
      component: "modal-note",
      componentProps: {
        jobId: ((_a = state === null || state === void 0 ? void 0 : state.job) === null || _a === void 0 ? void 0 : _a.id) || null,
        userId: ((_b = state === null || state === void 0 ? void 0 : state.user) === null || _b === void 0 ? void 0 : _b.id) || null,
      },
    });
    this.noteModalEl.present();
  }
  getExtension(path) {
    var basename = path.split(/[\\/]/).pop(), // extract file name from full path ...
    // (supports `\\` and `/` separators)
    pos = basename.lastIndexOf("."); // get last position of `.`
    if (basename === "" || pos < 1)
      // if file name is empty or ...
      return ""; //  `.` not found (-1) or comes first (0)
    return basename.slice(pos + 1); // extract extension ignoring `.`
  }
  async onPhotoUpload(event) {
    var _a;
    console.log(event);
    const storage = getStorage();
    const storageRef = ref(storage, `pictures/${new Date().toISOString()}.${this.getExtension((_a = event === null || event === void 0 ? void 0 : event.file) === null || _a === void 0 ? void 0 : _a.name)}`);
    const upload = await uploadBytes(storageRef, event.file);
    const url = await getDownloadURL(upload.ref);
    return {
      success: true,
      file: {
        url,
      },
    };
  }
  async componentDidLoad() {
    var _a, _b, _c, _d;
    if (!(Build === null || Build === void 0 ? void 0 : Build.isBrowser))
      return;
    this.editorJs = await ((_b = (_a = this.editorEl) === null || _a === void 0 ? void 0 : _a.getInstance) === null || _b === void 0 ? void 0 : _b.call(_a));
    if ((_c = state === null || state === void 0 ? void 0 : state.draftNote) === null || _c === void 0 ? void 0 : _c.editor) {
      try {
        this.editorJs.blocks.render(((_d = state.draftNote) === null || _d === void 0 ? void 0 : _d.editor) || {});
      }
      catch (error) {
        setTimeout(async () => {
          var _a;
          this.editorJs.blocks.render(((_a = state.draftNote) === null || _a === void 0 ? void 0 : _a.editor) || {});
        }, 1000);
      }
    }
    setInterval(() => {
      state.draftNote = { ...state.draftNote, createdAt: new Date() };
    }, 60000);
  }
  render() {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
    return [
      (state === null || state === void 0 ? void 0 : state.navigationView) === "profile" && h("floodteam-profile", null),
      h("div", { id: "feed", style: {
          display: (state === null || state === void 0 ? void 0 : state.navigationView) === "feed" ? "block" : "none",
        } }, h("ion-grid", { class: "ion-no-padding" }, h("ion-row", { class: "ion-padding" }, h("ion-col", null, h("floodteam-title-bar", null, h("ion-router-link", { href: "#" }, "Activity Feed"), h("ion-buttons", { slot: "end" }, h("ion-button", { style: {
          "--color": "rgba(var(--ion-text-color-rgb), 0.5)",
        }, onClick: (event) => this.fireenjinTrigger.emit({
          event,
          name: "filter",
          type: "feedType",
          payload: {
            control: {
              name: "type",
              label: "Type",
              icon: "help-circle",
              multiple: true,
              value: this.activityFilters,
              options: [
                {
                  label: "📝 Note",
                  value: "note",
                  group: "Type",
                },
                {
                  label: "✒️ Contract",
                  value: "contract",
                  group: "Type",
                },
                {
                  label: "📧 Email",
                  value: "email",
                  group: "Type",
                },
                {
                  label: "My Feed",
                  value: "me",
                  group: "Location",
                },
                ...(state.locations || [])
                  .filter((location) => {
                  var _a, _b;
                  return ((_a = state === null || state === void 0 ? void 0 : state.claims) === null || _a === void 0 ? void 0 : _a.admin) ||
                    ((_b = state === null || state === void 0 ? void 0 : state.claims) === null || _b === void 0 ? void 0 : _b.locationId) === (location === null || location === void 0 ? void 0 : location.id);
                })
                  .map(({ name: label, id }) => ({
                  label,
                  value: `location-${id}`,
                  group: "Location",
                })),
              ],
            },
          },
        }), fill: "outline", size: "small" }, "Filter", h("ion-icon", { slot: "end", name: "funnel" })))))), h("ion-row", null, h("ion-col", null, h("ion-card", { style: {
          overflow: "visible",
          padding: "1rem",
          position: "relative",
          zIndex: "9",
        } }, h("floodteam-template", { disablePosition: true, disableFrame: true, class: "feed-card-header", templateId: "a6PugONYo4E8EBq81RnM", style: {
          display: "block",
        }, data: {
          icon: ((_a = state === null || state === void 0 ? void 0 : state.profile) === null || _a === void 0 ? void 0 : _a.photo) ||
            `https://avatars.dicebear.com/api/initials/${((_d = (_c = (_b = state === null || state === void 0 ? void 0 : state.profile) === null || _b === void 0 ? void 0 : _b.firstName) === null || _c === void 0 ? void 0 : _c.charAt) === null || _d === void 0 ? void 0 : _d.call(_c, 0)) || ""}${((_g = (_f = (_e = state === null || state === void 0 ? void 0 : state.profile) === null || _e === void 0 ? void 0 : _e.lastName) === null || _f === void 0 ? void 0 : _f.charAt) === null || _g === void 0 ? void 0 : _g.call(_f, 0)) || ""}.svg`,
          badge: true
            ? `📝`
            : `<ion-toggle name="sendAlert" style="position: relative;" color="warning"></ion-toggle> 🔔`,
          badgeStyle: "font-size: 24px; cursor: pointer !important; display: flex; align-items: center; justify-content: end;",
          subtextStyle: "opacity: 0.6",
          subject: `${((_h = state === null || state === void 0 ? void 0 : state.profile) === null || _h === void 0 ? void 0 : _h.firstName) || ""} ${((_j = state === null || state === void 0 ? void 0 : state.profile) === null || _j === void 0 ? void 0 : _j.lastName) || ""}`,
          createdAt: (_k = state === null || state === void 0 ? void 0 : state.draftNote) === null || _k === void 0 ? void 0 : _k.createdAt,
        } }), h("fireenjin-form", { style: { padding: "0 10px" }, name: "note", endpoint: "addNote", beforeSubmit: async (data) => {
          var _a, _b;
          return ({
            ...state.draftNote,
            ...data,
            jobId: (_a = state === null || state === void 0 ? void 0 : state.job) === null || _a === void 0 ? void 0 : _a.id,
            userId: (_b = state === null || state === void 0 ? void 0 : state.user) === null || _b === void 0 ? void 0 : _b.id,
          });
        }, submitButton: "Send", resetButton: "Clear", resetButtonColor: "medium", disableEnterButton: true }, h("fireenjin-editor", { uploadCallback: (event) => this.onPhotoUpload(event), partials: state.templates, ref: (el) => (this.editorEl = el) })))))), h("fireenjin-pagination", { name: "activity-feed", id: "activity-feed", disableVirtualScroll: true, disablePageCheck: true, display: "grid", ref: (el) => (this.feedPaginationEl = el), fetchData: state === null || state === void 0 ? void 0 : state.feedFetchData, gridEl: ({ result }) => (h("ion-card", { innerHTML: result === null || result === void 0 ? void 0 : result.html })), endpoint: "listFeeds", limit: 20, resultsKey: "feeds" })),
      (state === null || state === void 0 ? void 0 : state.navigationView) === "pins" && (h("ion-reorder-group", { id: "pins", onIonItemReorder: (ev) => this.doReorder(ev), disabled: false }, ((state === null || state === void 0 ? void 0 : state.pins) || []).map((pin) => (h("ion-item", { style: { "--background": "transparent" }, "data-id": pin.id }, h("ion-buttons", { slot: "start" }, h("ion-button", { onClick: () => this.fireenjinTrigger.emit({
          name: "pin",
          payload: pin,
        }) }, h("ion-icon", { name: "pin", color: "primary" })), h("ion-icon", { name: pin === null || pin === void 0 ? void 0 : pin.icon, class: "ft-icon-style" })), h("ion-label", null, (pin === null || pin === void 0 ? void 0 : pin.name) || "No Label"), h("ion-reorder", { slot: "end" })))))),
      h("ion-list", { style: { background: "transparent" } }, h("div", { style: {
          display: ((_l = state === null || state === void 0 ? void 0 : state.session) === null || _l === void 0 ? void 0 : _l.uid) ? "none" : "block",
        } }, h("slot", null)), (state === null || state === void 0 ? void 0 : state.navigationView) === "menu" &&
        this.items.map((item) => {
          var _a, _b, _c, _d;
          return ((_a = item === null || item === void 0 ? void 0 : item.permissionCheck) === null || _a === void 0 ? void 0 : _a.call(item)) ? (h("ion-menu-toggle", { autoHide: false }, h("ion-item", { style: { "--background": "transparent" }, title: (item === null || item === void 0 ? void 0 : item.title) || (item === null || item === void 0 ? void 0 : item.name), href: (item === null || item === void 0 ? void 0 : item.href) || "#" }, h("ion-icon", { slot: "start", class: "ft-icon-style", name: item === null || item === void 0 ? void 0 : item.icon, color: "primary" }), h("ion-label", null, (item === null || item === void 0 ? void 0 : item.name) || ""), h("ion-buttons", { slot: "end" }, (item === null || item === void 0 ? void 0 : item.add) && (h("ion-button", { fill: "clear", onClick: (event) => event.stopPropagation(), href: item.add }, h("ion-icon", { name: "add-circle", slot: "icon-only", color: "primary" }))), h("ion-button", { fill: "clear", onClick: (event) => this.toggleNavPin(event, item) }, h("ion-icon", { name: "pin", slot: "icon-only", color: ((_d = (_c = (_b = state === null || state === void 0 ? void 0 : state.pins) === null || _b === void 0 ? void 0 : _b.map) === null || _c === void 0 ? void 0 : _c.call(_b, (pin) => pin === null || pin === void 0 ? void 0 : pin.href)) === null || _d === void 0 ? void 0 : _d.includes(item === null || item === void 0 ? void 0 : item.href))
              ? "primary"
              : null })))))) : null;
        })),
    ];
  }
  static get is() { return "floodteam-navigation-menu"; }
  static get states() {
    return {
      "activityFilters": {}
    };
  }
  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"
            }
          }
        }
      }, {
        "method": "fireenjinSubmit",
        "name": "fireenjinSubmit",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": ""
        },
        "complexType": {
          "original": "FireEnjinSubmitEvent",
          "resolved": "FireEnjinSubmitEvent",
          "references": {
            "FireEnjinSubmitEvent": {
              "location": "import",
              "path": "@fireenjin/sdk"
            }
          }
        }
      }];
  }
  static get listeners() {
    return [{
        "name": "fireenjinTrigger",
        "method": "onTrigger",
        "target": "document",
        "capture": false,
        "passive": false
      }, {
        "name": "ionInput",
        "method": "onSearchInput",
        "target": undefined,
        "capture": false,
        "passive": false
      }, {
        "name": "fireenjinSuccess",
        "method": "onFormFinish",
        "target": undefined,
        "capture": false,
        "passive": false
      }, {
        "name": "fireenjinReset",
        "method": "onFormFinish",
        "target": undefined,
        "capture": false,
        "passive": false
      }, {
        "name": "fireenjinChange",
        "method": "onEditorChange",
        "target": "body",
        "capture": false,
        "passive": false
      }];
  }
}
