<script setup>
import { getCurrentInstance, ref, onMounted, onUnmounted, nextTick } from 'vue';
import Swal from 'sweetalert2';
import LogoIkea from '@/assets/Ikea_logo.svg';
import Multiselect from 'vue-multiselect';
import { GChart } from 'vue-google-charts';
import { FwbDropdown, FwbListGroup, FwbListGroupItem } from 'flowbite-vue';
import EasyTable from "vue3-easy-data-table";
import SearchInput from '@/Components/SearchInput.vue';
//import autocomplete from '@trevoreyre/autocomplete-vue';


import {
  FwbNavbar,
  FwbNavbarCollapse,
  FwbNavbarLink,
  FwbNavbarLogo,
} from 'flowbite-vue';
import axios from 'axios';
import IkeaLogo from './Ikea/IkeaLogo.vue';
const type = 'GeoChart';

const ccountry = ref([]);
const ccountry_filter = ref([['Country'],]);
const ccountry_list = ref(['TEST']);
const selected = ref(null);
const article = ref('');
const hrates = ref([
  { text: "Currency", value: "currency", sortable: true },
  { text: "Country", value: "country_name", sortable: true },
  { text: "Rate", value: "rate", 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;
    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 > 4) {
      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 } });
      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'],];
  let aCntry = selected.value.map((country) => [country]);

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

onMounted(fetch);
onMounted(fetch_rates);
</script>

<template>
  <fwb-navbar>
    <template #logo>
      <fwb-navbar-logo alt="IKEA Price Craweler" :image-url="LogoIkea" link="#">
        IKEA Price Crawler
      </fwb-navbar-logo>
    </template>
    <template #default="{ isShowMenu }">
      <fwb-navbar-collapse :is-show-menu="isShowMenu">
        <fwb-navbar-link is-active link="#">
          Home
        </fwb-navbar-link>
        <fwb-navbar-link link="#">
          Services
        </fwb-navbar-link>
        <fwb-navbar-link link="#">
          Pricing
        </fwb-navbar-link>
        <fwb-navbar-link link="#">
          Contact
        </fwb-navbar-link>
      </fwb-navbar-collapse>
    </template>
  </fwb-navbar>
  <div class="m-3">
    <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">
        <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="selected" :options="ccountry_list"
            @select="selectCountry" @remove="selectCountry">
          </multiselect>
        </div>
        <div>
          <span class="font-extrabold font-mono">Zadaj polozku</span>
        </div>
        <div>
          <multiselect v-model="selected_item" label="item" track-by="item" :custom-label="customLabel" placeholder="Find item" :searchable="true" :options="options_items" @search-change="async_search"/>
        </div>
        <div class="mt-5">
          <EasyTable :rows-per-page=10 :headers="headers" :items="items"></EasyTable>
        </div>
        <div class="mt-5">
          <EasyTable :rows-per-page=15 :headers="hrates" :items="rates"></EasyTable>
        </div>
      </div>
    </div>
  </div>
</template>
<style>
@import 'vue3-easy-data-table/dist/style.css';
</style>
<style src="vue-multiselect/dist/vue-multiselect.css"></style>
