<template>
  <Fragment>
    <div class="wcc-scanner-container">
      <div class="wcc-loader-view" v-if="loading">
        <p class="wcc-loading-text">
          <loader />
          {{ $i18n.__("Fetching scan data", "webtoffee-cookie-consent") }}
        </p>
      </div>
      <div v-else-if="showScanDetails">
        <button class="wcc-button-transparent" @click="hideDetails" :data-test-id="`wcc-scan-history-back-button`">
          <span class="wcc-arrow">
            <base-icon icon="arrow"></base-icon>
          </span>
          <span class="wcc-back">
            {{
              $i18n.__("Back to Scan History", "webtoffee-cookie-consent")
            }}
          </span>
        </button>
        <div>
          <h5>
            {{ $i18n.__("Scan details", "webtoffee-cookie-consent") }}
          </h5>
          <p>
            {{ $i18n.__("Scan date:", "webtoffee-cookie-consent") }}
            {{ formatDate(selectedScanData.date_created) }}
          </p>
        </div>

        <div class="wcc-scanned-cookie-details-div">
          <div class="wcc-scanned-cookie-details-div-inner">
            <div class="wcc-scanned-cookie-details-top wcc-scanned-cookies-top">
              <div class="wcc-cookie-details-item">
                {{
                  $i18n.__(
                    selectedScanData.total_cookies,
                    "webtoffee-cookie-consent"
                  )
                }}
              </div>
            </div>
            <div
              class="wcc-scanned-cookie-details-bottom wcc-scanned-cookies-bottom"
            >
              <div class="wcc-cookie-details-item">
                {{ $i18n.__("Cookies", "webtoffee-cookie-consent") }}
              </div>
            </div>
          </div>
          <div class="wcc-scanned-cookie-details-div-inner">
            <div
              class="wcc-scanned-cookie-details-top wcc-scanned-category-top"
            >
              <div class="wcc-cookie-details-item">
                {{
                  $i18n.__(
                    selectedScanData.category,
                    "webtoffee-cookie-consent"
                  )
                }}
              </div>
            </div>
            <div
              class="wcc-scanned-cookie-details-bottom wcc-scanned-category-bottom"
            >
              <div class="wcc-cookie-details-item">
                {{ $i18n.__("Categories", "webtoffee-cookie-consent") }}
              </div>
            </div>
          </div>
          <div class="wcc-scanned-cookie-details-div-inner">
            <div class="wcc-scanned-cookie-details-top wcc-scanned-script-top">
              <div class="wcc-cookie-details-item">
                {{
                  $i18n.__(
                    selectedScanData.total_scripts,
                    "webtoffee-cookie-consent"
                  )
                }}
              </div>
            </div>
            <div
              class="wcc-scanned-cookie-details-bottom wcc-scanned-script-bottom"
            >
              <div class="wcc-cookie-details-item">
                {{ $i18n.__("Scripts", "webtoffee-cookie-consent") }}
              </div>
            </div>
          </div>
          <div class="wcc-scanned-cookie-details-div-inner">
            <div class="wcc-scanned-cookie-details-top wcc-scanned-urls-top">
              <div class="wcc-cookie-details-item">
                {{
                  $i18n.__(
                    selectedScanData.total_url,
                    "webtoffee-cookie-consent"
                  )
                }}
              </div>
            </div>
            <div
              class="wcc-scanned-cookie-details-bottom wcc-scanned-urls-bottom"
            >
              <div class="wcc-cookie-details-item">
                {{ $i18n.__("Total Pages", "webtoffee-cookie-consent") }}
              </div>
            </div>
          </div>
        </div>
        <div class="wcc-scanned-cookie-details">
          <h6 style="padding-left: 15px">
            {{ $i18n.__("Cookies", "webtoffee-cookie-consent") }}
          </h6>
          <scan-details :responseData="selectedScanData" />
        </div>
      </div>
      <div v-else>
        <div class="wcc-scanner-action-btn">
          <span class="wcc-scanner-connect-btn-title">
            {{ $i18n.__("Scan history", "webtoffee-cookie-consent") }}
          </span>
          <base-button
            class="wcc-button wcc-button-blue wcc-scan-connect-btn"
            ref="ckyButtonScannerConnect"
            @click.native="emitScannerConnect"
            style="margin-left: 15px"
            :disabled="hasInitiatedScan || this.scanning"
            :data-test-id="`wcc-scan-for-cookies-button`"
          >
            <!-- Show different content based on the 'scanning' state -->
            <template v-if="hasInitiatedScan || this.scanning">
             
              <span
                class="wcc-scanner-connect-btn-label"
                style="line-height: 20px; margin-right: 10px"
                :data-test-id="`wcc-scan-for-cookies-button-label`"
              >
                {{ $i18n.__("Scanning....", "webtoffee-cookie-consent") }}
              </span>
              <loader/>
            </template>
            <template v-else>
              <base-icon icon="search" color="#000000"></base-icon>
              <span
                class="wcc-scanner-connect-btn-label"
                style="margin-left: 10px"
                :data-test-id="`wcc-scan-for-cookies-button-label`"
              >
                {{
                  scanning
                    ? $i18n.__("Scanning....", "webtoffee-cookie-consent")
                    : $i18n.__(
                        "Scan for cookies",
                        "webtoffee-cookie-consent"
                      )
                }}
              </span>
            </template>
          </base-button>
        </div>
        <div class="wcc-scan-details">
          <div class="wcc-scan-notice" v-if="hasInitiatedScan || this.scanning">
            <span>
              <base-icon
                icon="exclamation-triangle"
                color="#000000"
              ></base-icon>
            </span>
            <span>
              {{
                $i18n.__(
                  "Scanning for cookies could take time based on the number of URLs in the site and the server speed. Feel free to move to other tasks while the scanning process continues in the background.",
                  "webtoffee-cookie-consent"
                )
              }}
            </span>
          </div>
          <div class="wcc-scan-result" v-if="hasData">
            <table class="wcc-custom-table">
                <thead>
                  <tr>
                    <th>
                      {{ $i18n.__("Scan date", "webtoffee-cookie-consent") }}
                    </th>
                    <th>
                      {{
                        $i18n.__("Scan status", "webtoffee-cookie-consent")
                      }}
                    </th>
                    <th>
                      {{
                        $i18n.__("URLs", "webtoffee-cookie-consent")
                      }}
                    </th>
                    <th>
                      {{
                        $i18n.__("Categories", "webtoffee-cookie-consent")
                      }}
                    </th>
                    <th>
                      {{ $i18n.__("Cookies", "webtoffee-cookie-consent") }}
                    </th>
                    <th>
                      {{ $i18n.__("Scripts", "webtoffee-cookie-consent") }}
                    </th>
                    <th></th>
                  </tr>
                </thead>
                <tbody>
                  <template v-for="item in paginatedData">
                    <tr v-if="item.scan_id" :key="item.id">
                      <td>
                        {{ item.date_created ? formatDate(item.date_created) : "" }}
                      </td>
                      <td>
                        <span
                          :style="getStatusStyle(item).style"
                          :class="`wcc-scan-status ${getStatusStyle(item).class}`"
                        >{{ getScanStatus(item.scan_status) }}</span>
                      </td>
                      <td>{{ item.total_url }}</td>
                      <td>{{ item.category }}</td>
                      <td>{{ item.total_cookies }}</td>
                      <td>{{ item.total_scripts }}</td>
                      <td>
                        <span v-if="hasInitiatedScan && item.scan_status === 'initiated'">
                          <a @click="emitAbortScan" :data-test-id="`wcc-scan-history-cancel-button`">
                            {{ $i18n.__("Cancel", "webtoffee-cookie-consent") }}
                          </a>
                        </span>
                        <span v-else-if="item.scan_status === 'Progress'">
                          {{ $i18n.__(item.scan_status, "webtoffee-cookie-consent") }}
                        </span>
                        <span v-else-if="item.scan_status === 'completed'">
                          <a @click="showDetails(item)" :data-test-id="`wcc-scan-history-view-button`">
                            {{ $i18n.__("View", "webtoffee-cookie-consent") }}
                          </a>
                        </span>
                      </td>
                    </tr>
                  </template>
                </tbody>
            </table>
            <!-- Pagination controls -->
            <div class="wcc-pagination-controls" v-if="totalPages > 1">
              <button
                @click="previousPage"
                :disabled="currentPage === 1"
                style="margin-right: 10px"
                :data-test-id="`wcc-scan-history-previous-button`"
              >
                <div class="wcc-button-container">
                  <base-icon
                    class="wcc-nav-arrow-left"
                    icon="angle-right"
                  ></base-icon>
                </div>
              </button>
              <div class="wcc-page-numbers">
                <button
                  v-for="pageNumber in visiblePageNumbers"
                  :key="pageNumber"
                  @click="gotoPage(pageNumber)"
                  :class="{ active: currentPage === pageNumber }"
                  :data-test-id="`wcc-scan-history-page-button-${pageNumber}`"
                >
                  <div class="wcc-button-container">
                    {{ pageNumber }}
                  </div>
                </button>
              </div>
              <button
                @click="nextPage"
                :disabled="currentPage === totalPages"
                style="margin-left: 10px"
                :data-test-id="`wcc-scan-history-next-button`"
                >
                <div class="wcc-button-container">
                  <base-icon
                    class="wcc-nav-arrow-right"
                    icon="angle-right"
                  ></base-icon>
                </div>
              </button>
            </div>
          </div>
          <div class="wcc-scan-loader" v-else>
            <card-loader />
          </div>
        </div>
      </div>
    </div>
  </Fragment>
