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

          <template #append>
            <v-btn
              variant="flat"
              color="primary"
              class="text-none"
              @click="dialogAdd = true"
            >
              Add
            </v-btn>
          </template>
        </v-toolbar>

        <v-card-text class="pa-0">
          <v-data-table
            :headers="headers"
            :items="items"
            fixed-header
            hide-default-footer
            @click:row="handleRowClick"
            style="max-height: 300px"
          >
          </v-data-table>
        </v-card-text>

        <v-toolbar density="compact" color="grey-lighten-4">
          <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="$emit('update:value', $event)"
              />
            </v-row>
          </template>
        </v-toolbar>
      </v-card>
    </v-col>

    <!-- Add Dialog -->
    <v-dialog v-model="dialogAdd" persistent width="450">
      <NFCTagForm
        title="Add NFC Tag"
        :site="props.site"
        :org-id="props.orgId"
        @cancel="dialogAdd = false"
        @success="handleSuccess"
        @error="handleError"
      />
    </v-dialog>

    <!-- Edit Dialog -->
    <v-dialog v-model="dialogEdit" persistent width="450">
      <NFCTagForm
        title="Edit NFC Tag"
        :site="props.site"
        :org-id="props.orgId"
        @cancel="dialogEdit = false"
        @success="handleSuccess"
        @error="handleError"
        mode="edit"
        :nfc-tag="selectedTag"
      />
    </v-dialog>

    <!-- Preview Dialog -->
    <v-dialog v-model="dialogPreview" persistent width="540">
      <v-card width="100%">
        <v-toolbar>
          <v-row no-gutters class="fill-height px-6" align="center">
            <span class="font-weight-bold text-h5 text-capitalize">
              NFC Tag Details
            </span>
          </v-row>
        </v-toolbar>

        <v-card-text
          style="max-height: 100vh; overflow-y: auto"
          class="pa-5 my-5 px-7"
        >
          <v-row no-gutters>
            <v-col cols="12" class="mb-2">
              Name:
              <span class="font-weight-bold">
                {{ selectedTag.name }}
              </span>
            </v-col>

            <v-col cols="12" class="mb-2">
              Tag ID:
              <span class="font-weight-bold">
                {{ selectedTag.tagID }}
              </span>
            </v-col>

          
          </v-row>
        </v-card-text>

        <v-toolbar class="pa-0" density="compact">
          <v-row no-gutters>
            <v-col cols="6" class="pa-0">
              <v-btn
                block
                variant="text"
                class="text-none"
                size="large"
                @click="dialogPreview = false"
                height="48"
              >
                Close
              </v-btn>
            </v-col>

            <v-col cols="6" class="pa-0">
              <v-menu>
                <template #activator="{ props }">
                  <v-btn
                    block
                    variant="flat"
                    color="black"
                    class="text-none"
                    height="48"
                    v-bind="props"
                    tile
                  >
                    More actions
                  </v-btn>
                </template>

                <v-list class="pa-0">
                  <v-list-item @click="openDialogEdit()">
                    <v-list-item-title class="text-subtitle-2">
                      Edit NFC Tag
                    </v-list-item-title>
                  </v-list-item>

                  <v-list-item @click="openDialogDelete()" class="text-red">
                    <v-list-item-title class="text-subtitle-2">
                      Delete NFC Tag
                    </v-list-item-title>
                  </v-list-item>
                </v-list>
              </v-menu>
            </v-col>
          </v-row>
        </v-toolbar>
      </v-card>
    </v-dialog>

    <!-- Delete Dialog -->
    <v-dialog v-model="dialogDelete" persistent width="540">
      <v-card width="100%">
        <v-card-text
          style="max-height: 100vh; overflow-y: auto"
          class="pa-5 my-5 px-7 text-center"
        >
          Are you sure you want to delete this NFC Tag?
        </v-card-text>

        <v-toolbar class="pa-0" density="compact">
          <v-row no-gutters>
            <v-col cols="6" class="pa-0">
              <v-btn
                block
                variant="text"
                class="text-none"
                size="large"
                tile
                @click="dialogDelete = false"
                height="48"
              >
                Cancel
              </v-btn>
            </v-col>

            <v-col cols="6" class="pa-0">
              <v-btn
                block
                tile
                variant="flat"
                class="text-none"
                size="large"
                height="48"
                color="black"
                @click="submitDelete()"
              >
                Delete
              </v-btn>
            </v-col>
          </v-row>
        </v-toolbar>
      </v-card>
    </v-dialog>

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

<script setup lang="ts">

import useNFCPatrolTag from "../../composables/useNFCPatrolTag";

const events = defineEmits(["update:value", "row-click"]);

const props = defineProps({
  site: {
    type: String,
    required: true,
  },
  siteName: {
    type: String,
    default: "",
  },
  orgId: {
    type: String,
    required: true,
  },
  headers: {
    type: Array as PropType<Array<any>>,
    default: () => [
      { title: "ID", value: "tagID" },
      { title: "Name", value: "name" },
      { title: "Status", value: "status" },
    ],
  },
});

const items = ref<Array<any>>([]);
const page = ref(1);
const pages = ref(0);
const pageRange = ref("1-20 of 1");

const { getAll: getAllNFCTags, deleteById: deleteNFCTagById } = useNFCPatrolTag();

const { data: getNFCTagReq, refresh: getNFCTagRefresh } = await useLazyAsyncData(
  `get-nfc-tags-${props.site}`,
  () => getAllNFCTags({ site: props.site, page: page.value }),
  {
    watch: [page],
  }
);

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

const dialogAdd = ref(false);
const dialogEdit = ref(false);
const dialogPreview = ref(false);
const dialogDelete = ref(false);

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

function openDialogEdit() {
  dialogEdit.value = true;

  if (dialogPreview.value) dialogPreview.value = false;
}

function openDialogDelete() {
  dialogDelete.value = true;

  if (dialogPreview.value) dialogPreview.value = false;
}

function handleSuccess() {
  if (dialogAdd.value) {
    dialogAdd.value = false;
    showMessage("NFC Tag created successfully!", "success");
  }

  if (dialogEdit.value) {
    dialogEdit.value = false;
    showMessage("NFC Tag updated successfully!", "success");
  }

  if (dialogPreview.value) dialogPreview.value = false;

  if (dialogDelete.value) dialogDelete.value = false;

  getNFCTagRefresh();
}

function handleError(error: any) {
  const errorMessage = error?.data?.message || error?.message || "An error occurred";
  showMessage(errorMessage, "error");
}

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

const selectedTag = ref<any>({
  name: "",
  tagID: "",
  status: "active",
});

function handleRowClick(_: any, data: any) {
  dialogPreview.value = true;
  selectedTag.value = JSON.parse(JSON.stringify(data.item));
}

async function submitDelete() {
  try {
    await deleteNFCTagById(selectedTag.value._id ?? "");
    await getNFCTagRefresh();
    dialogDelete.value = false;
    showMessage("NFC Tag deleted successfully!", "success");
  } catch (error) {
    console.error("Error deleting NFC tag:", error);
    handleError(error);
  }
}
</script>
