<template>
  <div class="table-actions">
    <div class="info-pane">
      <div>
        <img src="/favicon.svg" width="50" alt="" />
      </div>

      <div>
        <div style="font-size: 0.75em; color: #ccc">v{{ packageVersion }}</div>
        <div>
          <span v-if="authStore.user != null">
            Zalogowany jako <b>{{ authStore.user.name }}</b>
          </span>
          &bull;
          <span class="info-file" :class="sceneriesStore.dataState">
            <span v-if="sceneriesStore.dataState == LoadingState.LOADING">Ładowanie danych...</span>
            <span v-if="sceneriesStore.dataState == LoadingState.SUCCESS">Załadowano dane z bazy!</span>
            <span v-if="sceneriesStore.dataState == LoadingState.ERROR">Błąd podczas pobierania danych!</span>
          </span>
        </div>

        <div>
          <span class="file-changes" style="color: salmon" v-if="sceneriesStore.unsavedChanges">Niezapisane zmiany!</span>
          <span class="file-changes" style="color: #aaa" v-else>Brak niezapisanych zmian</span>
        </div>
      </div>
    </div>

    <div class="pane actions-pane">
      <button @click="addNewStation">Dodaj nową stację</button>
      <button @click="confirmLoadData">Odśwież dane</button>
      <button @click="confirmUpdateList" :data-disabled="!sceneriesStore.unsavedChanges" :disabled="!sceneriesStore.unsavedChanges">
        Zapisz zmiany
      </button>
      <button @click="signOut">Wyloguj się</button>
    </div>

    <div class="pane notify-pane">
      <label class="notify">
        <input type="checkbox" v-model="sceneriesStore.notifyDiscord" @input="onNotifyCheckboxChange(($event.target as HTMLInputElement)!.checked)" />
        <span>
          Powiadom o zmianach: <b>{{ sceneriesStore.notifyDiscord ? 'TAK' : 'NIE' }}</b>
        </span>
      </label>
    </div>

    <div class="pane search-pane">
      <input class="search" ref="search" type="text" v-model="sceneriesStore.searchedSceneryName" placeholder="Wpisz nazwę scenerii..." width="350" />

      <button @click="clearInput">Wyczyść</button>
    </div>

    <div class="pane">
      Pokazuj maks.
      <input type="number" min="1" v-model="sceneriesStore.maxVisibleResults" style="width: 4em; margin: 0 0.5em" />
      wyników
    </div>

    <div class="pane">
      Obecnie pokazane scenerie:
      {{ Math.min(sceneriesStore.maxVisibleResults, sceneriesStore.stationList.length, sceneriesStore.sortedStationList.length) }} /
      {{ sceneriesStore.stationList.length }}
    </div>

    <div class="pane">
      <button @click="changelogVisible = !changelogVisible">
        {{ changelogVisible ? 'Ukryj' : 'Pokaż' }} changelog ({{ sceneriesStore.changeList.length }})
      </button>
    </div>

    <Changelog v-if="changelogVisible" />
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import client from '../common/http';

import { version } from '../../package.json';
import Changelog from './Changelog.vue';
import { useSceneriesStore } from '../stores/sceneries.store';
import { LoadingState } from '../types/common.types';
import { SceneryRowItem } from '../types/sceneries.types';
import { useGlobalStore } from '../stores/global.store';
import { useAuthStore } from '../stores/auth.store';

