<template>
  <div class="manager" v-if="store.user">
    <RoutesModal v-if="store.currentStation" />
    <UpdateCard v-if="store.changesResponse.length > 0" />

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

    <div class="table_container">
      <table>
        <thead>
          <th v-for="header in headerNameList">{{ header }}</th>
          <th>Dostępność</th>
          <th>Usuń</th>
        </thead>

        <tbody>
          <tr v-for="(station, row) in store.sortedStationList" tabindex="0">
            <td v-for="(value, propName) in headerNameList" @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>

              <RouteList v-else-if="propName === 'routes'" :routes="station.routesInfo" />
              <!-- <span v-else-if="propName === 'routes'" v-html="getRouteNames(station.routesInfo)"></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="store.sortedStationList[row]['availability']"
                @input="(e) => changeAvailability(station, store.sortedStationList[row]['availability'], e)"
              >
                <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 { useStore } from '../store';
import { SceneryRowItem, Availability, AuthState } from '../types/types';
import RoutesModal from '../components/RoutesModal.vue';
import TableActions from '../components/TableActions.vue';
import UpdateCard from '../components/UpdateCard.vue';
import RouteList from '../components/RouteList.vue';

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

  data: () => ({
    AuthState,
    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',
      authors: 'Autorzy',
      routes: 'Szlaki',
      checkpoints: 'Posterunki',
      hidden: 'Ukryty',
    } as {
      [key: string]: string;
    },
  }),

  setup() {
    const store = useStore();
    return {
      store,
    };
  },

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

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

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

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

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

      if (stationListRow == -1) return;
      const oldValue = (this.store.stationList[stationListRow] as any)[propertyName];
      if (typeof oldValue === 'boolean') {
        (this.store.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.headerNameList[propertyName]}`, oldValue || '');
      if (newValue == null) return;
      (this.store.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.store.stationList.findIndex((station) => station.name == this.store.sortedStationList[row].name);

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

      this.store.stationList[stationListRow]['checkpoints'] = newCheckpoints;
      this.addChange(this.store.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.store.stationList = this.store.stationList.filter(({ id }) => id != scenery.id);
      this.addRemovalChange(scenery);
    },

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

<style lang="scss" scoped>
.table_container {
  overflow: auto;
  height: 100vh;
  margin: 0.5em 0;
}

table {
  text-align: center;
  color: white;
  position: relative;
  border-collapse: collapse;
  width: 100%;
  min-width: 1600px;
}

table thead {
  position: sticky;
  top: 0;
}

table th {
  padding: 0.4rem 0.45rem;
  background-color: #151b24;
  color: white;

  top: 0;
}

table tr {
  background-color: #2c394b;
  transition: background-color 100ms;
  text-overflow: ellipsis;
}

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

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

table tr:nth-child(even) {
  background-color: #334756;
}

table tr:hover {
  background-color: #1a293b;
  cursor: pointer;
}

table tr td {
  padding: 0.3rem 0.5rem;
  border: 1px solid #2c2c2c;
  overflow: auto;
  text-overflow: ellipsis;
}

td img {
  height: 1.45em;
  vertical-align: middle;
}
</style>
