<template>
  <div class="row">
    <div class="col-sm-12">
      <div class="table-responsive-xl">
        <table class="table table-sm table-striped" id="table-batting-stats">
          <thead class="thead-dark">
            <tr style="min-width: 75px">
              <th @click="sortBy('teamName')" :class="getArrow('teamName')">Team</th>
              <th @click="sortBy('pa')" :class="getArrow('pa')">PA</th>
              <th @click="sortBy('ab')" :class="getArrow('ab')">AB</th>
              <th @click="sortBy('run')" :class="getArrow('run')">R</th>
              <th @click="sortBy('hit')" :class="getArrow('hit')">H</th>
              <th @click="sortBy('double')" :class="getArrow('double')">2B</th>
              <th @click="sortBy('triple')" :class="getArrow('triple')">3B</th>
              <th @click="sortBy('hr')" :class="getArrow('hr')">HR</th>
              <th @click="sortBy('rbi')" :class="getArrow('rbi')">RBI</th>
              <th @click="sortBy('sb')" :class="getArrow('sb')">SB</th>
              <th @click="sortBy('cs')" :class="getArrow('cs')">CS</th>
              <th @click="sortBy('bb')" :class="getArrow('bb')">BB</th>
              <th @click="sortBy('so')" :class="getArrow('so')">SO</th>
              <th @click="sortBy('avg')" :class="getArrow('avg')">BA</th>
              <th @click="sortBy('obp')" :class="getArrow('obp')">OBP</th>
              <th @click="sortBy('slg')" :class="getArrow('slg')">SLG</th>
              <th @click="sortBy('ops')" :class="getArrow('ops')">OPS</th>
              <th @click="sortBy('woba')" :class="getArrow('woba')">wOBA</th>
              <th @click="sortBy('kPct')" :class="getArrow('kPct')">K%</th>
              <th @click="sortBy('bphr')" :class="getArrow('bphr')">BPHR</th>
              <th @click="sortBy('bpfo')" :class="getArrow('bpfo')">BPFO</th>
              <th @click="sortBy('bp1b')" :class="getArrow('bp1b')">BP1B</th>
              <th @click="sortBy('bplo')" :class="getArrow('bplo')">BPLO</th>
              <th @click="sortBy('gidp')" :class="getArrow('gidp')">GIDP</th>
              <th @click="sortBy('hbp')" :class="getArrow('hbp')">HBP</th>
              <th @click="sortBy('sac')" :class="getArrow('sac')">SAC</th>
              <th @click="sortBy('ibb')" :class="getArrow('ibb')">IBB</th>
            </tr>
          </thead>
          <tbody v-if="battingStats.length" >
            <tr v-for="stat in battingStats" :key="stat.player.bbref_id">
              <td>
                <RouterLink
                  :to="{ name: 'team', params: { seasonNumber: seasonNumber, teamAbbreviation: stat.team.abbrev } }">
                  {{ stat.team.sname }}
                </RouterLink>
              </td>
              <td>{{ stat.pa }}</td>
              <td>{{ stat.ab }}</td>
              <td>{{ stat.run }}</td>
              <td>{{ stat.hit }}</td>
              <td>{{ stat.double }}</td>
              <td>{{ stat.triple }}</td>
              <td>{{ stat.hr }}</td>
              <td>{{ stat.rbi }}</td>
              <td>{{ stat.sb }}</td>
              <td>{{ stat.cs }}</td>
              <td>{{ stat.bb }}</td>
              <td>{{ stat.so }}</td>
              <td>{{ stat.avg.toFixed(3) }}</td>
              <td>{{ stat.obp.toFixed(3) }}</td>
              <td>{{ stat.slg.toFixed(3) }}</td>
              <td>{{ stat.ops.toFixed(3) }}</td>
              <td>{{ stat.woba.toFixed(3) }}</td>
              <td>{{ stat.kPct }}</td>
              <td>{{ stat.bphr }}</td>
              <td>{{ stat.bpfo }}</td>
              <td>{{ stat.bp1b }}</td>
              <td>{{ stat.bplo }}</td>
              <td>{{ stat.gidp }}</td>
              <td>{{ stat.hbp }}</td>
              <td>{{ stat.sac }}</td>
              <td>{{ stat.ibb }}</td>
            </tr>
          </tbody>
          <tfoot v-if="battingStats.length" >
            <tr v-if="totalBattingStat">
              <th>Total</th>
              <th>{{ totalBattingStat.pa }}</th>
              <th>{{ totalBattingStat.ab }}</th>
              <th>{{ totalBattingStat.run }}</th>
              <th>{{ totalBattingStat.hit }}</th>
              <th>{{ totalBattingStat.double }}</th>
              <th>{{ totalBattingStat.triple }}</th>
              <th>{{ totalBattingStat.hr }}</th>
              <th>{{ totalBattingStat.rbi }}</th>
              <th>{{ totalBattingStat.sb }}</th>
              <th>{{ totalBattingStat.cs }}</th>
              <th>{{ totalBattingStat.bb }}</th>
              <th>{{ totalBattingStat.so }}</th>
              <th>{{ totalBattingStat.avg.toFixed(3) }}</th>
              <th>{{ totalBattingStat.obp.toFixed(3) }}</th>
              <th>{{ totalBattingStat.slg.toFixed(3) }}</th>
              <th>{{ totalBattingStat.ops.toFixed(3) }}</th>
              <th>{{ totalBattingStat.woba.toFixed(3) }}</th>
              <th>{{ calculateStrikeoutPercent(totalBattingStat) }}</th>
              <th>{{ totalBattingStat.bphr }}</th>
              <th>{{ totalBattingStat.bpfo }}</th>
              <th>{{ totalBattingStat.bp1b }}</th>
              <th>{{ totalBattingStat.bplo }}</th>
              <th>{{ totalBattingStat.gidp }}</th>
              <th>{{ totalBattingStat.hbp }}</th>
              <th>{{ totalBattingStat.sac }}</th>
              <th>{{ totalBattingStat.ibb }}</th>
            </tr>
          </tfoot>
        </table>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { aggregateBattingStats, fetchTeamBattingStatsBySeason, type BattingStat } from '@/services/battingStatsService'

