<template>
  <div class="manager-view centerDiv">

    <div v-if="!managerName" class="row">
      <div class="row">
        <h1 style="text-align:center">Active</h1>
      </div>
      <div class="row">
        <div class="col-sm-2 my-1" v-for="manager in activeManagers.slice().sort((a, b) => a.name.localeCompare(b.name))"
          :key="manager.id">
          <RouterLink :to="{ name: 'managers', params: { managerName: manager.name } }">
            <h5>{{ manager.name }}</h5>
          </RouterLink>
        </div>
      </div>

      <div class="row">
        <h1 style="text-align:center">Retired</h1>
      </div>
      <div class="row">
        <div class="col-sm-2 my-1" v-for="manager in retiredManagers.slice().sort((a, b) => a.name.localeCompare(b.name))"
          :key="manager.id">
          <RouterLink :to="{ name: 'managers', params: { managerName: manager.name } }">
            <h5>{{ manager.name }}</h5>
          </RouterLink>
        </div>
      </div>
    </div>
    <div v-else>
      <div class="row">
        <div class="col-sm-12">
          <h1 id="manager-name">{{ managerName }}</h1>
        </div>

        <div class="col-sm-12" v-if="managerModel">
          <!-- <h3 id="manager-record">Manager Record: {{ managerModel.managerWins }}-{{ managerModel.managerLosses }}</h3> -->
          <h3 id="manager-record">Career Record: {{ managerModel.teamWins }}-{{ managerModel.teamLosses }}</h3>
        </div>

        <div class="row">
          <div class="col-sm-4">
            <h3 style="text-align: center">Teams Managed</h3>
            <div class="table-responsive-xl">
              <table style="text-align: center" class="table table-sm table-striped" id="manager-teams-table">
                <thead class="thead-dark">
                  <tr>
                    <th>Season</th>
                    <th>Team</th>
                    <th>Record</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="row in teamsManagedRows" :key="row.season">
                    <td>{{ row.season }}</td>
                    <td>
                      <RouterLink
                        :to="{ name: 'team', params: { seasonNumber: row.season, teamAbbreviation: row.teamAbbreviation } }">
                        {{ row.teamName }}
                      </RouterLink>
                    </td>
                    <td>{{ row.record }}</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>

          <div class="col-sm-5">
            <h3 style="text-align: center">Awards Received</h3>
            <div class="table-responsive-xl">
              <table style="text-align: center" class="table table-sm table-striped" id="manager-awards-table">
                <thead class="thead-dark">
                  <tr>
                    <th>Season</th>
                    <th>Award</th>
                    <th>Team</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="award in managerAwards.slice().sort((a1, a2) => a2.season - a1.season)" :key="award.id">
                    <td>{{ award.season }}</td>
                    <td>{{ award.name }}</td>
                    <td>
                      <RouterLink
                        :to="{ name: 'team', params: { seasonNumber: award.season, teamAbbreviation: award.team!.abbrev } }">
                        {{ award.team!.sname }}
                      </RouterLink>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import type { Manager, Team } from '@/services/apiResponseTypes'
import type { Award } from '@/services/awardsService'
import { fetchActiveManagers, fetchRetiredManagers } from '@/services/managerService'
import { fetchTeamsByManagerId } from '@/services/teamsService'
import { fetchAwardsByManagerId } from '@/services/awardsService'
import { fetchStandingByTeam, type TeamStanding } from '@/services/standingsService'
import { isNotUndefined } from '@/services/utilities'

interface ManagerModel {
  managerWins: number
  managerLosses: number
  teamWins: number
  teamLosses: number
}

export default {
  name: 'ManagerView',
  data() {
    return {
      activeManagers: [] as Manager[],
      retiredManagers: [] as Manager[],
      managerTeams: [] as Team[],
      managerTeamStandings: [] as TeamStanding[],
      managerAwards: [] as Award[]
    }
  },
  props: {
    managerName: { type: String, default: undefined },
  },
  computed: {
    selectedManager(): Manager | undefined {
      if (!this.managerName) return undefined

      return this.activeManagers.find(manager => manager.name === this.managerName) ?? this.retiredManagers.find(manager => manager.name === this.managerName)
    },
    managerModel(): ManagerModel | undefined {
      if (!this.selectedManager) return undefined

      return this.managerTeamStandings.reduce((acc, val) => {
        return {
          managerWins: acc.managerWins + val.wins,
          managerLosses: acc.managerLosses + val.losses,
          teamWins: acc.managerWins + val.wins,
          teamLosses: acc.managerLosses + val.losses
        }
      }, {
        managerWins: 0,
        managerLosses: 0,
        teamWins: 0,
        teamLosses: 0
      }
      )
    },
    teamsManagedRows(): { season: number, teamName: string, teamAbbreviation: string, record: string }[] {
      return this.managerTeams
        .map(team => {
          const standing = this.managerTeamStandings.find(ts => ts.season === team.season)
          const record = `${standing?.wins ?? 0}-${standing?.losses ?? 0}`
          return { season: team.season, teamName: team.sname, teamAbbreviation: team.abbrev, record }
        })
        .sort((r1, r2) => r2.season - r1.season)
    }
  },
  created() {
    this.fetchData()
  },
  watch: {
    managerName(newValue, oldValue) {
      if (newValue !== oldValue)
        this.fetchManagerData()
    }
  },
  methods: {
    async fetchData(): Promise<void> {
      this.activeManagers = await fetchActiveManagers()
      this.retiredManagers = await fetchRetiredManagers()
      await this.fetchManagerData()
    },
    async fetchManagerData(): Promise<void> {
      // need to fetch manager/team wins/losses and awards
      // fetch all teams managed, then surface managerModel as a computed instead of data
      if (!this.selectedManager) return

      this.managerTeams = await fetchTeamsByManagerId(this.selectedManager.id)
      this.managerTeamStandings = (await Promise.all(this.managerTeams.flatMap(team =>
        fetchStandingByTeam(team)
      ))).filter(isNotUndefined)
      this.managerAwards = await fetchAwardsByManagerId(this.selectedManager.id)
    }
  }
}
</script>