</template>
  
<script>
import BaseIcon from "@/components/icons/BaseIcon.vue";
import ScanDetails from "@/modules/scanner/views/ScanDetails.vue";
import { Fragment } from "vue-frag";
import api from "@/modules/scanner/helpers/api";
import Loader from "@/components/elements/Loader.vue";
import CardLoader from "@/components/elements/CardLoader.vue";

export default {
  name: "ScanResult",
  components: {
    BaseIcon,
    Fragment,
    ScanDetails,
    Loader,
    CardLoader,
  },
  props: {
    responseData: Object, // Define the prop to receive responseData
  },
  data() {
    return {
      scanning: false,
      scanId: null,
      scan_token: null,
      scanResult: null,
      showScanDetails: false,
      loading: true,
      selectedScanData: {},
      scanResponseData: {},
      currentPage: 1, // Initialize current page to 1
      itemsPerPage: 10, // Number of items to display per page
      responseDataLoaded: false,
      cookieCounts: {}, // Object to store counts of cookies
    };
  },
  computed: {
    filteredData() {
      // Filter responseData to exclude items where scan_id is empty
      return Object.values(this.responseData)
        .filter((item) => item && item.scan_id !== "")
        .reverse();
    },
    // Compute if there is responseData with status "initiated"
    hasInitiatedScan() {
      if (!this.responseData) {
        // Handle the case when responseData is not defined (null or undefined)
        return false;
      }
      // Check if scanResponseData exists and has a scan_status of 'initiated'
      return Object.values(this.responseData).some(
        (item) => item && item.scan_status === "initiated"
      );
    },
    // Calculate the total number of pages based on itemsPerPage
    totalPages() {
      return Math.ceil(this.filteredData.length / this.itemsPerPage);
    },

    // Compute the data to display on the current page
    paginatedData() {
      const startIndex = (this.currentPage - 1) * this.itemsPerPage;
      const endIndex = startIndex + this.itemsPerPage;
      const slicedData = this.filteredData.slice(startIndex, endIndex);
      return slicedData; // Reverse the order
    },
    // Calculate an array of page numbers
    pageNumbers() {
      return Array.from({ length: this.totalPages }, (_, index) => index + 1);
    },
    // Calculate an array of visible page numbers (up to 3 pages)
    visiblePageNumbers() {
      const totalPageNumbers = this.pageNumbers.length;
      const middlePage = this.currentPage;
      const startPage = Math.max(1, middlePage - 1);
      const endPage = Math.min(totalPageNumbers, middlePage + 1);
      return Array.from(
        { length: endPage - startPage + 1 },
        (_, index) => startPage + index
      );
    },
    hasData() {
      return this.paginatedData.some((item) => item.scan_id);
    },
    getStatusStyle() {
      return (item) => {
        let style = {}; // Initialize an empty style object
        let cssClass = ""; // Initialize an empty class string

        // Check if item.scan_status exists and is truthy
        if (item.scan_status) {
          switch (item.scan_status) {
            case "initiated":
              style = {
                backgroundColor: "#B2D5FF",
                color: "#0055CC",
              };
              cssClass = "wcc-initiated-class"; // Add your custom CSS class name
              break;
            case "processing":
              style = {
                backgroundColor: "#B2D5FF",
                color: "#0055CC",
              };
              cssClass = "wcc-processing-class"; // Add your custom CSS class name
              break;
            case "completed":
              style = {
                backgroundColor: "#E6F3E9",
                color: "#006116",
              };
              cssClass = "wcc-completed-class"; // Add your custom CSS class name
              break;
            default:
              style = {
                backgroundColor: "#FBEBEB",
                color: "#962627",
              };
              cssClass = "default-class"; // Add your default CSS class name here
              break;
          }
        } else {
          // If item.scan_status is falsy or undefined, assign a default class
          style = {
            backgroundColor: "#FBEBEB",
            color: "#962627",
          };
          cssClass = "default-class"; // Add your default CSS class name here
        }

        return {
          style,
          class: cssClass,
        };
      };
    },
    // New computed property to get the last scan status
    lastScanStatus() {
      return !this.filteredData.length ? null : this.filteredData[0].scan_status;
    },
  },
  // Add a watcher to monitor changes in the responseData prop
  watch: {
    responseData: {
      handler(newVal) {
        // Check if responseData has been provided (is not null or undefined)
        if (newVal) {
          this.loading = false; // Set loading to false when data is available
          this.responseDataLoaded = true;
        }
      },
      immediate: true, // This will trigger the handler immediately when the component is created
    },
    // Watch the lastScanStatus computed property
    lastScanStatus(newStatus) {
      if ("completed" ===  newStatus) {
        this.scanning = false;
      }
    },
  },
  created() {
    // Check if responseData is already available
    if (this.responseData) {
      // Data is already available, so set loading to false
      this.loading = false;
    }

    // Add listener for scan error events
    this.$root.$on("scan-error", () => {
      this.scanning = false;
    });
  },
  beforeDestroy() {
    // Remove the event listener when component is destroyed
    this.$root.$off("scan-error");
  },
  methods: {
    emitScannerConnect() {
      // Set scanning status to true
      this.scanning = true;
      // Emit a custom event named 'scanner-connect-clicked'
      this.$root.$emit("scanner-connect-clicked");
    },

    emitAbortScan() {
      // Emit a custom event named 'scanner-connect-clicked'
      this.$root.$emit("abort-scan-clicked");
      // Set scanning status to false
      this.scanning = false;
    },

    emitFetchScanStatus() {
      // Emit a custom event named 'scanner-connect-clicked'
      this.$root.$emit("fetch-scan-clicked");
    },

    createHeaders() {
      const headers = new Headers();
      headers.append("Accept", "application/json");
      headers.append("Content-Type", "application/json");
      return headers;
    },

    async showDetails(item) {
      this.selectedScanData = await this.fetchItem(item);
      //this.selectedScanData = this.responseData;
      this.showScanDetails = true;
    },
    hideDetails() {
      this.showScanDetails = false;
    },
    getScanStatus(scan_status) {
      switch (scan_status) {
        case "processing":
          return "In progress";
        case "completed":
          return "Completed";
        case "aborted":
          return "Aborted";
        case "failed":
          return "Failed";
        case "initiated":
          return "In progress";
        default:
          return "In progress";
      }
    },
    formatDate(dateString) {
      const options = {
        year: "numeric",
        month: "short",
        day: "numeric",
        hour: "numeric",
        minute: "numeric",
        second: "numeric",
      };
      const formattedDate = new Date(dateString).toLocaleDateString(
        "en-US",
        options
      );
      return formattedDate;
    },
    async fetchItem(item) {
      // Set item id
      const item_id = item.id;
      // Make an HTTP request to your API endpoint to check the database
      const response = await api.fetchItem(item_id);
      return response;
    },
    // Function to navigate to the previous page
    previousPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
      }
    },

    // Function to navigate to the next page
    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
      }
    },
    // Function to go to a specific page
    gotoPage(pageNumber) {
      if (pageNumber >= 1 && pageNumber <= this.totalPages) {
        this.currentPage = pageNumber;
      }
    },
    // Function to calculate the total no of cookies in each url.
    calculateCookieCounts() {
      this.cookieCounts = {}; // Clear the object first

      for (const categoryId in this.data) {
        const category = this.data[categoryId];
        const categoryCookies = category.cookies;

        for (const cookieName in categoryCookies) {
          const cookie = categoryCookies[cookieName];
          const firstFoundURL = cookie.frist_found_url;

          if (firstFoundURL in this.cookieCounts) {
            this.cookieCounts[firstFoundURL] += 1;
          } else {
            this.cookieCounts[firstFoundURL] = 1;
          }
        }
      }
    },
    // Method to fetch data from the API
    async fetchDataFromApi() {
      try {
        this.loading = true; // Set loading to true while fetching data
        const response = await api.fetchAll();
        this.scanResponseData = response.data;
        this.loading = false; // Set loading to false when data is fetched
      } catch (error) {
        console.error("Error fetching data:", error);
        this.loading = false; // Set loading to false even if there is an error
      }
    },
  },
};
</script>

