<template>
  <v-row no-gutters>
    <v-col cols="12" class="mb-2">
      <v-row no-gutters>
        <v-btn
          v-if="props.seatManagement !== 'index'"
          class="text-none"
          rounded="pill"
          variant="tonal"
          :to="{
            name: props.seatManagement,
            params: { organization: props.orgId },
          }"
          size="large"
        >
          Manage seats
        </v-btn>
      </v-row>
    </v-col>

    <v-col cols="12">
      <v-card width="100%" variant="outlined" border="thin" rounded="lg">
        <v-toolbar density="compact" color="grey-lighten-4">
          <template #prepend>
            <v-btn fab icon density="comfortable" @click="getAll()">
              <v-icon>mdi-refresh</v-icon>
            </v-btn>
          </template>

          <template #append>
            <v-row no-gutters justify="end" align="center">
              <span class="mr-2 text-caption text-font gray">
                {{ pageRange }}
              </span>
              <local-pagination
                v-model="page"
                :length="pages"
                @update:value="getAll()"
              />
            </v-row>
          </template>

          <template #extension>
            <v-tabs
              v-model="selectedStatus"
              color="primary"
              :height="40"
              @update:model-value="toRoute"
              class="w-100"
            >
              <v-tab
                v-for="(tab, i) in tabOptions"
                :value="tab.status"
                :key="i"
                class="text-capitalize"
              >
                {{ tab.name }}
              </v-tab>
            </v-tabs>
          </template>
        </v-toolbar>

        <v-data-table
          :headers="props.headers"
          :items="items"
          item-value="_id"
          items-per-page="20"
          fixed-header
          hide-default-footer
          style="max-height: calc(100vh - (126px))"
          :loading="loading"
        >
          <template #item.nature="{ item }">
            {{ replaceMatch(item.nature, "_", " ") }}
          </template>
          <template #item.action-table="{ item }">
            <v-menu
              v-if="
                (currentStatus === 'active' &&
                  (canSuspendMembers || canDeleteMembers)) ||
                (currentStatus === 'suspended' &&
                  (canActivateMembers || canDeleteMembers))
              "
              v-model="item.menuOpen"
              :close-on-content-click="false"
              offset-y
              width="150"
            >
              <template v-slot:activator="{ props }">
                <v-icon v-bind="props">mdi-dots-horizontal</v-icon>
              </template>
              <v-list>
                <v-list-item
                  v-if="props.assignRole"
                  @click="
                    setMember({
                      dialog: true,
                      mode: 'assign-role',
                      role: item,
                    })
                  "
                >
                  Assign Role
                </v-list-item>

                <v-list-item
                  v-if="currentStatus === 'active' && canSuspendMembers"
                  @click="openUpdateDialog(item._id, 'suspended')"
                >
                  Suspend
                </v-list-item>
                <v-list-item
                  v-if="currentStatus === 'suspended' && canActivateMembers"
                  @click="openUpdateDialog(item._id, 'active')"
                >
                  Activate
                </v-list-item>
                <v-list-item
                  v-if="canDeleteMembers"
                  @click="openUpdateDialog(item._id, 'deleted')"
                >
                  Delete
                </v-list-item>
              </v-list>
            </v-menu>
          </template>
        </v-data-table>
      </v-card>
    </v-col>
    <ConfirmDialog
      v-model="confirmDialog"
      :loading="updateLoading"
      @submit="handleUpdateMemberStatus"
    >
      <template #title>
        <span class="font-weight-medium text-h5">
          {{ updateActionText }} Member</span
        >
      </template>

      <template #description>
        <p class="text-subtitle-2">
          Are you sure you want to {{ updateActionText }} this Member? This
          action cannot be undone.
        </p>
      </template>

      <template #footer>
        <v-btn
          variant="text"
          @click="confirmDialog = false"
          :disabled="updateLoading"
        >
          Close
        </v-btn>
        <v-btn
          color="primary"
          variant="flat"
          @click="handleUpdateMemberStatus"
          :loading="updateLoading"
        >
          {{ updateActionText }} Member </v-btn
        >r
      </template>
    </ConfirmDialog>

    <Snackbar v-model="messageSnackbar" :text="message" :color="messageColor" />

    <v-dialog v-model="assignRoleDialog" max-width="400px">
      <v-card>
        <v-card-title class="text-h5">Assign Role</v-card-title>
        <v-card-text>
          <v-form v-model="memberRoleForm" @submit.prevent="updateMemberRole()">
            <v-row no-gutters>
              <v-col cols="12" class="mb-2">
                <v-row no-gutters>
                  <InputLabel class="text-capitalize" title="Name" required />
                  <v-col cols="12">
                    <v-select
                      v-model="selectedRole"
                      :items="roles"
                      item-value="_id"
                      item-title="name"
                      density="comfortable"
                      :rules="[requiredRule]"
                      :error-messages="
                        selectedRole === selectedMemberRole
                          ? 'Role already assigned'
                          : ''
                      "
                      persistent-hint
                    ></v-select>
                  </v-col>

                  <v-col cols="12" class="text-error text-center">
                    {{ message }}
                  </v-col>
                </v-row>
              </v-col>

              <v-col cols="12">
                <v-row>
                  <v-col cols="6">
                    <v-btn
                      block
                      variant="text"
                      @click="setMember({ mode: 'assign-role' })"
                    >
                      Cancel
                    </v-btn>
                  </v-col>
                  <v-col cols="6">
                    <v-btn
                      block
                      variant="flat"
                      color="black"
                      :disabled="!memberRoleForm"
                      type="submit"
                    >
                      Submit
                    </v-btn>
                  </v-col>
                </v-row>
              </v-col>
            </v-row>
          </v-form>
        </v-card-text>
      </v-card>
    </v-dialog>
  </v-row>
