<template>
  <div class="wcc-gcm-consent-table-container">
    <table class="wcc-gcm-consent-table">
      <thead>
        <tr>
          <th style="min-width: 180px">
            {{ $i18n.__("Region", "webtoffee-cookie-consent") }}
          </th>
          <th>
            {{ $i18n.__("analytics_storage", "webtoffee-cookie-consent") }}
          </th>
          <th>{{ $i18n.__("ad_storage", "webtoffee-cookie-consent") }}</th>
          <th>{{ $i18n.__("ad_user_data", "webtoffee-cookie-consent") }}</th>
          <th>
            {{ $i18n.__("ad_personalization", "webtoffee-cookie-consent") }}
          </th>
          <th>
            {{ $i18n.__("functionality_storage", "webtoffee-cookie-consent") }}
          </th>
          <th>
            {{
              $i18n.__("personalization_storage", "webtoffee-cookie-consent")
            }}
          </th>
          <th>{{ $i18n.__("Actions", "webtoffee-cookie-consent") }}</th>
        </tr>
      </thead>
      <tbody v-if="loading">
        <tr>
          <td colspan="8" class="wcc-gcm-consent-loader">
            <card-loader />
          </td>
        </tr>
      </tbody>
      <tbody v-if="!loading">
        <tr v-if="rows.length === 0">
          <td colspan="8" class="wcc-gcm-consent-no-regions">
            {{
              $i18n.__(
                "No regions added. All consents are denied by default",
                "webtoffee-cookie-consent"
              )
            }}
          </td>
        </tr>

        <tr v-for="(row, index) in rows" :key="index">
          <td style="min-width: 180px">
            <div class="wcc-multi-select" @click="toggleDropdown(index)" v-if="editMode[index]"
              :class="{ 'wcc-region-error': isEmptyRegion(index) }">
              <span class="wcc-select-region-placeholder" v-if="row.region.length === 0">
                {{ $i18n.__("Select a region", "webtoffee-cookie-consent") }}
              </span>
              <span v-else class="wcc-selected-regions">
                <span v-for="regionCode in row.region" :key="regionCode" class="wcc-selected-region">
                  {{ regionCode }}
                  <span class="wcc-remove-region" @click.stop="removeRegion(index, regionCode)">×</span>
                </span>
              </span>
              <ul v-show="isDropdownOpen(index)" class="wcc-dropdown">
                <li v-for="(name, code) in availableRegions" :key="code" @click.stop="selectRegion(index, code)">
                  <span class="wcc-dropdown-label" :class="{ disabled: allSelectedRegions.includes(code) }"
                     :style="{
                      cursor: allSelectedRegions.includes(code)
                        ? 'not-allowed'
                        : 'pointer',
                    }">
                    {{ name }}
                  </span>
                </li>
              </ul>
            </div>
            <div v-else>
              <span v-if="row.region.length === 0">
                {{ $i18n.__("No region selected", "webtoffee-cookie-consent") }}
              </span>
              <span v-else>
                {{ row.region.join(", ") }}
              </span>
            </div>
          </td>
          <td>
            <div v-if="editMode[index]">
              <select class="wcc-storage-select" v-model="row.analytics_storage" @change="
                updateStorageValue(
                  index,
                  'analytics_storage',
                  row.analytics_storage
                )
                ">
                <option>Denied</option>
                <option>Granted</option>
              </select>
            </div>
            <div v-else>
              {{ row.analytics_storage }}
            </div>
          </td>
          <td>
            <div v-if="editMode[index]">
              <select class="wcc-storage-select" v-model="row.ad_storage" @change="
                updateStorageValue(index, 'ad_storage', row.ad_storage)
                ">
                <option>Denied</option>
                <option>Granted</option>
              </select>
            </div>
            <div v-else>
              {{ row.ad_storage }}
            </div>
          </td>
          <td>
            <div v-if="editMode[index]">
              <select class="wcc-storage-select" v-model="row.ad_user_data" @change="
                updateStorageValue(index, 'ad_user_data', row.ad_user_data)
                ">
                <option>Denied</option>
                <option>Granted</option>
              </select>
            </div>
            <div v-else>
              {{ row.ad_user_data }}
            </div>
          </td>
          <td>
            <div v-if="editMode[index]">
              <select class="wcc-storage-select" v-model="row.ad_personalization" @change="
                updateStorageValue(
                  index,
                  'ad_personalization',
                  row.ad_personalization
                )
                ">
                <option>Denied</option>
                <option>Granted</option>
              </select>
            </div>
            <div v-else>
              {{ row.ad_personalization }}
            </div>
          </td>
          <td>
            <div v-if="editMode[index]">
              <select class="wcc-storage-select" v-model="row.functionality_storage" @change="
                updateStorageValue(
                  index,
                  'functionality_storage',
                  row.functionality_storage
                )
                ">
                <option>Denied</option>
                <option>Granted</option>
              </select>
            </div>
            <div v-else>
              {{ row.functionality_storage }}
            </div>
          </td>
          <td>
            <div v-if="editMode[index]">
              <select class="wcc-storage-select" v-model="row.personalization_storage" @change="
                updateStorageValue(
                  index,
                  'personalization_storage',
                  row.personalization_storage
                )
                ">
                <option>Denied</option>
                <option>Granted</option>
              </select>
            </div>
            <div v-else>
              {{ row.personalization_storage }}
            </div>
          </td>
          <td>
            <div v-if="!row.showRemoveButton && !editMode[index]"
              class="wcc-gcm-default-consent-actions wcc-col-2 wcc-align-center">
              <base-popper :content="$i18n.__('Edit row', 'webtoffee-cookie-consent')">
                <button class="wcc-button-no-style" @click="toggleEditMode(index)" :disabled="!googleConsentModeStatus" :data-test-id="`wcc-gcm-edit-row-button-${index}`">
                  <base-icon class="wcc-nav-tab-button-icon" icon="edit-alt" height="14px" color="#000000"></base-icon>
                </button>
              </base-popper>
              <base-popper :content="$i18n.__('Delete row', 'webtoffee-cookie-consent')">
                <button class="wcc-button-no-style"  @click="removeRow(index)" :disabled="!googleConsentModeStatus" :data-test-id="`wcc-gcm-delete-row-button-${index}`">
                  <base-icon class="wcc-nav-tab-button-icon" icon="trash" height="14px" color="#eb4034"></base-icon>
                </button>
              </base-popper>
            </div>
            <button v-else @click="removeRow(index)" class="wcc-button wcc-button-red" :disabled="!googleConsentModeStatus" :data-test-id="`wcc-gcm-remove-row-button-${index}`">
              {{ $i18n.__("Remove row", "webtoffee-cookie-consent") }}
            </button>
          </td>
        </tr>
        <tr style="background-color: #ffffff;">
          <td colspan="8">
            <button @click="addRow" class="wcc-button wcc-button-light-blue" :disabled="!googleConsentModeStatus" :data-test-id="`wcc-gcm-add-new-region-button`">
              {{ $i18n.__("+ Add new", "webtoffee-cookie-consent") }}
            </button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
