<template>
  <v-skeleton-loader
    type="card"
    :width="'100%'"
    :height="'200px'"
    v-if="loading"
  />
  <v-row no-gutters class="" v-if="!loading">
    <v-col cols="12" elevation="3" class="border">
      <v-row no-gutters class="px-6 pt-4">
        <!-- <div class="d-flex mt-7 pb-5">
          <p class="mr-6 font-weight-medium flex-grow-1">
            Physical / Key Pass
            <span class="d-block text-caption text-grey-darken-1 mt-1">
              A Physical Pass Card is a tangible identification or access card
              used for entry and verification purposes at a specific site or
              property. Its primary functions include granting authorized
              access, enhancing security, and tracking attendance or movement.
            </span>
          </p>
          <v-switch
            color="success"
            hide-details
            v-model="currentEntryPassSettings.physicalPass"
            @update:modelValue="updateEntryPassSettingsPhysicalPass()"
          ></v-switch>
        </div>
        <v-divider thickness="1"></v-divider> -->
        <div class="d-flex mt-7 pb-5 pr-5">
          <p class="mr-6 font-weight-medium flex-grow-1">
            NFC / QR Code Pass
            <span class="d-block text-caption text-grey-darken-1 mt-1">
              NFC Card Pass is a type of access card that uses Near Field
              Communication (NFC) technology to enable secure and convenient
              entry to a site or property. This technology facilitates wireless
              communication between the card and an NFC reader when they are
              placed in close proximity (typically within 4 cm).
            </span>
          </p>
          <v-switch
            color="success"
            hide-details
            v-model="currentEntryPassSettings.nfcPass"
            @update:modelValue="updateEntryPassSettingsNfcPass()"
          ></v-switch>
        </div>
        <v-divider thickness="1"></v-divider>
        <div class="d-flex w-100 mt-7 pb-10">
          <p class="font-weight-medium flex-grow-1">
            Upload Access Cards Template
            <span class="d-block text-caption text-grey-darken-1 mt-1">
              <a
                v-if="currentEntryPassSettings.template?.id"
                href="#"
                class="text-truncate d-flex items-center text-decoration-none"
                @click.prevent="downloadTemplate"
              >
                <v-icon class="mr-2" size="24px">mdi-paperclip</v-icon>
                {{ currentEntryPassSettings.template.name }}
              </a>
            </span>
          </p>
          <div class="d-flex align-center" style="margin-left: auto; gap: 8px">
            <v-btn
              v-if="!currentEntryPassSettings.template?.id"
              variant="flat"
              color="primary"
              size="small"
              style="height: 40px"
              prepend-icon="mdi-tray-arrow-up"
              :loading="uploadingTemplate"
              @click="triggerTemplateUpload"
            >
              Upload
            </v-btn>
            <v-btn
              v-if="currentEntryPassSettings.template?.id"
              variant="flat"
              color="error"
              size="small"
              style="height: 40px"
              prepend-icon="mdi-file-document-remove-outline"
              :loading="uploadingTemplate"
              @click="removeTemplate"
            >
              Remove
            </v-btn>
          </div>
          <input
            type="file"
            ref="templateFileInput"
            accept=".xlsx,.xls"
            style="display: none"
            @change="handleTemplateUpload"
          />
        </div>
        <v-divider thickness="1"></v-divider>
        <div class="d-flex w-100 mt-7 pb-10">
          <p class="font-weight-medium flex-grow-1">
            Printer Setup
            <v-col cols="12">
              <v-row align="center">
                <v-col cols="3">
                  <v-text-field
                    label="Vendor ID"
                    hide-details
                    clearable
                    v-model="currentEntryPassSettings.printerVendorId"
                  ></v-text-field>
                </v-col>
                <v-col cols="3">
                  <v-text-field
                    label="Product ID"
                    hide-details
                    clearable
                    v-model="currentEntryPassSettings.printerProductId"
                  ></v-text-field>
                </v-col>
                <v-col cols="3" class="d-flex align-end">
                  <v-btn
                    color="primary"
                    variant="outlined"
                    prepend-icon="mdi-magnify"
                    block
                    height="48"
                    :loading="scanningPrinter"
                    @click="scanPrinter()"
                  >
                    Scan Printer
                  </v-btn>
                </v-col>
                <v-col cols="3" class="d-flex align-end pr-0">
                  <v-btn
                    color="success"
                    variant="outlined"
                    prepend-icon="mdi-printer-check"
                    block
                    height="48"
                    :loading="testingPrinter"
                    @click="testAndPrint()"
                  >
                    Test & Print
                  </v-btn>
                </v-col>
              </v-row>
              <v-row class="mt-4">
                <v-col cols="12" md="3">
                  <v-btn
                    color="primary"
                    variant="flat"
                    prepend-icon="mdi-printer"
                    block
                    @click="savePrinterSettings()"
                  >
                    Save Settings
                  </v-btn>
                </v-col>
              </v-row>
            </v-col>
          </p>
        </div>

        <v-divider thickness="1"></v-divider>

        <div class="d-flex w-100 mt-7 pb-10">
          <p class="font-weight-medium flex-grow-1">
            QR Code Template
            <span class="d-block text-caption text-grey-darken-1 mt-1">
              <v-col cols="12">
                <v-row>
                  <v-col cols="12" class="pr-0">
                    <v-text-field
                      label="Header"
                      placeholder="Enter QR code header"
                      hide-details
                      density="comfortable"
                      clearable
                      v-model="currentEntryPassSettings.qrCodeTemplateHeader"
                    ></v-text-field>
                  </v-col>
                  <v-col cols="12" class="pr-0">
                    <v-text-field
                      label="Subtext"
                      placeholder="Enter qr code sub header"
                      hide-details
                      density="comfortable"
                      clearable
                      class="mb-2"
                      v-model="
                        currentEntryPassSettings.qrCodeTemplateHeaderSubText
                      "
                    ></v-text-field>
                  </v-col>
                  <v-row class="mt-3">
                    <v-col cols="12" md="3">
                      <v-btn color="success" variant="flat" prepend-icon="mdi-eye" block @click="isShowTemplatePreview = true">
                        Preview
                      </v-btn>
                    </v-col>
                    <v-col cols="12" md="3">
                      <v-btn
                        color="primary"
                        variant="flat"
                        prepend-icon="mdi-qrcode"
                        block
                        @click="saveQrCodeTemplate()"
                      >
                        Save
                      </v-btn>
                    </v-col>
                  </v-row>
                </v-row>
              </v-col>
            </span>
          </p>
        </div>

        <v-divider thickness="1"></v-divider>

        <div class="d-flex w-100 mt-7 pb-10">
          <p class="font-weight-medium flex-grow-1">
            QR Code Validity
            <span class="d-block text-caption text-grey-darken-1 mt-1">
              Set how long a generated QR code remains valid before it expires.
            </span>
            <v-col cols="12" class="pr-0 mt-3">
              <v-row no-gutters>
                <v-col cols="12" md="4" class="mb-5">
                  <v-text-field
                    label="Validity (minutes)"
                    placeholder="e.g. 30"
                    hide-details
                    density="comfortable"
                    clearable
                    type="number"
                    min="1"
                    v-model.number="currentEntryPassSettings.qrCodeValidityMinutes"
                  ></v-text-field>
                </v-col>
              </v-row>
              <v-row>
                <v-col cols="12" md="3">
                  <v-btn
                    color="primary"
                    variant="flat"
                    prepend-icon="mdi-timer-outline"
                    block
                    @click="saveQrCodeValidity()"
                  >
                    Save
                  </v-btn>
                </v-col>
              </v-row>
            </v-col>
          </p>
        </div>

        <v-divider thickness="1"></v-divider>

        <div class="d-flex w-100 mt-7 pb-10">
          <p class="font-weight-medium flex-grow-1">
            Resident-app Disclaimer Message
            <span class="d-block text-caption text-grey-darken-1 mt-1">
              <v-col cols="12" class="pr-0">
                <v-row no-gutters>
                  <v-col cols="12" class="mb-5">
                    <v-textarea
                      label="Disclaimer Message"
                      placeholder="Enter disclaimer message for resident app"
                      hide-details
                      density="comfortable"
                      clearable
                      rows="5"
                      auto-grow
                      v-model="currentEntryPassSettings.disclaimerMessage"
                    ></v-textarea>
                  </v-col>
                  <v-row class="mt-3">
                    <v-col cols="12" md="3">
                      <v-btn
                        color="primary"
                        variant="flat"
                        prepend-icon="mdi-message-text-outline"
                        block
                        @click="saveResidentAppDisclaimerMsg()"
                      >
                        Save
                      </v-btn>
                    </v-col>
                  </v-row>
                </v-row>
              </v-col>
            </span>
          </p>
        </div>

        <v-divider thickness="1"></v-divider>

        <div class="d-flex w-100 mt-7 pb-10">
          <p class="font-weight-medium flex-grow-1">
            Entrypass URL
            <span class="d-block text-caption text-grey-darken-1 mt-1">
              <v-col class="pr-0">
                <v-text-field
                  label="Enter entrypass URL"
                  placeholder="https://your-entrypass-socket-url.com"
                  outlined
                  clearable
                  hide-details
                  v-model="currentEntryPassSettings.url"
                />
              </v-col>
              <v-col cols="12" md="3">
                <v-btn color="primary" variant="flat" prepend-icon="mdi-link-variant" block @click="saveEntryPassUrl()">Save</v-btn>
              </v-col>
            </span>
          </p>
        </div>
      </v-row>
    </v-col>

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

    <EntryPassQrTemplatePreview
      v-model="isShowTemplatePreview"
      :header="currentEntryPassSettings.qrCodeTemplateHeader"
      :sub-text="currentEntryPassSettings.qrCodeTemplateHeaderSubText"
    />
  </v-row>