</template>

<script setup lang="ts">
const props = defineProps({
  orgId: {
    type: String,
    default: "",
  },
  customerId: {
    type: String,
    default: "",
  },
  siteId: {
    type: String,
    default: "",
  },
  status: {
    type: String,
    default: "active",
  },
  type: {
    type: String,
    default: "organization",
  },
  seatManagement: {
    type: String,
    default: "index",
  },
  inviteMember: {
    type: String,
    default: "index",
  },
  route: {
    type: String,
    default: "index",
  },
  canActivateMembers: {
    type: Boolean,
    default: false,
  },
  canSuspendMembers: {
    type: Boolean,
    default: false,
  },
  canDeleteMembers: {
    type: Boolean,
    default: false,
  },
  assignRole: {
    type: Boolean,
    default: false,
  },
  headers: {
    type: Array as PropType<Array<Record<string, string>>>,
    default: () => [
      {
        title: "Name",

        value: "name",
      },
      {
        title: "Role",

        value: "roleName",
      },
      {
        title: "Organization",

        value: "orgName",
      },
      {
        title: "Status",

        value: "status",
      },
      {
        title: "Action",
        value: "action-table",
      },
    ],
  },
});

const items = ref<Array<Record<string, any>>>([]);
const page = ref(1);
const pages = ref(10);
const pageRange = ref("-- - -- of --");

const message = ref("");
const messageSnackbar = ref(false);
const messageColor = ref("");

const {
  getAll: _getAll,
  updateMemberStatus: _updateMemberStatus,
  updateMemberRole: _updateMemberRole,
} = useMember();

const { headerSearch } = useLocal();
const { replaceMatch, setRouteParams, requiredRule } = useUtils();

const selectedStatus = ref(props.status);
const currentStatus = computed(() => selectedStatus.value || props.status);
const route = useRoute();
const routeName = (useRoute().name as string) ?? "";
const normalizedRouteParams = computed(() => {
  const params: Record<string, string> = {};
  Object.entries(route.params as Record<string, unknown>).forEach(
    ([key, value]) => {
      if (typeof value === "string") {
        params[key] = value;
      }
    }
  );
  return params;
});

