<template>
  <div class="manager-view">
    <div class="view-wrapper">
      <div class="top-bar">
        <div class="brand">
          <img class="brand-image" src="/icon-logo.svg" alt="logo" />
          <h3>Edytor pojazdów</h3>
        </div>

        <div class="search-box">
          <input type="text" placeholder="Wyszukaj pojazd..." v-model="vehicleSearchValue" />
        </div>
      </div>

      <div class="table-wrapper">
        <table>
          <thead>
            <tr>
              <th style="width: 50px">#</th>
              <th style="width: 300px">Nazwa</th>
              <th style="width: 200px">Typ</th>
              <th style="width: 150px">Kabina (lok.)</th>
              <th style="width: 150px">Grupa</th>
              <th style="width: 150px">Tylko sponsorzy do</th>
              <th style="width: 150px">Tylko zespół</th>
            </tr>
          </thead>

          <tbody>
            <tr v-for="row in vehiclesTableComp" :key="row.vehicleRef.id">
              <td>{{ row.vehicleRef.id }}</td>
              <td
                class="editable"
                :data-pending="row.pendingChanges.name !== undefined && row.pendingChanges.name !== row.vehicleRef.name"
                @click="editRowPrimitive(row, VehicleEditRowKey.NAME)"
              >
                {{ row.pendingChanges.name ?? row.vehicleRef.name }}
              </td>
              <td
                class="editable"
                :data-pending="row.pendingChanges.type !== undefined && row.pendingChanges.type !== row.vehicleRef.type"
                @click="editRowPrimitive(row, VehicleEditRowKey.TYPE)"
              >
                {{ row.pendingChanges.type ?? row.vehicleRef.type }}
              </td>

              <td
                class="editable"
                :data-pending="row.pendingChanges.cabinName !== undefined && row.pendingChanges.cabinName !== row.vehicleRef.cabinName"
                @click="editRowPrimitive(row, VehicleEditRowKey.CABIN)"
              >
                {{ row.pendingChanges.cabinName ?? row.vehicleRef.cabinName }}
              </td>

              <td class="editable">{{ row.vehicleRef.group.name }}</td>
              <td
                class="editable"
                :data-pending="
                  row.pendingChanges.restrictions?.sponsorOnly !== undefined &&
                  row.pendingChanges.restrictions.sponsorOnly !== row.vehicleRef.restrictions?.sponsorOnly
                "
                @click="editRowRestrictions(row, VehicleEditRestrictionKey.SPONSOR_ONLY)"
              >
                <span v-if="row.pendingChanges.restrictions?.sponsorOnly !== undefined">
                  {{ new Date(row.pendingChanges.restrictions.sponsorOnly).toLocaleString() }}
                </span>

                <span v-else-if="row.vehicleRef.restrictions?.sponsorOnly !== undefined">
                  {{ new Date(row.vehicleRef.restrictions.sponsorOnly).toLocaleString() }}
                </span>

                <span v-else>❌</span>
              </td>
              <td
                class="editable"
                :data-pending="
                  row.pendingChanges.restrictions?.teamOnly !== undefined &&
                  row.pendingChanges.restrictions.teamOnly !== row.vehicleRef.restrictions?.teamOnly
                "
                @click="editRowRestrictions(row, VehicleEditRestrictionKey.TEAM_ONLY)"
              >
                <span v-if="row.pendingChanges.restrictions?.teamOnly !== undefined">
                  {{ row.pendingChanges.restrictions.teamOnly ? '✔️' : '❌' }}
                </span>

                <span v-else-if="row.vehicleRef.restrictions?.teamOnly !== undefined">
                  {{ row.vehicleRef.restrictions.teamOnly ? '✔️' : '❌' }}
                </span>

                <span v-else>❌</span>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import { useVehiclesStore } from '../stores/vehicles.store';
import { VehicleEditRowKey, IVehicleTableRow, VehicleEditRestrictionKey } from '../types/vehicles.types';
import { IVehicle } from '../types/vehicles.types';