</template>
<script lang="ts" setup>
definePageMeta({
  middleware: ["01-auth", "02-org"],
  memberOnly: true,
});
const prop = defineProps({
  site: {
    type: String,
    required: true,
  },
  siteName: {
    type: String,
    required: true,
  },

  orgId: {
    type: String,
    required: true,
  },
});

const currentEntryPassSettings = ref<Record<string, any>>({
  _id: "",
  site: "",
  org: "",
  isEnabled: true,
  api: null,
  port: null,
  serviceId: null,
  physicalPass: false,
  nfcPass: false,
  qrPass: false,
  keyPass: false,
  printerVendorId: "",
  printerProductId: "",
  qrCodeTemplateHeader: "",
  qrCodeTemplateHeaderSubText: "",
  qrCodeTemplateDate: "",
  qrCodeValidityMinutes: null,
  disclaimerMessage: "",
  url: "",
  template: { id: "", name: "" },
  status: "",
  createdBy: "",
  updatedBy: "",
  createdAt: "",
  updatedAt: "",
  deletedAt: "",
});

const {
  getBySiteId: _getSiteEntryPassSettings,
  save: _save,
} = useSiteEntryPassSettings();

const { requestDevice, testConnection, isWebUsbSupported } = useWebUsb();
const { addFile, getFileUrl } = useFile();