const tabOptions = [
  { name: "Active", status: "active" },
  { name: "Suspended", status: "suspended" },
];

function toRoute(status: any) {
  const obj = tabOptions.find((x) => x.status === status);
  if (!obj) return;
  page.value = 1;
  navigateTo({
    name: routeName,
    params: setRouteParams(normalizedRouteParams.value, { status }),
  });
}

watch(
  () => props.status,
  (status) => {
    if (status && status !== selectedStatus.value) {
      selectedStatus.value = status;
    }
  },
  { immediate: true }
);

const {
  data: getAllReq,
  refresh: getAll,
  status: getAllReqStatus,
} = useAsyncData(
  `get-all-members-${props.type}-${props.orgId}-${props.siteId}-${props.status}`,
  () =>
    _getAll({
      status: props.status,
      org: props.orgId,
      search: headerSearch.value,
      page: page.value,
      type: props.type,
      siteId: props.siteId,
    }),
  {
    watch: [() => props.status, () => props.orgId, () => props.siteId, headerSearch],
  }
);

const loading = computed(() => getAllReqStatus.value === "pending");

watch(headerSearch, () => {
  page.value = 1;
});

watch([() => props.orgId, () => props.siteId], () => {
  page.value = 1;
});

watchEffect(() => {
  if (getAllReq.value) {
    items.value = getAllReq.value.items;
    pages.value = getAllReq.value.pages;
    pageRange.value = getAllReq.value.pageRange;
  }
});

const confirmDialog = ref(false);
const selectedMemberId = ref<string | null>(null);
const updateLoading = ref(false);
const updateAction = ref("");

const memberRoleForm = ref(false);
const assignRoleDialog = ref(false);
const selectedRole = ref<string | null>(null);
const selectedMemberRole = ref("");

function setMember({
  dialog = false,
  mode = "",
  role = {} as Record<string, any>,
} = {}) {
  if (mode === "assign-role") {
    assignRoleDialog.value = dialog;
  }

  selectedMemberId.value = role._id;
  selectedRole.value = role.role;
  selectedMemberRole.value = role.role;
}

const roles = ref<Array<Record<string, any>>>([]);
const { getRoles } = useRole();
const { data: getAllRoleReq } = useLazyAsyncData(`get-roles-${props.type}-${props.orgId}`, () =>
  getRoles({ org: props.orgId, type: props.type, limit: 20 })
);

watchEffect(() => {
  if (getAllRoleReq.value) {
    roles.value = getAllRoleReq.value.items;
  }
});

watchEffect(() => {
  if (selectedRole.value) {
    message.value = "";
  }
});

async function updateMemberRole() {
  try {
    await _updateMemberRole(
      selectedMemberId.value ?? "",
      selectedRole.value ?? "",
      props.type,
      props.orgId
    );
    await setMember({ mode: "assign-role" });
    await getAll();
  } catch (error: any) {
    message.value = error?.response?._data?.message || "Failed to update role";
  }
}

function openUpdateDialog(id: string, action: string) {
  updateAction.value = action;
  selectedMemberId.value = id;
  confirmDialog.value = true;
}

function showMessage(msg: string, color: string) {
  message.value = msg;
  messageColor.value = color;
  messageSnackbar.value = true;
}

async function handleUpdateMemberStatus() {
  if (!selectedMemberId.value) return;
  updateLoading.value = true;
  try {
    const res = await _updateMemberStatus(
      selectedMemberId.value,
      updateAction.value
    );

    confirmDialog.value = false;
    showMessage(res.message, "success");
    getAll();
  } catch (error: any) {
    const errorMessage = error?.response?._data?.message;
    showMessage(errorMessage, "error");
  } finally {
    updateLoading.value = false;
    selectedMemberId.value = null;
  }
}
const updateActionText = computed(() => {
  const map: Record<string, string> = {
    active: "Activate",
    suspended: "Suspend",
    deleted: "Delete",
  };
  return map[updateAction.value] || updateAction.value;
});
</script>
