<template>
  <div class="team-management-overview">
    <div class="team-management-hero">
      <div class="team-management-hero-header">
        <div class="team-management-hero-copy">
          <h2>{{ $t('teamManagement.title') }}</h2>
          <p>{{ $t('teamManagement.subtitle') }}</p>
        </div>
        <div class="team-management-hero-actions">
          <div class="team-management-season-selector">
            <span class="team-management-hero-label">{{ $t('teamManagement.season') }}</span>
            <SeasonSelector
              :model-value="selectedSeasonId"
              :show-current-season="true"
              @update:model-value="$emit('update:selected-season-id', $event)"
              @season-change="$emit('season-change', $event)"
            />
          </div>
        </div>
      </div>

      <div v-if="schedulerJobs.rating_updates || schedulerJobs.match_results" class="scheduler-jobs-summary">
        <div class="scheduler-jobs-summary-copy">
          <strong>{{ $t('teamManagement.automaticJobs') }}</strong>
          <span v-if="schedulerJobs.rating_updates?.lastRun || schedulerJobs.match_results?.lastRun" class="scheduler-jobs-summary-text">
            {{ $t('teamManagement.lastRun') }}:
            {{ formatJobDate(schedulerJobs.match_results?.lastRun || schedulerJobs.rating_updates?.lastRun) }}
          </span>
        </div>
        <button type="button" class="scheduler-jobs-toggle" @click="$emit('toggle-job-details')">
          <span class="scheduler-jobs-toggle-icon">{{ showGlobalJobDetails ? '▾' : '▸' }}</span>
          <span class="scheduler-jobs-toggle-text">{{ showGlobalJobDetails ? $t('common.close') : $t('common.details') }}</span>
        </button>
      </div>

      <div class="team-management-summary">
        <div class="team-summary-card">
          <span class="team-summary-label">{{ $t('teamManagement.teams') }}</span>
          <strong class="team-summary-value">{{ teamsCount }}</strong>
        </div>
        <div class="team-summary-card">
          <span class="team-summary-label">{{ $t('teamManagement.fullyConfigured') }}</span>
          <strong class="team-summary-value">{{ fullyConfiguredTeamsCount }}</strong>
        </div>
        <div class="team-summary-card">
          <span class="team-summary-label">{{ $t('teamManagement.partiallyConfigured') }}</span>
          <strong class="team-summary-value">{{ partiallyConfiguredTeamsCount }}</strong>
        </div>
        <div class="team-summary-card">
          <span class="team-summary-label">{{ $t('teamManagement.noLeague') }}</span>
          <strong class="team-summary-value">{{ teamsWithoutLeagueCount }}</strong>
        </div>
      </div>
    </div>

    <div v-if="showGlobalJobDetails && (schedulerJobs.rating_updates || schedulerJobs.match_results)" class="scheduler-jobs-info">
      <div class="job-info" v-if="schedulerJobs.rating_updates?.lastRun">
        <span class="job-label">🔄 {{ $t('teamManagement.ratingUpdates') }}:</span>
        <span class="job-details">
          {{ $t('teamManagement.lastRun') }}: {{ formatJobDate(schedulerJobs.rating_updates.lastRun) }}
          <span v-if="schedulerJobs.rating_updates.updatedCount !== null" class="job-count">
            ({{ schedulerJobs.rating_updates.updatedCount }} {{ $t('teamManagement.updated') }})
          </span>
          <span v-if="!schedulerJobs.rating_updates.success" class="job-error">⚠️ {{ $t('teamManagement.error') }}</span>
        </span>
      </div>
      <div class="job-info" v-if="schedulerJobs.match_results?.lastRun">
        <div class="job-header">
          <span class="job-label">📊 {{ $t('teamManagement.matchResults') }}:</span>
          <span class="job-details">
            {{ $t('teamManagement.lastRun') }}: {{ formatJobDate(schedulerJobs.match_results.lastRun) }}
            <span v-if="schedulerJobs.match_results.fetchedCount !== null" class="job-count">
              ({{ schedulerJobs.match_results.fetchedCount }} {{ $t('teamManagement.fetched') }})
            </span>
            <span v-if="!schedulerJobs.match_results.success" class="job-error">⚠️ {{ $t('teamManagement.error') }}</span>
          </span>
        </div>
        <div v-if="filteredTeamDetails.length > 0" class="team-details">
          <div v-for="team in filteredTeamDetails" :key="team.clubTeamId" class="team-detail-item">
            <span class="team-name">{{ team.teamName }}</span>
            <span v-if="team.success" class="team-status success">✓</span>
            <span v-else class="team-status error">✗</span>
          </div>
        </div>
      </div>
    </div>

    <div class="teams-list">
      <div class="teams-list-header">
        <h3>{{ $t('teamManagement.teams') }} ({{ filteredTeams.length }}) - {{ $t('teamManagement.season') }} {{ currentSeasonLabel || $t('teamManagement.seasonUnknown') }}</h3>
        <div class="teams-list-tools">
          <input
            :value="teamSearchQuery"
            type="search"
            class="team-search-input"
            :placeholder="$t('teamManagement.searchTeams')"
            @input="$emit('update:team-search-query', $event.target.value)"
          >
          <div class="team-filter-chips">
            <button type="button" class="team-filter-chip" :class="{ active: teamFilter === 'all' }" @click="$emit('update:team-filter', 'all')">{{ $t('teamManagement.filterAll') }}</button>
            <button type="button" class="team-filter-chip" :class="{ active: teamFilter === 'configured' }" @click="$emit('update:team-filter', 'configured')">{{ $t('teamManagement.filterConfigured') }}</button>
            <button type="button" class="team-filter-chip" :class="{ active: teamFilter === 'attention' }" @click="$emit('update:team-filter', 'attention')">{{ $t('teamManagement.filterNeedsAttention') }}</button>
            <button type="button" class="team-filter-chip" :class="{ active: teamFilter === 'noLeague' }" @click="$emit('update:team-filter', 'noLeague')">{{ $t('teamManagement.filterNoLeague') }}</button>
          </div>
          <button type="button" class="btn-primary team-create-button" @click="$emit('create-new-team')">
            {{ $t('teamManagement.createNewTeam') }}
          </button>
        </div>
      </div>

      <div v-if="teamsCount === 0" class="no-teams">
        <p>{{ $t('teamManagement.noTeamsYet') }}</p>
      </div>
      <div v-else-if="filteredTeams.length === 0" class="no-teams">
        <p>{{ $t('teamManagement.noMatchingTeams') }}</p>
      </div>

      <div v-else class="teams-grid">
        <TeamListCard
          v-for="team in filteredTeams"
          :key="team.id"
          :team="team"
          :active="activeTeamId === team.id"
          :status="getMyTischtennisStatus(team)"
          :league-name="team.league ? team.league.name : $t('teamManagement.noLeague')"
          :season-label="team.season?.season || $t('teamManagement.unknown')"
          :created-text="formatDate(team.createdAt)"
          :last-updated-text="getTeamJobInfo(team) && getTeamJobInfo(team).lastRun ? formatJobDate(getTeamJobInfo(team).lastRun) : $t('teamManagement.never')"
          :has-code-list="getTeamDocuments(team.id, 'code_list').length > 0"
          :has-pin-list="getTeamDocuments(team.id, 'pin_list').length > 0"
          @edit="$emit('edit-team', team)"
          @delete="$emit('delete-team', team)"
          @show-code-list="$emit('show-pdf-dialog', team.id, 'code_list')"
          @show-pin-list="$emit('show-pdf-dialog', team.id, 'pin_list')"
        />
      </div>
    </div>
  </div>