import api from "@/modules/gcm/helpers/api";
import CardLoader from "@/components/elements/CardLoader.vue";
import BaseIcon from "@/components/icons/BaseIcon.vue";

export default {
  name: "WccGcmConsentTable",
  props: {
    emptyRegions: {
      type: Array,
      default: () => [],
    },
  },
  components: {
    CardLoader,
    BaseIcon,
  },
  data() {
    return {
      rows: [], // Array to store the rows
      availableRegions: {}, // Object to store region codes and names
      loading: true, // Initialize loading to true
      openDropdownIndex: null, // Track which dropdown is open
      editMode: [], // Initialize as an empty array to track edit mode for each row
    };
  },
  computed: {
    allSelectedRegions() {
      return this.rows.reduce((acc, row) => {
        return acc.concat(row.region);
      }, []);
    },
    googleConsentModeStatus: {
      get() {
        return this.$store.state.settings.options.google_consent_mode.status;
      },
      set(value) {
        this.$store.state.settings.options.google_consent_mode.status = value;
        let data = {};
        data.status = value;
        this.setOption("google_consent_mode", data);
        this.saveOptions();
      },
    },
  },
  methods: {
    addRow() {
      // Set showRemoveButton to false for existing rows
      this.rows.forEach((row) => (row.showRemoveButton = false));

      const newRow = {
        region: [],
        analytics_storage: "Denied",
        ad_storage: "Denied",
        ad_user_data: "Denied",
        ad_personalization: "Denied",
        functionality_storage: "Denied",
        personalization_storage: "Denied",
        security_storage: "Granted",
        showRemoveButton: true, // Show the remove button for the new row
      };
      this.rows.push(newRow);
      this.editMode.push(true); // Add initial edit mode state for the new row
      this.emitConsentValues(); // Emit values when a new row is added
    },
    removeRow(index) {
      this.rows.splice(index, 1);
      this.editMode.splice(index, 1); // Remove the edit mode state for this row
      this.emitConsentValues(); // Emit values when a row is removed
    },
    updateSelectedRegions(index, code) {
      const row = this.rows[index];
      const regionIndex = row.region.indexOf(code);
      if (regionIndex === -1) {
        // We're trying to add a region, so check if it's already selected in other rows
        const otherSelectedRegions = this.allSelectedRegions.filter(
          (region, idx) => this.rows[idx] !== row // Exclude the current row
        );

        if (!otherSelectedRegions.includes(code)) {
          // Add the region if not already selected anywhere
          row.region.push(code);
        }
      } else {
        // Remove the region if already selected
        row.region.splice(regionIndex, 1);
      }

      // Check if the row is no longer empty and remove it from emptyRegions if necessary
      if (row.region.length > 0) {
        const emptyRegionIndex = this.emptyRegions.findIndex(
          (emptyRegion) => emptyRegion.index === index
        );
        if (emptyRegionIndex !== -1) {
          this.emptyRegions.splice(emptyRegionIndex, 1);
        }
      }

      this.emitConsentValues(); // Emit values on region update
    },
    updateStorageValue(index, key, value) {
      if (this.rows[index]) {
        this.rows[index][key] = value; // Update the specified storage value
        this.emitConsentValues(); // Emit values on storage update
      }
    },
    emitConsentValues() {
      this.$emit("updateConsentValues", this.rows); // Emit the current consent values
    },
    async getAllRegions() {
      try {
        this.loading = true;
        const response = await api.allRegions();
        this.availableRegions = response;
      } catch (error) {
        console.error("API Error:", error);
      } finally {
        this.loading = false;
      }
    },
    async getDefaultConsents() {
      try {
        this.loading = true;
        const response = await api.getConsents();

        if (response && response.length > 0) {
          // Map the consent data using the helper function
          this.rows = response.map((consent) => ({
            region: consent.region,
            analytics_storage: this.getConsentValue(consent.analytics_storage),
            ad_storage: this.getConsentValue(consent.ad_storage),
            ad_user_data: this.getConsentValue(consent.ad_user_data),
            ad_personalization: this.getConsentValue(consent.ad_personalization),
            functionality_storage: this.getConsentValue(consent.functionality_storage),
            personalization_storage: this.getConsentValue(consent.personalization_storage),
            security_storage: this.getConsentValue(consent.security_storage),
          }));

          this.editMode = new Array(this.rows.length).fill(false); // Initialize editMode array
        }
      } catch (error) {
        console.error("API Error:", error);
      } finally {
        this.loading = false;
        this.emitConsentValues();
      }
    },
    // Helper function to determine consent value
    getConsentValue(key) {
      return key === 'Denied' ? 'Denied' : 'Granted';
    },
    toggleDropdown(index) {
      this.openDropdownIndex = this.openDropdownIndex === index ? null : index;
    },
    isDropdownOpen(index) {
      return this.openDropdownIndex === index;
    },
    selectRegion(index, code) {
      this.updateSelectedRegions(index, code);
    },
    removeRegion(index, regionCode) {
      const row = this.rows[index];
      const regionIndex = row.region.indexOf(regionCode);
      if (regionIndex !== -1) {
        row.region.splice(regionIndex, 1);
      }
    },
    toggleEditMode(index) {
      this.$set(this.editMode, index, !this.editMode[index]); // Toggle the edit mode for the specific item
    },
    isEmptyRegion(index) {
      return this.emptyRegions.some((region) => region.index === index);
    },
    closeDropdown() {
      // Add a click event listener to the document
      document.addEventListener('click', (event) => {
        const target = event.target;
        const dropdowns = document.querySelectorAll('.wcc-dropdown'); // Get all dropdowns
        const multiSelectDivs = document.querySelectorAll('.wcc-multi-select'); // Get all multi-select containers

        let isAnyDropdownOpen = false;

        // Loop through each dropdown
        dropdowns.forEach((dropdown, index) => {
          // Check if the dropdown is hidden
          const isDropdownHidden = getComputedStyle(dropdown).display === 'none';
          
          // If any dropdown is visible, mark the flag
          if (!isDropdownHidden) {
            isAnyDropdownOpen = true;
            
            const regionPlaceholderSpan = multiSelectDivs[index]?.querySelector('.wcc-select-region-placeholder');

            // If the click is on the region placeholder span or within the div containing it, do nothing
            if (target === regionPlaceholderSpan || multiSelectDivs[index].contains(target)) {
              return;
            }

            // If the click is inside the current open dropdown, do nothing
            if (dropdown.contains(target)) {
              return;
            }

            // Close the current dropdown if the click is outside
            this.openDropdownIndex = null;
          }
        });
        // If no dropdown is open, do nothing
        if (!isAnyDropdownOpen) return;
      });
    }
  },
  created() {
    // Fetch regions on component creation
    this.getAllRegions();
    this.getDefaultConsents();
  },
  mounted() {
    document.addEventListener('click', this.closeDropdown);
  },
  beforeDestroy() {
    document.removeEventListener('click', this.closeDropdown);
  },
};
</script>

