<script setup>
import { getDepartment, selectScan } from "@/components/shop/POSDepartmentProcess.vue";
import {
  isLoaded,
  isLoading,
  list,
  loadList,
  metaCurrentPage,
  metaItemsPerPage,
  metaTotalItems,
  setEndpoint,
  setMetaItemsPerPage,
  setPage,
  search,
  setFilter,
  setOrder,
  metaSearch,
} from "@/components/pagination/paginatedList.vue";
import {useElementVisibility} from "@vueuse/core";
import {SessionUser} from "@/components/session/token/SessionUser.vue";
import {ref, watch, onMounted, useTemplateRef} from 'vue';
import {popperBox, showPopper, showPopperWithContent, removePopperIfOpen} from "@/components/displays/PopperDefault.vue";
import { Colors } from "@/ThemeConfig.vue";

const activeTab = ref(null);

const panel_tabs = ref([
  {
    name: 'Seneste scanninger',
    active: true
  },
  {
    name: 'Søg efter nummerplade',
    active: false
  }
]);

const scansInfinityScroll = ref(null);
const highestPage = ref(0); // The highest page that has been loaded (This is used to prevent loading the same page multiple times)
const limitReached = ref(false);

/** Fetch the scans when the component is mounted */
onMounted(() => {
  limitReached.value = false;
  setEndpoint("/numberplatescans", false);
  setFilter('department_id', parseInt(getDepartment()), false);
  setOrder('created_at', 'desc', false);
  setMetaItemsPerPage(10, false);
});

/** Whenever the search changes, reset the infinite scroll */
const onChanged = () => {
  scansInfinityScroll.value = null;
  highestPage.value = 0;
  console.log('Changed', 'total items: ' + metaTotalItems.value, 'items per page: ' + metaItemsPerPage.value, 'current page: ' + metaCurrentPage.value, 'search: ' + metaSearch.value, 'limit reached: ' + limitReached.value);
};

/** Whenever the tab changes, update the items per page, and reset the search */
const changeTab = (tabIndex) => {
  // Reset the infinite scroll
  scansInfinityScroll.value = null;
  // Set the highest page to 0
  highestPage.value = 0;
  search('', false);
  // Set the page to 1
  setPage(1);
  // Load the list
  loadList();
};

/** Whenever the search changes, reset the infinite scroll */
watch(metaSearch, () => {
  onChanged();
});




// Watch the list, and add the items to the infinite scroll list
watch(list, (newList) => {
  if (scansInfinityScroll.value === null) {
    scansInfinityScroll.value = newList;
  } else {
    // Check if the list already contains the ids from the new list (To prevent duplicates)
    const ids = scansInfinityScroll.value.map((item) => item.id);
    newList = newList.filter((item) => !ids.includes(item.id));
    // If the new list is empty, then return (There's no new items)
    scansInfinityScroll.value = scansInfinityScroll.value.concat(newList);
  }
});

const activePopperPlate = ref({
  plate: '',
  isLoaded: false
});

const tmp = {
  "registration_number": "BA95215",
  "status": "Registreret",
  "status_date": "2016-04-04T14:12:14.000+02:00",
  "type": "Stor personbil",
  "use": "Busku00f8rsel",
  "first_registration": "2016-04-04+02:00",
  "vin": "YV3T2U829G1177642",
  "own_weight": 15900,
  "cerb_weight": 16500,
  "total_weight": 24350,
  "axels": 3,
  "pulling_axels": 1,
  "seats": 54,
  "coupling": true,
  "trailer_maxweight_nobrakes": 0,
  "trailer_maxweight_withbrakes": 2800,
  "doors": null,
  "make": "VOLVO",
  "model": "9700",
  "variant": "9700HD (9711R 13,83)",
  "model_type": "B6SC",
  "model_year": 0,
  "color": null,
  "chassis_type": "",
  "engine_cylinders": 6,
  "engine_volume": 10837,
  "engine_power": 345,
  "fuel_type": "Diesel",
  "is_hybrid": false,
  "hybrid_type": "mild",
  "registration_zipcode": "",
  "vehicle_id": 9000000001742548,
  "mot_info": {
    "type": "PeriodiskSyn",
    "date": "2024-02-22",
    "result": "Godkendt",
    "status": "Aktiv",
    "status_date": "2024-02-22",
    "mileage": 546000
  },
  "is_leasing": false,
  "leasing_from": null,
  "leasing_to": null
};