export default defineComponent({
  setup() {
    return {
      sceneriesStore: useSceneriesStore(),
      globalStore: useGlobalStore(),
      authStore: useAuthStore(),

      LoadingState,
    };
  },
  data() {
    return {
      changelogVisible: false,
      packageVersion: version,
    };
  },
  methods: {
    confirmLoadData() {
      const confirmed = confirm('Czy na pewno chcesz odświeżyć dane? Wszelkie niezapisane zmiany zostaną utracone!');
      if (confirmed) this.sceneriesStore.fetchSceneriesData();
    },

    confirmRestoreList() {
      const confirmed = confirm('Czy na pewno chcesz zresetować listę do ustawień z pliku? Wszelkie niezapisane zmiany zostaną utracone!');
      if (confirmed) this.restoreList();
    },

    confirmUpdateList() {
      const confirmed = confirm('Czy na pewno chcesz wprowadzić obecne zmiany?');
      if (confirmed) this.updateListToDb();
    },

    async signOut() {
      await client.post('/auth/logout');
      this.$router.push('/login');
      this.authStore.removeUserData();
    },

    onNotifyCheckboxChange(value: boolean) {
      window.localStorage.setItem('notifyDiscord', Number(value).toString());
    },

    async updateListToDb() {
      try {
        const mappedChangeList = this.sceneriesStore.changeList.map((v) => {
          if (/^#/.test(v.id.toString())) {
            return { ...v, id: undefined };
          }
          return { ...v };
        });
        const updateResData = (await this.sceneriesStore.updateSceneriesData(mappedChangeList)).data;
        this.sceneriesStore.changesResponse = updateResData;
        this.sceneriesStore.fetchSceneriesData();
      } catch (error) {
        this.globalStore.alertMessage = 'Ups! Wystąpił błąd podczas zapisywania danych!';
        console.error(error);
      }
    },

    addNewStation() {
      const name = prompt('Nazwa nowej scenerii');
      if (!name) return;
      if (this.sceneriesStore.stationList.some((station) => station.name.toLocaleLowerCase('pl-PL') == name.toLocaleLowerCase('pl-PL'))) {
        this.globalStore.alertMessage = 'Sceneria o takiej nazwie już istnieje!';
        return;
      }
      this.sceneriesStore.newStationsCount++;
      const newSt: SceneryRowItem = {
        name,
        abbr: name.slice(0, 2),
        url: '',
        hash: '',
        lines: '',
        project: null,
        projectUrl: null,
        reqLevel: -1,
        signalType: 'współczesna',
        controlType: 'SCS',
        SUP: false,
        ASDEK: false,
        hidden: false,
        routesInfo: [
          {
            isElectric: true,
            isInternal: false,
            isRouteSBL: false,
            routeLength: 0,
            routeSpeed: 0,
            routeTracks: 1,
            routeName: 'Test',
            hidden: false,
          },
        ],
        checkpoints: '',
        authors: '',
        availability: 'default',
        id: `#${Math.random().toString(32).substring(2)}`,
      };
      this.sceneriesStore.changeList.push({ ...newSt });
      // this.store.changeBackupList[newSt.id] = null;
      this.sceneriesStore.searchedSceneryName = name;
      this.sceneriesStore.stationList.unshift(newSt);
    },
    restoreList() {
      if (this.sceneriesStore.backupList.length == 0) return;
      this.sceneriesStore.stationList = JSON.parse(JSON.stringify(this.sceneriesStore.backupList));
      this.sceneriesStore.changeList = [];
      this.sceneriesStore.stationsToRemove = [];
      this.sceneriesStore.searchedSceneryName = '';
    },
    clearInput() {
      this.sceneriesStore.searchedSceneryName = '';
    },
  },
  components: { Changelog },
});
</script>

<style lang="scss" scoped>
.table-actions {
  display: flex;
  flex-direction: column;
  gap: 1em;
}

.pane {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.info-pane {
  display: flex;
  align-items: center;
  gap: 0.5em;
}

.info-file {
  color: greenyellow;
}

.info-file.LOADING {
  color: #aaa;
}

.info-file.ERROR {
  color: salmon;
}

#notify-checkbox:checked + label {
  color: gold;
}

.search-pane {
  display: flex;

  gap: 0.5em;

  .search {
    color: black;

    border: 1px solid white;
    outline: none;
    appearance: none;

    padding: 0.35em 0.4em;
  }
}

.actions-pane {
  display: flex;
  gap: 0.5em;
}

label.notify {
  display: flex;
  cursor: pointer;
  text-align: center;

  color: #000;

  span {
    padding: inherit;
    background-color: salmon;
    padding: 0.3em 2em;
  }

  input {
    position: absolute;
    width: 1px;
    height: 1px;
    opacity: 0;

    &:checked + span {
      background-color: lightblue;
    }

    &:focus-visible + span {
      outline: 1px solid gold;
    }
  }
}

@media screen and (max-width: 550px) {
  .pane {
    justify-content: center;
    text-align: center;
  }

  .changelog h3 {
    text-align: center;
  }
}
</style>
