<script setup>
import { getCurrentInstance, ref, onMounted, onUnmounted, nextTick, computed } from 'vue';
import Swal from 'sweetalert2';

import Multiselect from 'vue-multiselect';
import { GChart } from 'vue-google-charts';

import EasyTable from "vue3-easy-data-table";
import GuestLayout from '../Layouts/GuestLayout.vue';

import { useForm } from '@inertiajs/inertia-vue3'
import axios from 'axios';
import IkeaLogo from './Ikea/IkeaLogo.vue';

const props = defineProps({ 
  products: {
    type: Object,
    default: []
  },
  countryHash: {
    type: Object,
    default: []
  },
  menu: {
    type: Object,
    default: []
  }
 })

 console.log(props.countryHash);
let tproducts = computed(() => {
  return props.products.map((prod) => { 
    prod.salesPrice = parseFloat(prod.salesPrice);
    prod.country = props.countryHash[prod.country];
    return prod;
   } )
})

const type = 'GeoChart';
const form = useForm({
  countries: '',
  codes: '',
  currency: 'EUR',
});
const ccountry = ref([]);
const ccountry_filter = ref([['Country'],]);
const ccountry_list = ref(['TEST']);
const selected = ref(null);
const article = ref('');
const currency = ref([]);
const hrates = ref([
  { text: "Currency", value: "currency", sortable: true },
  { text: "Country", value: "country_name", sortable: true },
  { text: "Rate", value: "rate", sortable: true }
]);
// { "country": "AT", "code": "50161321", "url": "https://www.ikea.com/at/de/p/hol-aufbewahrungstisch-akazie-50161321/", "name": "HOL", "typeName": "Aufbewahrungstisch", "mainImageUrl": "https://www.ikea.com/at/de/images/products/hol-aufbewahrungstisch-akazie__0104310_pe251255_s5.jpg", "itemNoGlobal": "50161321", "salesPrice": "80.99", "tag": "FAMILY_PRICE", "last_mod": "2023-12-03 16:44:24" }, 
const hproducts = ref([
  { text: "Country", value:"country", sortable: true},
  { text: "Name", value:"name", sortable: true},
  { text: "Price", value:"salesPrice", sortable: true}
]);

const rates = ref([]);
const options_items = ref([]);
const selected_item = ref(null);

const options = {
  region: 150,

  width: 700,
  height: 500,
};

const chart_settings = {
  packages: ['geochart', 'map'],
  mapsApiKey: "AIzaSyAJaLArHgTmQPMOSogitG-umhZilVIgdNU",
};

const gchartEvents = ref({
  regionClick: () => {
    const selection = getSelection()
    console.log(selection);
    console.log("T");
  }
},);



const fetch = async () => {
  try {
    const response = await axios.get(route('ccountry.active'))
    ccountry.value = response.data
    let aCntry = ccountry.value.map((country) => [country.country_name]);
    ccountry_filter.value.push(...aCntry);

    ccountry_list.value = ccountry.value.map((country) => country.country_name);
    var i = 1;
    items.value = ccountry.value.map((country) => { return { "country": country.country_name, "currency": country.currency_code, "id": i++ } });
    console.log("TEST=", ccountry_filter.value, ccountry_list.value);
  } catch (e) {
    const response = await Swal.fire({
      title: __('are you want to try again') + '?',
      text: __(`${e}`),
      icon: 'question',
      showCancelButton: true,
      showCloseButton: true,
    })

    response.isConfirmed && fetch()
  }
}

const fetch_rates = async () => {
  try {
    const response = await axios.get(route('rates.index'))
    rates.value = response.data;
    currency.value = rates.value.map((currency) => currency.currency);
    currency.value.unshift('EUR');
    console.log("RATE=", rates.value);
  } catch (e) {
    const response = await Swal.fire({
      title: __('are you want to try again') + '?',
      text: __(`${e}`),
      icon: 'question',
      showCancelButton: true,
      showCloseButton: true,
    })

    response.isConfirmed && fetch()
  }
}

const async_search = async (item) => {
  try {
    if (item.length >= 3) {
      const response = await axios.get(route('products.search', item));
      options_items.value = response.data.map((i) => { return { "item": i.name, "desc": i.typeName, "img": i.mainImageUrl, "code": i.code } });
      console.log("VALUES=", options_items.value);
    }
  } catch (e) {
    const response = await Swal.fire({
      title: __('are you want to try again') + '?',
      text: __(`${e}`),
      icon: 'question',
      showCancelButton: true,
      showCloseButton: true,
    })

    response.isConfirmed && fetch()
  }
}

function customLabel({ item, desc }) {
  //console.log(item);
  return `${item} - ${desc}`;
}
const headers = ref([
  { text: "Id", value: "id", sortable: true },
  { text: "Country", value: "country", sortable: true },
  { text: "Currency", value: "currency" },
]);
const items = ref([]);

function selectCountry(item, id) {
  let cCntry = [['Country'],];
  console.log(form.countries);
  let aCntry = form.countries.map((country) => [country]);

  ccountry_filter.value = cCntry;
  ccountry_filter.value.push(...aCntry);
}

onMounted(fetch);
onMounted(fetch_rates);

const submit = () => {
    form.post(route('products.compare'));
};
</script>

<template>
    <GuestLayout>
    <div class="flex flex-wrap gap-2 justify-center align-middle ">
      <div class="justify-center rounded-md border-black border-8 max-h-[518px]">
        <GChart :events="gchartEvents" :type="type" :data="ccountry_filter" :options="options"
          :settings="chart_settings" />
      </div>
      <div class="mr-auto">
        <form @submit.prevent="submit">
          <div class="flex flex-col start-0">
            <span class="font-extrabold font-mono">Zadaj krajiny v ktorych chces vyhadavat</span>
          </div>
          <div>
            <multiselect :close-on-select="false" :multiple="true" v-model="form.countries" :options="ccountry_list"
              @select="selectCountry" @remove="selectCountry">
            </multiselect>
          </div>
          <div>
            <span class="font-extrabold font-mono">Zadaj polozku</span>
          </div>
          <div>
            <multiselect v-model="form.codes" label="item" track-by="item" :custom-label="customLabel"
              placeholder="Find item" :searchable="true" :options="options_items" @search-change="async_search" />
          </div>
          <div>
            <span class="font-extrabold font-mono">Prepocet do meny</span>
          </div>
          <div>
            <multiselect v-model="form.currency" :multiple="flase" :allow-empty="false"
              placeholder="Currency" :searchable="true" :options="currency" />
          </div>
          <div class="text-end mt-2">
            <button type="submit"
              class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm w-full sm:w-auto px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800"
              :disabled="form.processing" :class="{ 'opacity-25': form.processing }">
              Search
            </button>
          </div>
        </form>
        <div class="mt-5">
          <EasyTable :rows-per-page=10 :headers="headers" :items="items" alternating></EasyTable>
        </div>
        <div class="mt-5">
          <EasyTable :rows-per-page=15 :headers="hrates" :items="rates" alternating></EasyTable>
        </div>
      </div>
      <div>
        <div class="flex flex-col start-0">
          <span class="font-extrabold font-mono">Vysledky vyhladavania</span>
        </div>
        <div>
          <EasyTable :rows-per-page=15 :headers="hproducts" :items="tproducts" alternating></EasyTable>  
        </div>
      </div>
    </div>
    
  </GuestLayout>
</template>
<style>
@import 'vue3-easy-data-table/dist/style.css';
</style>
<style src="vue-multiselect/dist/vue-multiselect.css"></style>