const scanningPrinter = ref(false);
const testingPrinter = ref(false);
const isShowTemplatePreview = ref(false);
const uploadingTemplate = ref(false);
const templateFileInput = ref<HTMLInputElement | null>(null);

function triggerTemplateUpload() {
  templateFileInput.value?.click();
}

async function handleTemplateUpload(e: Event) {
  const files = (e.target as HTMLInputElement).files;
  if (!files || files.length === 0) return;
  uploadingTemplate.value = true;
  try {
    const res = await addFile(files[0]);
    currentEntryPassSettings.value.template = {
      id: res.id as string,
      name: (res.name as string) || files[0].name,
    };
    await _save(buildPayload());
    showMessage("Template uploaded successfully!", "success");
    getSiteEntryPassSettings();
  } catch {
    showMessage("Failed to upload template", "error");
  } finally {
    uploadingTemplate.value = false;
    (e.target as HTMLInputElement).value = "";
  }
}

async function removeTemplate() {
  currentEntryPassSettings.value.template = { id: "", name: "" };
  await _save(buildPayload());
  showMessage("Template removed successfully!", "success");
  getSiteEntryPassSettings();
}

async function downloadTemplate() {
  const { id, name } = currentEntryPassSettings.value.template;
  try {
    const response = await fetch(getFileUrl(id));
    const blob = await response.blob();
    const blobUrl = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = blobUrl;
    link.download = name;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(blobUrl);
  } catch {
    showMessage("Failed to download template", "error");
  }
}

async function scanPrinter() {
  if (!isWebUsbSupported.value) {
    showMessage("Web USB is not supported in this browser", "error");
    return;
  }
  try {
    scanningPrinter.value = true;
    const device = await requestDevice();
    currentEntryPassSettings.value.printerVendorId = String(device.vendorId);
    currentEntryPassSettings.value.printerProductId = String(device.productId);
    showMessage(
      `Printer found: ${device.productName} (${device.vendorId}:${device.productId})`,
      "success",
    );
  } catch (error: any) {
    if (error.message !== "No device selected") {
      showMessage(error.message || "Failed to scan printer", "error");
    }
  } finally {
    scanningPrinter.value = false;
  }
}

async function testAndPrint() {
  if (!isWebUsbSupported.value) {
    showMessage("Web USB is not supported in this browser", "error");
    return;
  }
  const vendorId = Number(currentEntryPassSettings.value.printerVendorId);
  const productId = Number(currentEntryPassSettings.value.printerProductId);
  if (!vendorId || !productId) {
    showMessage("Please set a valid Vendor ID and Product ID first", "warning");
    return;
  }
  try {
    testingPrinter.value = true;
    const result = await testConnection(vendorId, productId);
    showMessage(
      result.message,
      result.success ? "success" : "error",
    );
  } catch (error: any) {
    showMessage(error.message || "Test print failed", "error");
  } finally {
    testingPrinter.value = false;
  }
}

