<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="getCameraRefresh()">
              <v-icon>mdi-refresh</v-icon>
            </v-btn>
          </template>

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

        <v-card-text class="pa-0 bg-red">
          <v-data-table
            :headers="computedHeaders"
            :items="items"
            fixed-header
            hide-default-footer
            hide-default-header
            @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>

    <!-- dialog -->
    <v-dialog v-model="dialogAdd" persistent width="450">
      <CameraForm
        title="Add Camera"
        :site="prop.site"
        :guard-posts="prop.guardPosts"
        :type="prop.type"
        @cancel="dialogAdd = false"
        @success="handleSuccess"
        @error="handleError"
      />
    </v-dialog>

    <v-dialog v-model="dialogEdit" persistent width="450">
      <CameraForm
        title="Edit Camera"
        :site="prop.site"
        :guard-posts="prop.guardPosts"
        :type="prop.type"
        @cancel="dialogEdit = false"
        @success="handleSuccess"
        @error="handleError"
        mode="edit"
        :camera="camera"
      />
    </v-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">
              Preview
            </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 v-if="camera.type === 'ip'" cols="12" class="mb-2">
              Camera Name:
              <span class="font-weight-bold">
                {{ camera.name }}
              </span>
            </v-col>
            <v-col cols="12" class="mb-2">
              Host:
              <span class="font-weight-bold">
                {{ camera.host }}
              </span>
            </v-col>

            <v-col v-if="camera.type === 'anpr'" cols="12" class="mb-2">
              Username:
              <span class="font-weight-bold">
                {{ camera.username }}
              </span>
            </v-col>

            <v-col v-if="camera.type === 'anpr'" cols="12" class="mb-2">
              Password:
              <span class="font-weight-bold">
                {{ camera.password }}
              </span>
            </v-col>

            <v-col cols="12" class="mb-2">
              Type:
              <span class="font-weight-bold">
                {{ camera.type }}
              </span>
            </v-col>

            <v-col cols="12" class="mb-2">
              Category:
              <span class="font-weight-bold">
                {{ camera.category }}
              </span>
            </v-col>

            <v-col v-if="camera.type === 'anpr'" cols="12" class="mb-2">
              Direction:
              <span class="font-weight-bold">
                {{ camera.direction }}
              </span>
            </v-col>

            <v-col v-if="camera.type === 'anpr'" cols="12">
              Guard House:
              <span class="font-weight-bold">
                {{ camera.guardPost }}
              </span>
            </v-col>
          </v-row>
        </v-card-text>

        <v-toolbar class="pa-0" density="compact">
          <v-row no-gutters>
            <v-col :cols="prop.readOnly ? 12 : 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 v-if="!prop.readOnly" 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
                    </v-list-item-title>
                  </v-list-item>

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

    <Snackbar
      v-model="messageSnackbar"
      :text="message"
      :color="messageColor"
      style="z-index: 3000"
    />

    <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 want to delete this {{ camera.type }} camera?
        </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>
  </v-row>
</template>

<script setup lang="ts">
import type { PropType } from "vue";
import useSiteSettings from "../composables/useSiteSettings";

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

const prop = defineProps({
  site: {
    type: String,
    required: true,
    default: "site",
  },
  type: {
    type: String as PropType<TSiteCamera["type"]>,
    default: "anpr",
  },
  guardPosts: {
    type: Number,
    default: 0,
  },
  headers: {
    type: Array as PropType<Array<any>>,
    default: () => [
      { text: "Host", value: "host" },
      { text: "Category", value: "category" },
      { text: "Guard House", value: "guardPost" },
      { text: "Actions", value: "action", sortable: false },
    ],
  },
  readOnly: {
    type: Boolean,
    default: false,
  },
});

const computedHeaders = computed(() => {
  if (prop.type === "ip") {
    const base = [...prop.headers];
    base.splice(0, 0, { text: "Name", value: "name" });
    return base;
  }
  return prop.headers;
});

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

const { getAllSiteCameras, deleteSiteCameraById } = useSiteSettings();
const { data: getCameraReq, refresh: getCameraRefresh } =
  await useLazyAsyncData(
    `get-site-${prop.site}-${prop.type}-cameras`,
    () =>
      getAllSiteCameras({ site: prop.site, type: prop.type, page: page.value }),
    {
      watch: [page],
    }
  );

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

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

const messageSnackbar = ref(false);
const message = ref("");
const messageColor = ref<"success" | "error" | "info">();

function showMessage(text: string, type: "success" | "error" | "info") {
  messageSnackbar.value = true;
  message.value = text;
  messageColor.value = type;
}

function openDialogEdit() {
  dialogEdit.value = true;

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

function openDialogDelete() {
  dialogDelete.value = true;

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

function handleError(msg: string) {
  const text = prop.type === "ip" ? "CCTV camera already exist" : msg;
  showMessage(text, "error");
}

function handleSuccess() {
  if (dialogAdd.value) dialogAdd.value = false;

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

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

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

  getCameraRefresh();
}

const camera = ref<TSiteCamera>({
  site: "",
  host: "",
  username: "",
  password: "",
  type: "ip",
  category: "standard",
  direction: "none",
  guardPost: null,
  status: "active",
});

function handleRowClick(_: any, data: any) {
  console.log("row clicked", data.item);
  dialogPreview.value = true;
  camera.value = JSON.parse(JSON.stringify(data.item));
}

async function submitDelete() {
  try {
    await deleteSiteCameraById(camera.value._id ?? "");
    await getCameraRefresh();
    dialogDelete.value = false;
  } catch (error: any) {
    showMessage(
      error?.response?._data?.message || "Failed to delete camera.",
      "error"
    );
  }
}
</script>