</template>

<script>
import SeasonSelector from '../SeasonSelector.vue';
import TeamListCard from './TeamListCard.vue';

export default {
  name: 'TeamManagementOverview',
  components: {
    SeasonSelector,
    TeamListCard
  },
  props: {
    selectedSeasonId: { type: [Number, String, null], default: null },
    schedulerJobs: { type: Object, required: true },
    showGlobalJobDetails: { type: Boolean, required: true },
    teamsCount: { type: Number, required: true },
    fullyConfiguredTeamsCount: { type: Number, required: true },
    partiallyConfiguredTeamsCount: { type: Number, required: true },
    teamsWithoutLeagueCount: { type: Number, required: true },
    filteredTeamDetails: { type: Array, required: true },
    formatJobDate: { type: Function, required: true },
    filteredTeams: { type: Array, required: true },
    currentSeasonLabel: { type: String, default: '' },
    teamSearchQuery: { type: String, required: true },
    teamFilter: { type: String, required: true },
    activeTeamId: { type: [Number, null], default: null },
    getMyTischtennisStatus: { type: Function, required: true },
    formatDate: { type: Function, required: true },
    getTeamJobInfo: { type: Function, required: true },
    getTeamDocuments: { type: Function, required: true }
  },
  emits: [
    'update:selected-season-id',
    'season-change',
    'toggle-job-details',
    'update:team-search-query',
    'update:team-filter',
    'create-new-team',
    'edit-team',
    'delete-team',
    'show-pdf-dialog'
  ]
};
</script>

<style scoped>
.team-management-overview {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.team-management-hero,
.scheduler-jobs-info,
.teams-list {
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius);
  background: var(--background-light);
  padding: 0.9rem;
}

.team-management-hero-header,
.scheduler-jobs-summary,
.teams-list-header,
.teams-list-tools,
.team-management-summary {
  display: flex;
  flex-wrap: wrap;
  gap: 0.85rem;
}

.team-management-hero-header,
.scheduler-jobs-summary,
.teams-list-header {
  justify-content: space-between;
  align-items: flex-start;
}

.team-management-hero-copy h2,
.teams-list-header h3 {
  margin: 0;
}

.team-management-hero-copy p {
  margin: 0.25rem 0 0;
  color: var(--text-muted);
}

.team-summary-card {
  min-width: 150px;
  flex: 1 1 150px;
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius);
  background: white;
  padding: 0.75rem;
}

.team-summary-label,
.scheduler-jobs-summary-text {
  color: var(--text-muted);
  font-size: 0.85rem;
}

.team-summary-value {
  display: block;
  margin-top: 0.2rem;
}

.teams-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 1.1rem;
  margin-top: 0.2rem;
}

.team-filter-chips {
  display: flex;
  flex-wrap: wrap;
  gap: 0.45rem;
}

.team-filter-chip {
  border: 1px solid var(--border-color);
  background: white;
  border-radius: 999px;
  padding: 0.4rem 0.75rem;
  color: var(--text-color) !important;
}

.team-filter-chip.active {
  background: var(--primary-light);
  border-color: var(--primary-color);
  color: var(--primary-dark) !important;
}

.team-search-input {
  min-width: 14rem;
}

.job-info {
  display: flex;
  flex-direction: column;
  gap: 0.4rem;
}

.team-details {
  display: flex;
  flex-wrap: wrap;
  gap: 0.45rem;
}

.team-detail-item {
  display: inline-flex;
  align-items: center;
  gap: 0.35rem;
  padding: 0.25rem 0.55rem;
  border-radius: 999px;
  background: white;
  border: 1px solid var(--border-color);
}

@media (max-width: 900px) {
  .teams-list-tools {
    width: 100%;
  }
}
</style>