interface ExtendedBattingStat extends BattingStat {
  teamName: string
  kPct: string
}

export default {
  name: 'LeaderboardTeamBattingTable',
  props: {
    seasonNumber: { type: Number, required: true }
  },
  data() {
    return {
      battingStats: [] as ExtendedBattingStat[],
      sortKey: 'teamName' as keyof ExtendedBattingStat,
      sortOrder: 1
    }
  },
  computed: {
    totalBattingStat(): BattingStat | undefined {
      if (this.battingStats.length > 0) {
        return aggregateBattingStats(this.battingStats)
      }

      return undefined
    }
  },
  created() {
    this.fetchData()
  },
  watch: {
    seasonNumber(newValue, oldValue) {
      if (newValue !== oldValue){
        this.battingStats = []
        this.sortKey = 'teamName'
        this.sortOrder = 1
        this.fetchData()
      }
    }
  },
  methods: {
    async fetchData(): Promise<void> {
      const unsortedBattingStats: BattingStat[] = await fetchTeamBattingStatsBySeason(this.seasonNumber)
      this.battingStats = unsortedBattingStats
        .map(s => ({...s, teamName: s.team.sname, kPct: this.calculateStrikeoutPercent(s)}))
        .sort((s1, s2) => s2.teamName < s1.teamName ? 1 : -1)
    },
    sortBy(stat: keyof ExtendedBattingStat): void {
      this.setKey(stat)
      
      this.battingStats.sort((s1, s2) => s2[stat] < s1[stat] ? this.sortOrder : -1 * this.sortOrder)
    },
    setKey(stat: keyof ExtendedBattingStat): void {
      if (this.sortKey === stat) {
        // if key currently selected, flip sort order
        this.sortOrder *= -1
      } else {
        this.sortKey = stat
        this.sortOrder = stat === 'teamName' ? 1 : -1
      }
    },
    getArrow(stat: keyof ExtendedBattingStat): string {
      if (this.sortKey !== stat) return 'faux-arrow'
      
      return this.sortOrder > 0 ? 'up' : 'down'
    },
    calculateStrikeoutPercent(stat: BattingStat): string {
      if (!stat.pa) return 'N/A'
      return (stat.so * 100 / stat.pa).toFixed(1)
    }
  }
}
</script>

<style>
.up::after {
  content: "▵"
}
.down::after {
  content: "▿"
}
.faux-arrow::after {
  opacity: 0;
  content: "▿"
}
</style>