<style lang="scss">
.wcc-scanner-action-btn .wcc-button-blue {
  display: inline-flex;
}
.wcc-scanner-connect-btn .wcc-icon-base {
  vertical-align: text-bottom;
}
.wcc-scanner-connect-btn-title {
  font-weight: bold;
}
.wcc-scanner-action-btn {
  padding-left: 4px;
}
.wcc-scan-notice {
  display: flex;
  color: #997410;
  background-color: #fbf6e8;
  width: 815px;
  height: 54px;
  padding: 10px 4px;
  margin-top: 16px;
  border-radius: 4px;
}
.wcc-scan-notice span {
  margin: 0px 4px;
}
.wcc-scan-result {
  margin-left: -15px;
  margin-right: -15px;
}
.wcc-scan-status-text {
  color: var(--light-color-text-information, #05c);
  text-align: center;
  font-size: 11px;
  font-style: normal;
  font-weight: 700;
  line-height: 16px;
  text-transform: uppercase;
  padding: 0px 4px;
}
/* Add CSS to center the inner-div */
.wcc-scanned-cookie-details-div {
  width: 100%;
  text-align: center;
  padding-top: 20px;
  padding-bottom: 20px;
}

/* Style for the wcc-scanned-cookie-details-inner-div elements */
.wcc-scanned-cookie-details-div-inner {
  width: 134px; /* Set the width to 134px */
  height: 134px;
  display: inline-block;
  margin-right: 10px;
  margin-left: 10px; /* Add margin for spacing between inline divs */
  vertical-align: top; /* Align divs to the top to maintain vertical alignment */
}
/* Add styling for the items within the wcc-scanned-cookie-details-inner-div */
.wcc-cookie-details-item {
  padding: 10px;
}
.wcc-scanned-cookie-details {
  margin: 0px 12px;
}
.wcc-scanned-cookie-details-top {
  height: 95px; /* Height of the top part */
  background-color: inherit; /* Inherit the background color from the parent wcc-scanned-cookie-details-inner-div */
  border-top-right-radius: 8px;
  border-top-left-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.wcc-scanned-cookie-details-top .wcc-cookie-details-item {
  font-weight: bold;
  font-size: 40px;
  color: #555e6b;
}
.wcc-scanned-cookie-details-bottom .wcc-cookie-details-item {
  font-weight: 600;
  color: #fff;
}
.wcc-pages-scanned {
  margin: 12px 12px 0px 12px;
}
.wcc-scanned-cookie-details-bottom {
  height: 39px; /* Height of the bottom part */
  background-color: inherit; /* Inherit the background color from the parent wcc-scanned-cookie-details-inner-div */
  border-bottom-right-radius: 8px;
  border-bottom-left-radius: 8px;
}
.wcc-scanned-cookie-details .wcc-app-accordion-open {
  border: 1px solid #e9ebf8;
}
.wcc-scanned-cookies-top {
  background-color: #ffe6ba;
}
.wcc-scanned-cookies-bottom {
  background-color: #df9539;
}
.wcc-scanned-category-top {
  background-color: #f1f8fe;
}
.wcc-scanned-category-bottom {
  background-color: #758ec3;
}
.wcc-scanned-urls-top {
  background-color: #e6f3e9;
}
.wcc-scanned-urls-bottom {
  background-color: #6bbb7e;
}
.wcc-scanned-script-top {
  background-color: #fbebeb;
}
.wcc-scanned-script-bottom {
  background-color: #e26f71;
}
.wcc-pagination-controls {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  font-size: 16px;
}

.wcc-pagination-controls button {
  color: #333;
  padding: 8px 12px;
  margin: 0 4px;
  cursor: pointer;
  height: 27px;
  width: 27px;
  border: none;
  background-color: #fff;
}

.wcc-pagination-controls button:hover {
  background-color: #ebf1fd;
  color: #2b3645;
  border-radius: 4px;
}

.wcc-page-numbers {
  display: flex;
  align-items: center;
}

.wcc-page-numbers button {
  background-color: #fff;
  color: #333;
  padding: 6px 6px;
  margin: 0 4px;
  cursor: pointer;
  transition: background-color 0.3s, color 0.3s;
  height: 27px;
  width: 27px;
  font-size: 14px;
  line-height: 16px;
  border-radius: 4px;
  border: none;
}

.wcc-page-numbers button.active {
  background-color: #f1f8fe;
  color: #0576fe;
  border-radius: 4px;
}

/* FontAwesome icons styling (you can adjust the styles as needed) */
.wcc-pagination-controls button i {
  margin-right: 5px;
}
.wcc-nav-arrow-left {
  transform: rotate(180deg);
}
.wcc-button-container {
  display: flex;
  justify-content: center; /* Center horizontally */
  align-items: center; /* Center vertically */
  height: 100%;
}
.wcc-scan-status {
  font-size: 11px;
  font-style: normal;
  font-weight: 700;
  line-height: 16px; /* 145.455% */
  text-transform: uppercase;
  padding: 2px 6px;
  border-radius: 3px;
}
.wcc-scan-loader {
  margin-top: 16px;
}
.wcc-scan-connect-btn .wcc-spinner .wcc-icon-base > svg > g > rect{
  fill: #ffffff;
}
</style>