<template>
  <v-row no-gutters>
    <v-col cols="12" class="mb-2">
      <v-row no-gutters>
        <v-btn
          class="text-none mr-2"
          rounded="pill"
          variant="tonal"
          size="large"
          @click="inviteMember()"
          v-if="props.inviteMember"
        >
          Invite member
        </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="getVerifications()"
            >
              <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-fontgray">
                {{ pageRange }}
              </span>
              <local-pagination
                v-model="page"
                :length="pages"
                @update:value="getVerifications"
              />
            </v-row>
          </template>

          <template #extension>
            <v-tabs>
              <v-tab
                :to="{
                  name: props.route,
                  params: { status: 'pending' },
                }"
              >
                Pending
              </v-tab>
              <v-tab
                :to="{
                  name: props.route,
                  params: { status: 'expired' },
                }"
              >
                Expired
              </v-tab>
            </v-tabs>
          </template>
        </v-toolbar>

        <v-data-table
          :headers="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.permissions="{ value }">
            <span class="text-caption font-weight-bold text-capitalize">
              permissions
            </span>
            <v-chip>{{ value.length }}</v-chip>
          </template>
          <template #item.createdAt="{ item }">
            {{ item.createdAt ? formatDate(item.createdAt) : "" }}
          </template>
          <template #item.action-table="{ item }">
            <v-menu
              :close-on-content-click="false"
              offset-y
              width="150"
              v-if="props.cancelInvitation"
            >
              <template v-slot:activator="{ props }">
                <v-icon v-bind="props">mdi-dots-horizontal</v-icon>
              </template>
              <v-list>
                <v-list-item @click="openConfirmDialog(item._id ?? '')" v-if="item.status === 'pending'">
                  Cancel Invite
                </v-list-item>
              </v-list>
            </v-menu>
          </template>
        </v-data-table>
      </v-card>
    </v-col>

    <ConfirmDialog
      v-model="confirmDialog"
      :loading="cancelLoading"
      @submit="onConfirmCancel"
    >
      <template #title>
        <span class="font-weight-medium text-h5">Cancel Invitation</span>
      </template>
      <template #description>
        <p class="text-subtitle-2">
          Are you sure you want to cancel this invitation? This action cannot be
          undone.
        </p>
      </template>
      <template #footer>
        <div class="d-flex justify-center ga-3 w-100">
          <v-btn
            variant="text"
            @click="confirmDialog = false"
            :disabled="cancelLoading"
          >
            Close
          </v-btn>
          <v-btn
            color="primary"
            variant="flat"
            @click="onConfirmCancel"
            :loading="cancelLoading"
          >
            Cancel Invite
          </v-btn>
        </div>
      </template>
    </ConfirmDialog>
    <Snackbar v-model="messageSnackbar" :text="message" :color="messageColor" />

    <v-dialog v-model="dialogMember" max-width="450">
      <InvitationForm
        title="Invite member"
        :org="org"
        @cancel="dialogMember = false"
        @success="handleSuccess"
        @invited="getVerifications()"
        :app="props.app"
      />
    </v-dialog>
  </v-row>
</template>

<script setup lang="ts">
const props = defineProps({
  app: {
    type: String,
    default: "organization",
  },
  route: {
    type: String,
    default: "index",
  },
  org: {
    type: String,
    default: "",
  },
  customerId: {
    type: String,
    default: "",
  },
  siteId: {
    type: String,
    default: "",
  },
  status: {
    type: String,
    default: "pending",
  },
  cancelInvitation: {
    type: Boolean,
    default: true,
  },
  inviteMember: {
    type: Boolean,
    default: true,
  },
  viewInvitations: {
    type: Boolean,
    default: true,
  },
});

const { authenticate } = useLocalAuth();
authenticate();

const headers = computed(() => {
  const baseHeaders = [
    {
      title: "Date",
      value: "createdAt",
    },
    {
      title: "E-mail",
      value: "email",
    },
  ];

  if (props.status === "pending" && props.cancelInvitation) {
    baseHeaders.push({
      title: "Action",
      value: "action-table",
    });
  }

  return baseHeaders;
});

const { getVerifications: _getVerifications, cancelUserInvitation } =
  useVerification();

const page = ref(1);
const pages = ref(0);
const pageRange = ref("-- - -- of --");

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

const items = ref<Array<TMiniVerification>>([]);
const { headerSearch } = useLocal();
const { formatDate } = useUtils();

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

const {
  data: getVerificationsReq,
  refresh: getVerifications,
  status: getVerificationsStatus,
} = useLazyAsyncData<{
  items: TMiniVerification[];
  pages: number;
  pageRange: string;
}>(
  `get-verifications-${props.app}-${props.org}-${props.siteId}-${props.status}`,
  () =>
    _getVerifications({
      page: page.value,
      status: props.status,
      search: headerSearch.value,
      type: "user-invite,member-invite",
      app: props.app,
      orgId: props.org,
      siteId: props.siteId,
    }),
  {
    watch: [() => props.status]
  }
);

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

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

watch([headerSearch, () => props.status], () => {
  page.value = 1;
  getVerifications();
});

const confirmDialog = ref(false);
const selectedInviteId = ref<string | null>(null);
const cancelLoading = ref(false);

function openConfirmDialog(id: string) {
  selectedInviteId.value = id;
  confirmDialog.value = true;
}

async function onConfirmCancel() {
  if (!selectedInviteId.value) return;

  cancelLoading.value = true;
  try {
    const res = await cancelUserInvitation(selectedInviteId.value);

    showMessage(res.message || "Invitation cancelled successfully", "success");
    await getVerifications();
    confirmDialog.value = false;
    selectedInviteId.value = null;
  } catch (error: any) {
    showMessage(error?.message || "Failed to cancel invitation", "error");
  }
  cancelLoading.value = false;
}

function handleSuccess(closeForm: boolean) {
  getVerifications();
  if (closeForm) {
    dialogMember.value = false;
  }
}

watchEffect(() => {
  if (!props.viewInvitations) {
    useRouter().back();
  }
});

const dialogMember = ref(false);

function inviteMember() {
  dialogMember.value = true;
}
</script>
