<template>
  <v-row no-gutters class="w-100">
    <v-card class="w-100">
      <v-card-text>
        <v-btn
          block
          color="primary-button"
          :height="40"
          text="Scan QR Code"
          class="text-capitalize"
          disabled
          prepend-icon="mdi-qrcode"
        />
        <v-autocomplete
          v-model="selectedPass"
          v-model:search="passInput"
          :hide-no-data="false"
          class="mt-3"
          :items="passItems"
          :rules="props.passRules"
          item-title="prefixAndName"
          item-value="_id"
          label="Pass"
          variant="outlined"
          hide-details
          density="compact"
          persistent-hint
          small-chips
          :clearable="props.clearable"
        >
          <template v-slot:chip="{ props, item }">
            <v-chip
              v-if="selectedPass"
              v-bind="props"
              prepend-icon="mdi-card-bulleted-outline"
              :text="item.raw?.prefixAndName"
            ></v-chip>
          </template>
        </v-autocomplete>

        <template v-if="!props.hideKeys">
          <v-autocomplete
            v-model="selectedKeys"
            v-model:search="keyInput"
            :hide-no-data="false"
            class="mt-3"
            :items="keyItems"
            :rules="props.passRules"
            item-title="prefixAndName"
            item-value="_id"
            label="Keys"
            multiple
            variant="outlined"
            hide-details
            density="compact"
            persistent-hint
            small-chips
            :clearable="props.clearable"
          >
            <template v-slot:chip="{ props, item }">
              <v-chip
                v-if="selectedKeys.length > 0"
                v-bind="props"
                prepend-icon="mdi-key"
                :text="item.raw?.prefixAndName"
              ></v-chip>
            </template>
          </v-autocomplete>
        </template>

        <v-divider class="my-4 w-100" />

        <template v-if="selectedType">
          <v-number-input
            v-model="count"
            variant="outlined"
            :min="1"
            :precision="0"
            density="compact"
            :rules="countRules"
          />
        </template>
      </v-card-text>
    </v-card>
  </v-row>
</template>

<script setup lang="ts">
import type { PropType } from "vue";
import type { ValidationRule } from "vuetify/lib/types.mjs";
import usePassKey from "../composables/usePassKey";
import useKey from "../composables/useKey";

const props = defineProps({
  passRules: {
    type: Array as PropType<ValidationRule[]>,
    default: [],
  },
  countRules: {
    type: Array as PropType<ValidationRule[]>,
    default: [],
  },
  site: {
    type: String,
    required: true,
  },
  type: {
    type: String as PropType<TVisitorType>,
    required: true,
  },
  contractorType: {
    type: String,
    default: "",
  },
  hideKeys: {
    type: Boolean,
    default: false,
  },
  clearable: {
    type: Boolean,
    default: false,
  },
});

const pass = defineModel<TPassKeyPayload[]>("pass", { default: [] });
const keys = defineModel<TPassKeyPayload[]>("keys", { default: [] });
const selectedPass = ref<string>("");
const selectedKeys = ref<string[]>([]);
const passInput = ref("");
const keyInput = ref("");
const passItems = ref<TPassKey[]>([]);
const keyItems = ref<any[]>([]);
const selectedType = ref<"qr-pass" | "nfc-card">();
const count = ref(1);

const { getPassKeysByPageSearch } = usePassKey();

const typeItems = [
  {
    label: "QR Pass",
    value: "qr-pass",
  },
  {
    label: "NFC Card",
    value: "nfc-card",
  },
];

const passTypesComputed = computed(() => {
  if (props.type === "contractor") {
    if (props.contractorType === "property-agent") {
      return ["agent-pass"];
    } else {
      return ["contractor-pass"];
    }
  } else {
    return ["visitor-pass"];
  }
});

const {
  data: passesData,
  refresh: refreshPassesData,
  pending: fetchPassesPending,
} = await useLazyAsyncData("get-pass-keys", () => {
  return getPassKeysByPageSearch({
    search: passInput.value,
    page: 1,
    limit: 500,
    passTypes: passTypesComputed.value,
    sites: [props.site],
    statuses: ["Available"],
  });
});

watch(passesData, (data: any) => {
  passItems.value = data?.items || [];
});

const {
  data: keysData,
  refresh: refreshKeysData,
  pending: fetchKeysPending,
} = await useLazyAsyncData("get-keys", () => {
  return getPassKeysByPageSearch({
    search: keyInput.value,
    statuses: ["Available"],
    passTypes: ["pass-key"],
    page: 1,
    limit: 500,
    sites: [props.site],
  });
});

watch(keysData, (data: any) => {
  keyItems.value = data?.items || [];
});

watch(selectedPass, (newVal) => {
  pass.value = [{ keyId: newVal }];
});

watch(selectedKeys, (newVal) => {
  keys.value = newVal.map((key) => ({ keyId: key }));
});

//prevent negative value;
watch(count, (newCount) => {
  if (newCount < 1) {
    count.value = 1;
  }
});

onMounted(() => {
  if (pass.value.length > 0) {
    selectedPass.value = pass.value[0].keyId;
  }
  if (keys.value.length > 0) {
    selectedKeys.value = keys.value.map((k) => k.keyId);
  }
});
</script>

<style scoped></style>
