<template>
  <div class="manager-view" v-if="authStore.user != null">
    <RoutesModal v-if="sceneriesStore.currentStation" />
    <UpdateCard v-if="sceneriesStore.changesResponse.length > 0" />

    <hr color="white" />
    <TableActions />
    <hr color="white" />

    <div class="table_container">
      <table>
        <thead>
          <tr>
            <td v-for="header in headers" :width="header.width">{{ header.value }}</td>
            <td width="250">Dostępność</td>
            <td width="80">Usuń</td>
          </tr>
        </thead>

        <tbody>
          <tr v-for="(station, row) in sceneriesStore.sortedStationList" tabindex="0">
            <td
              v-for="{ id: propName } in headers"
              @click="changeProperty(station, row, propName as string)"
              :class="propName"
            >
              <span v-if="propName === 'url'" :style="station.url ? 'color: gold' : 'color: gray;'">URL</span>
              <span v-else-if="propName === 'projectUrl'" :style="station.projectUrl ? 'color: gold' : 'color: gray;'"
                >URL</span
              >

              <span v-else-if="propName === 'checkpoints'">{{ station[propName] ? 'POKAŻ' : 'DODAJ' }}</span>

              <span v-else-if="propName === 'routes'" style="font-size: 1.1em" :routes="station.routesInfo">
                <b>{{ station.routesInfo.length }}</b>
              </span>

              <span v-else-if="propName === 'signalType'"> {{ station[propName] }}</span>

              <span v-else-if="typeof (station as any)[propName] === 'boolean'">
                {{ (station as any)[propName] ? '✅' : '❌' }}
              </span>

              <span v-else>{{ (station as any)[propName] }}</span>
            </td>

            <td>
              <select
                name="availability"
                :id="`select-${row}`"
                v-model="sceneriesStore.sortedStationList[row]['availability']"
                @input="changeAvailability(station, sceneriesStore.sortedStationList[row]['availability'], $event)"
              >
                <option value="default">dostępna (w paczce)</option>
                <option value="nonDefault">dostępna (poza paczką)</option>
                <option value="unavailable">niedostępna</option>
                <option value="nonPublic">niepubliczna</option>
                <option value="abandoned">wycofana</option>
              </select>
            </td>

            <td @click="removeStation(station)"><img src="/icon-trash.svg" alt="remove" /></td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import changeMixin from '../mixins/changeMixin';
import RoutesModal from '../components/RoutesModal.vue';
import TableActions from '../components/TableActions.vue';
import UpdateCard from '../components/UpdateCard.vue';
import { AuthState } from '../types/auth.types';
import { SceneryRowItem, Availability } from '../types/sceneries.types';
import { useSceneriesStore } from '../stores/sceneries.store';
import { useAuthStore } from '../stores/auth.store';