const decodeMotorAPIString = (string) => {
  // Check if the string contains u00, if so add a backslash
  if (string.includes('u00')) {
    string = string.replace(/u00/g, '\\u00');
  }
  // unicode decode
  return string.replace(/\\u[\dA-F]{4}/gi,
      (match) => String.fromCharCode(parseInt(match.replace(/\\u/g, ''), 16)));
};



const generatePopperPlate = (scan, motorapi_data) => {
  const data = {
    make: motorapi_data.make,
    model: motorapi_data.model,
    variant: motorapi_data.variant,
    type: motorapi_data.type,
    use: decodeMotorAPIString(motorapi_data.use),
    time: '<strong>'
        + new Date(scan.created_at).toLocaleTimeString(
      'da-DK',
      {
        timeZone: 'Europe/Copenhagen',
        hour: '2-digit',
        minute: '2-digit',
        hour12: false,
      })
        + '</strong>' +
        ' d. ' +
        '<strong>' +
        new Date(scan.created_at).toLocaleDateString(
            'da-DK',
            {
              timeZone: 'Europe/Copenhagen'
            }
        )
        + '</strong>'
  }
  return `
    <div class="numberplate-popper" data-plate="${scan.plate}">
      <p><strong>Mærke:</strong> ${data.make}</p>
      <p><strong>Model:</strong> ${data.model}</p>
      <p><strong>Variant:</strong> ${data.variant}</p>
      <p><strong>Type:</strong> ${data.type}</p>
      <p><strong>Use:</strong> ${data.use}</p>
      <p><strong>Scannet:</strong> kl. ${data.time}</p>
    </div>
  `;
};

const isPlatePopperLoading = ref(false);

const shownNumberPlatePoppers = ref([]);

const removePlatePoppersIfOpen = () => {
  shownNumberPlatePoppers.value.forEach((popperId) => {
    removePopperIfOpen(popperId);
  });
};


const showPopperPlate = (scan, element) => {
  // If the plate is loading, then return
  if (isPlatePopperLoading.value) {
    return;
  }
  if (scan === null) {
    return;
  }
  // Set the plate as loading
  isPlatePopperLoading.value = true;
  // Get the plate registration
  SessionUser.superUser.modules.motorapi.functions.lookup(scan.plate).then((response) => {
    const motorapi_data = response.data.data;
    let content = generatePopperPlate(scan, motorapi_data);
    const uniqueId = "plate-popper-" + scan.plate;
    showPopper(popperBox(
        'Nummerplade: ' + scan.plate,
        content,
        uniqueId
    ), element);
    shownNumberPlatePoppers.value.push(uniqueId);
    isPlatePopperLoading.value = false;
  }).catch((error) => {
    isPlatePopperLoading.value = false;
    console.error(error);
  });
}

const plate_scanners = ref([]);

const getPlateScanners = async () => {
  await SessionUser.request('/department/numberplatescanners?id=' + getDepartment(),
      'GET')
      .then((response) => {
        plate_scanners.value = response.data.data;
        console.log(plate_scanners.value);
      }
  );
}

getPlateScanners();

const getPlateScannerName = (id) => {
  for (let i = 0; i < plate_scanners.value.length; i++) {
    if (plate_scanners.value[i].id === id) {
      return plate_scanners.value[i].name;
    }
  }
  return 'N/A';
};

/**
 * End of list reference
 */
const endOfList = useTemplateRef('endOfList');

/**
 * If the end of the list is visible, then load more items
 */
const endOfListVisibility = useElementVisibility(endOfList);

watch(endOfListVisibility, (isVisible) => {
  console.log('Checking visibility');
  console.log(isVisible);
  if (isVisible) {
    // If the current page is the highest page, then return
    console.log('Current page: ' + metaCurrentPage.value);
    console.log('Highest page: ' + highestPage.value);
    console.log('Total items: ' + metaTotalItems.value);
    console.log('Items per page: ' + metaItemsPerPage.value);
    // Calculate the total pages
    const totalPages = Math.ceil(metaTotalItems.value / metaItemsPerPage.value);
    console.log('Total pages: ' + totalPages);
    // If the current page is the highest page, then return
    if (metaCurrentPage.value === totalPages) {
      limitReached.value = true;
      return;
    } else {
      limitReached.value = false;
    }
    // Load more items
    setPage(metaCurrentPage.value + 1);
    // If the current page is 1, then we don't need to load the list again
    if (metaCurrentPage.value !== 1) {
      loadList();
    }
  }
});

const isLimitReached = () => {
  return limitReached.value;
};