export default defineComponent({
  data: () => ({
    vehiclesStore: useVehiclesStore(),
    vehicleSearchValue: '',
    VehicleEditRowKey,
    VehicleEditRestrictionKey,
  }),

  mounted() {
    this.vehiclesStore.fetchVehicles();
  },

  computed: {
    vehiclesTableComp() {
      return this.vehiclesStore.vehiclesTable
        .filter((row) => row.vehicleRef.name.toLowerCase().startsWith(this.vehicleSearchValue.trim().toLowerCase()))
        .sort((r1, r2) => {
          //v1.name.localeCompare(v2.name, 'pl-PL')

          return r1.vehicleRef.id - r2.vehicleRef.id;
        });
    },
  },

  methods: {
    editRowPrimitive(row: IVehicleTableRow, editKey: VehicleEditRowKey) {
      if (!(editKey in row.vehicleRef)) return;

      const promptValue = prompt('Zmień wartość:', row.vehicleRef[editKey]);
      if (promptValue == null) return;

      let changedVehileObj: Partial<IVehicle> = {};

      changedVehileObj[editKey] = promptValue;

      if (row.vehicleRef[editKey] === promptValue) {
        delete row.pendingChanges[editKey];
      } else row.pendingChanges = { ...row.pendingChanges, ...changedVehileObj };
    },

    editRowRestrictions(row: IVehicleTableRow, editKey: VehicleEditRestrictionKey) {
      let changedVehileObj: Partial<IVehicle> = {};

      if (editKey == VehicleEditRestrictionKey.TEAM_ONLY) {
        let nextTeamOnly = true;

        if (row.pendingChanges.restrictions?.teamOnly !== undefined) nextTeamOnly = !row.pendingChanges.restrictions.teamOnly;
        else if (row.vehicleRef.restrictions?.teamOnly !== undefined) nextTeamOnly = !row.vehicleRef.restrictions.teamOnly;

        changedVehileObj['restrictions'] = {
          teamOnly: nextTeamOnly,
        };

        if (row.vehicleRef.restrictions?.teamOnly === changedVehileObj.restrictions.teamOnly) delete changedVehileObj['restrictions']['teamOnly'];
      }

      if (editKey == VehicleEditRestrictionKey.SPONSOR_ONLY) {
        const promptValue = prompt('Zmień wartość (timestamp):', row.vehicleRef.restrictions?.sponsorOnly?.toString() ?? Date.now().toString());

        if (promptValue == null) return;

        if (promptValue.trim() == '') {
          changedVehileObj['restrictions'] = { sponsorOnly: undefined };
        } else if (!isNaN(parseInt(promptValue))) {
          const timestampPromptValue = parseInt(promptValue);

          changedVehileObj['restrictions'] = { sponsorOnly: timestampPromptValue };
        }
      }

      row.pendingChanges = { ...row.pendingChanges, ...changedVehileObj };

      // console.log(this.vehiclesStore.vehiclesTable.filter((v) => Object.keys(v.pendingChanges).length > 0));
    },

    getTableValueHTML(pendingValue: any, originalValue: any) {
      if (pendingValue === undefined) return `${originalValue ?? '-'}`;

      return `<s>${originalValue ?? '-'}</s> ${pendingValue}`;
    },
  },
});
</script>

<style lang="scss" scoped>
.view-wrapper {
  display: grid;
  grid-template-rows: auto 1fr;
  max-height: 100vh;
  padding: 0.5em;
}

.brand {
  display: flex;
  gap: 0.5em;
}

img.brand-image {
  max-width: 4em;
}

.search-box {
  margin-top: 1em;
}

.table-wrapper {
  overflow: auto;
  margin-top: 1em;
}

table {
  border-collapse: collapse;
  text-align: center;
  table-layout: fixed;

  thead {
    position: sticky;
    top: 0;
  }

  th {
    background-color: #2b2b2b;
  }

  tr:nth-child(odd) {
    background-color: #3b3b3b;
  }

  tr:nth-child(even) {
    background-color: #4c4c4c;
  }

  td.editable {
    cursor: pointer;
  }

  td[data-pending='true'] {
    background-color: lightgreen;
    color: black;
  }

  th,
  td {
    padding: 0.5em;
  }
}
</style>