const route = useRoute();
const siteId = route.params.site as string;
const orgId = route.params.org as string;

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

const {
  data: getSiteEntryPassSettingsReq,
  refresh: getSiteEntryPassSettings,
  status: getSiteEntryPassSettingsReqStatus,
} = useLazyAsyncData("get-site-entry-pass-settings", () =>
  _getSiteEntryPassSettings(prop.site as string)
);

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

watchEffect(() => {
  const data = getSiteEntryPassSettingsReq.value?.data;
  if (data) {
    currentEntryPassSettings.value = {
      ...currentEntryPassSettings.value,
      _id: data._id ?? "",
      site: data.site ?? "",
      isEnabled: data.isEnabled ?? true,
      api: data.api ?? null,
      port: data.port ?? null,
      serviceId: data.serviceId ?? null,
      physicalPass: data.settings?.physicalPass ?? false,
      nfcPass: data.settings?.nfcPass ?? false,
      qrPass: data.settings?.qrPass ?? false,
      keyPass: data.settings?.keyPass ?? false,
      printerVendorId: data.settings?.printer?.vendorId ? String(data.settings.printer.vendorId) : "",
      printerProductId: data.settings?.printer?.productId ? String(data.settings.printer.productId) : "",
      qrCodeTemplateHeader: data.settings?.qrTemplate?.header ?? "",
      qrCodeTemplateHeaderSubText: data.settings?.qrTemplate?.subText ?? "",
      qrCodeTemplateDate: data.settings?.qrTemplate?.date ?? "",
      qrCodeValidityMinutes: data.settings?.validityMinutes ?? null,
      url: data.settings?.url ?? "",
      template: data.settings?.template ?? { id: "", name: "" },
      createdAt: data.createdAt ?? "",
      updatedAt: data.updatedAt ?? "",
    };
  }
});

function buildPayload() {
  return {
    site: siteId,
    isEnabled: currentEntryPassSettings.value.isEnabled ?? true,
    api: currentEntryPassSettings.value.api ?? null,
    port: currentEntryPassSettings.value.port ?? null,
    serviceId: currentEntryPassSettings.value.serviceId ?? null,
    settings: {
      physicalPass: currentEntryPassSettings.value.physicalPass,
      nfcPass: currentEntryPassSettings.value.nfcPass,
      qrPass: currentEntryPassSettings.value.qrPass ?? false,
      keyPass: currentEntryPassSettings.value.keyPass ?? false,
      printer: {
        vendorId: Number(currentEntryPassSettings.value.printerVendorId) || null,
        productId: Number(currentEntryPassSettings.value.printerProductId) || null,
      },
      qrTemplate: {
        header: currentEntryPassSettings.value.qrCodeTemplateHeader,
        subText: currentEntryPassSettings.value.qrCodeTemplateHeaderSubText,
        date: currentEntryPassSettings.value.qrCodeTemplateDate || null,
      },
      validityMinutes: currentEntryPassSettings.value.qrCodeValidityMinutes || null,
      url: currentEntryPassSettings.value.url,
      template: currentEntryPassSettings.value.template?.id
        ? currentEntryPassSettings.value.template
        : null,
    },
  };
}

async function updateEntryPassSettingsPhysicalPass() {
  await _save(buildPayload());
  showMessage("Entry Pass Settings updated successfully!", "success");
  getSiteEntryPassSettings();
}

async function updateEntryPassSettingsNfcPass() {
  await _save(buildPayload());
  showMessage("Entry Pass Settings updated successfully!", "success");
  getSiteEntryPassSettings();
}

async function savePrinterSettings() {
  await _save(buildPayload());
  showMessage("Entry Pass Settings updated successfully!", "success");
  getSiteEntryPassSettings();
}

async function saveQrCodeTemplate() {
  await _save(buildPayload());
  showMessage("Entry Pass Settings updated successfully!", "success");
  getSiteEntryPassSettings();
}

async function saveQrCodeValidity() {
  await _save(buildPayload());
  showMessage("Entry Pass Settings updated successfully!", "success");
  getSiteEntryPassSettings();
}

async function saveResidentAppDisclaimerMsg() {
  await _save(buildPayload());
  showMessage("Entry Pass Settings updated successfully!", "success");
  getSiteEntryPassSettings();
}

async function saveEntryPassUrl() {
  await _save(buildPayload());
  showMessage("Entry Pass Settings updated successfully!", "success");
  getSiteEntryPassSettings();
}

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