export default defineComponent({
  components: { RoutesModal, TableActions, UpdateCard },
  mixins: [changeMixin],

  data: () => ({
    sceneriesStore: useSceneriesStore(),
    authStore: useAuthStore(),

    AuthState,

    headers: [
      { id: 'name', value: 'Nazwa', width: 150 },
      { id: 'abbr', value: 'Skrót post.', width: 60 },
      { id: 'hash', value: 'Hash', width: 120 },
      { id: 'url', value: 'URL', width: 80 },
      { id: 'projectUrl', value: 'URL projektu', width: 80 },
      { id: 'lines', value: 'Linie', width: 80 },
      { id: 'project', value: 'Projekt', width: 100 },
      { id: 'reqLevel', value: 'Wym. poziom', width: 80 },
      { id: 'signalType', value: 'Sygnalizacja', width: 150 },
      { id: 'controlType', value: 'Sterowanie', width: 180 },
      { id: 'SUP', value: 'SUP', width: 70 },
      { id: 'ASDEK', value: 'ASDEK', width: 70 },
      { id: 'authors', value: 'Autorzy', width: 200 },
      { id: 'routes', value: 'Szlaki', width: 70 },
      { id: 'checkpoints', value: 'Posterunki', width: 100 },
      { id: 'hidden', value: 'Ukryty', width: 80 },
    ],

    headerNameList: {
      name: 'Nazwa',
      abbr: 'Skrót posterunku',
      hash: 'Hash',
      url: 'URL',
      lines: 'Linie',
      project: 'Projekt',
      projectUrl: 'URL projektu',
      reqLevel: 'Wym. poziom',
      signalType: 'Sygnalizacja',
      controlType: 'Sterowanie',
      SUP: 'SUP',
      ASDEK: 'ASDEK',
      authors: 'Autorzy',
      routes: 'Szlaki',
      checkpoints: 'Posterunki',
      hidden: 'Ukryty',
    } as {
      [key: string]: string;
    },
  }),

  mounted() {
    this.sceneriesStore.fetchSceneriesData();
  },

  methods: {
    changeProperty(station: SceneryRowItem, row: number, propertyName: string) {
      this.sceneriesStore.selectedStationName = station.name;

      if (propertyName == 'checkpoints') {
        this.changeCheckpoints(row);
        return;
      }

      if (propertyName == 'routes') {
        this.showRoutesModal(station);
        return;
      }

      const stationListRow = this.sceneriesStore.stationList.findIndex(
        (station) => station.name == this.sceneriesStore.sortedStationList[row].name,
      );

      if (stationListRow == -1) return;
      const oldValue = (this.sceneriesStore.stationList[stationListRow] as any)[propertyName];
      if (typeof oldValue === 'boolean') {
        (this.sceneriesStore.stationList[stationListRow] as any)[propertyName] = !oldValue;
        // this.$set(this.stationList[stationListRow], propertyName, !oldValue);
        this.addChange(station, propertyName, oldValue, !oldValue);
        return;
      }

      let newValue = prompt(
        `Zmień wartość dla rubryki ${this.headers.find((h) => h.id === propertyName)?.value ?? ''}`,
        oldValue || '',
      );
      if (newValue == null) return;
      (this.sceneriesStore.stationList[stationListRow] as any)[propertyName] =
        typeof oldValue === 'number' ? parseInt(newValue) : newValue;
      // this.$set(this.stationList[stationListRow], propertyName, parseInt(newValue));
      this.addChange(station, propertyName, oldValue, typeof oldValue === 'number' ? parseInt(newValue) : newValue);
    },

    changeCheckpoints(row: number) {
      const stationListRow = this.sceneriesStore.stationList.findIndex(
        (station) => station.name == this.sceneriesStore.sortedStationList[row].name,
      );

      if (stationListRow == -1) return;
      const oldCheckpoints = this.sceneriesStore.stationList[stationListRow].checkpoints;
      const newCheckpoints = prompt('Wpisz posterunki (oddzielone średnikiem):', oldCheckpoints);
      if (newCheckpoints === null) return;

      this.sceneriesStore.stationList[stationListRow]['checkpoints'] = newCheckpoints;
      this.addChange(this.sceneriesStore.sortedStationList[row], 'checkpoints', oldCheckpoints, newCheckpoints);
    },

    changeAvailability(scenery: SceneryRowItem, availability: Availability, e: Event) {
      const selectedAvailability: Availability = (e.target as HTMLSelectElement).value as Availability;
      this.addChange(scenery, 'availability', availability, selectedAvailability);
    },

    removeStation(scenery: SceneryRowItem) {
      const confirmRemove = confirm('Czy na pewno chcesz zaznaczyć tę scenerię do usunięcia?');

      if (!confirmRemove) return;

      this.sceneriesStore.stationList = this.sceneriesStore.stationList.filter(({ id }) => id != scenery.id);
      this.addRemovalChange(scenery);
    },

    showRoutesModal(scenery: SceneryRowItem) {
      this.sceneriesStore.currentStation = scenery;
    },
  },
});
</script>

<style lang="scss" scoped>
.table_container {
  overflow: auto;
  height: calc(100vh - 1em);
  margin: 0.5em 0;
  width: 100%;
}

table tr.current {
  outline: 1px solid white;
}

table td.routes {
  font-size: 0.9em;
  min-width: 150px;
}
</style>