<style scoped>
.wcc-gcm-consent-table-container {
  width: 100%;
  background-color: #f9f9f9;
}

.wcc-gcm-consent-table {
  width: 100%;
  border-collapse: collapse;
  background-color: #fff;
  text-align: left;
  font-family: Arial, sans-serif;
}

.wcc-gcm-consent-table th,
.wcc-gcm-consent-table td {
  padding: 12px 15px;
}

.wcc-gcm-consent-table th {
  background-color: #fff;
  font-weight: bold;
  color: #6e7681;
}

.wcc-gcm-consent-table tr {
  vertical-align: top;
}

.wcc-gcm-consent-table tbody tr:nth-child(odd) {
  background-color: #f6f7f8;
}

.wcc-gcm-consent-no-regions {
  text-align: left;
  color: #808080;
  font-style: italic;
}

.wcc-gcm-consent-add-button {
  margin-top: 10px;
  padding: 8px 12px;
  font-size: 14px;
  color: #4285f4;
  background-color: transparent;
  border: 1px solid #4285f4;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.wcc-gcm-consent-add-button:hover {
  background-color: #e8f0fe;
}

.wcc-remove-row {
  padding: 6px 10px;
  background-color: #ff4d4d;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.wcc-remove-row:hover {
  background-color: #ff6666;
}