// Wait 1s before loading the list
setTimeout(() => {
  loadList();
}, 1000);

</script>

<template>
  <div @mouseleave="removePlatePoppersIfOpen()">
    <article class="" id="scans-panel">
      <p
          class="is-size-4 title"
          style="font-weight: 400;"
      >
        Nummerplader
      </p>
      <p
        class="is-size-6 subtitle mb-1"
      >
        Seneste scanninger
      </p>

      <p class="control mb-2">
        <input
            @input="onChanged(); search($event.target.value);"
            class="input mt-2 has-sharp-edges has-placeholder-italic"
            type="text"
            placeholder="Søg efter nummerplade"
            style="border-color: transparent;"
            :style="{
              'background-color': Colors.inputs.default.backgroundColor,
              'color': Colors.inputs.default.textColor
            }"
            v-model="metaSearch"
        />
      </p>
      <div id="scans-list" class="scans-list">
        <table class="table is-fullwidth is-hoverable">
          <thead>
          <tr>
            <th>Nummerplade</th>
            <th class="is-narrow">Scanner</th>
            <th class="is-narrow">{{ SessionUser.objects.global.language.time.at_hour }}</th>
          </tr>
          </thead>
          <tbody>
          <tr class="plate-scan-entry" v-for="scan in scansInfinityScroll" :key="scan.id" @click="selectScan(scan)"
              @mouseenter="showPopperPlate(scan, $event.target)"
              @mouseleave="removePlatePoppersIfOpen()">
            <!--<span class="panel-icon">
              <i class="fas fa-car" aria-hidden="true"></i>
            </span> -->
            <td style="width: 50%;">{{ scan.plate }}</td>
            <td class="" style="width: 15%;"
                v-if="plate_scanners.length > 0"
            >
              {{ getPlateScannerName(parseInt(scan.plate_scanner_id)) }}
            </td>
            <!-- Time, and date HH:MM DD/MM (European format - 13:00 01/01) -->
            <td
                class="is-narrow"
                style="width: 50%;"
            >
              {{ SessionUser.functions.date.toLocalTimeHours(scan.created_at) }}
            </td>
          </tr>
          <!-- If the infinity scroll is null, show a loading spinner -->
          <tr v-if="scansInfinityScroll === null">
            <td colspan="3">
              <div class="has-text-centered">
                <i class="fas fa-spinner fa-spin"></i>
              </div>
            </td>
          </tr>
          <!-- If the infinity scroll is empty, show a message -->
          <tr v-if="scansInfinityScroll !== null && scansInfinityScroll.length === 0">
            <td colspan="3">
              <div class="has-text-centered">
                Ingen flere nummerplader
              </div>
            </td>
          </tr>
          <!-- Element to detect the end of the list -->
          <tr ref="endOfList" class="end-of-list">
            <td colspan="3">
              <div class="has-text-centered" v-if="!isLimitReached()">
                <i class="fas fa-spinner fa-spin"></i>
              </div>
              <div class="has-text-centered" v-else>
                <span class="icon">
                  <i class="fas fa-check"></i>
                </span>
                <span>{{ SessionUser.objects.global.language.nothing_left_to_show }}</span>
              </div>
            </td>
          </tr>
          </tbody>
        </table>
      </div>
      <!-- If there's no scans, and the infinity scroll is also empty or null -->
      <div class="panel-block" v-if="list.length === 0 && getDepartment() !== '' && (scansInfinityScroll === null || scansInfinityScroll.length === 0)">
        <p>
          Ingen nummerplader blev fundet
        </p>
      </div>
      <!-- Reload button -->
      <div class="panel-block" v-if="list.length === 0 && getDepartment() !== '' && scansInfinityScroll === null">
        <button class="button is-dark is-fullwidth" @click="loadList">
          <span class="icon">
            <i class="fas fa-redo"></i>
          </span>
          <span>Prøv igen</span>
        </button>
      </div>
    </article>
    <div>
    </div>
  </div>
</template>

<style scoped>
.scans-list {
  overflow-y: auto;
  max-height: 300px;
}
.scans-list::-webkit-scrollbar {
  width: 5px;
}
.scans-list::-webkit-scrollbar-thumb {
  background-color: #4a4a4a;
  border-radius: 5px;
}
.scans-list::-webkit-scrollbar-track {
  background-color: transparent;
}
.input.has-sharp-edges {
  border-radius: 0;
}
.input.has-placeholder-italic::placeholder {
  font-style: italic;
}
</style>