.wcc-multi-select {
  position: relative;
  /* Ensure dropdown is positioned relative to this element */
  cursor: pointer;
  min-width: 155px;
  background-color: white;
  padding-top: 6px;
  border: 1px solid #ccc;
  display: flex;
  flex-wrap: wrap;
  max-width: 155px;
}

.wcc-storage-select {
  padding-top: 4px;
  padding-bottom: 4px;
  border: 1px solid #ccc;
}

.wcc-select-region-placeholder {
  padding: 2px 10px 8px 10px;
}

.wcc-selected-regions {
  display: flex;
  /* Display selected regions in a flex container */
  flex-wrap: wrap;
  /* Allow wrapping */
  overflow: hidden;
  /* Hide overflow */
  padding-left: 10px;
}

.wcc-selected-region {
  display: inline-flex;
  /* Inline flex for each selected region */
  background-color: #e0e0e0;
  /* Optional: light gray background for selected regions */
  border-radius: 6px;
  /* Rounded corners */
  padding: 4px 6px;
  /* Padding for selected region */
  margin-right: 5px;
  /* Space between regions */
  margin-bottom: 5px;
  /* Space between rows of regions */
  position: relative;
  /* Position relative for the close icon */
  font-size: 12px;
}

.wcc-remove-region {
  margin-left: 5px;
  /* Space between region code and close icon */
  cursor: pointer;
  /* Pointer cursor for close icon */
  color: #ff4d4d;
  /* Close icon color */
  font-weight: bold;
  /* Make it bold */
}

.wcc-dropdown {
  position: absolute;
  top: 100%;
  /* Position the dropdown just below the input box */
  left: 0;
  background-color: white;
  border: 1px solid #ccc;
  width: 300px;
  /* Match the width of the parent element */
  max-height: 200px;
  overflow-y: auto;
  z-index: 10;
  padding: 0;
  margin-top: 6px;
  /* Optional: Add some space between the input and dropdown */
}

.wcc-dropdown li {
  list-style: none;
  padding: 8px 10px;
}

.wcc-dropdown li:hover {
  background-color: #f1f1f1;
}

.wcc-dropdown-label {
  display: flex;
  /* Flexbox for better alignment */
  align-items: center;
  /* Center vertically */
}

.wcc-dropdown-label.disabled {
  color: #ccc;
  /* Change color for disabled regions */
  cursor: not-allowed;
  /* Change cursor style for disabled regions */
}

/* Ensure all dropdown items have a consistent background on hover */
.wcc-dropdown li:hover {
  background-color: #f1f8fe;
  /* Change background on hover */
}

.wcc-gcm-default-consent-actions {
  justify-content: center;
}

.wcc-gcm-default-consent-actions .wcc-popper-container {
  margin-left: 14px;
}

.wcc-region-error {
  border: 1px solid red;
  /* Or any styling you prefer */
}
</style>