<template>
  <div class="club-archive-page">
    <header class="page-header card">
      <div>
        <p class="page-eyebrow">TT-Verein</p>
        <h2>Archiv</h2>
        <p class="page-subtitle">
          Inaktive Mitglieder und archivierte Vereinsvorgänge getrennt vom aktiven Tagesgeschäft.
        </p>
      </div>
      <button type="button" class="btn-secondary" @click="loadArchive" :disabled="loading || !currentClub">
        {{ loading ? 'Lädt…' : 'Neu laden' }}
      </button>
    </header>

    <section v-if="!currentClub" class="card empty-state">
      <h3>Kein Verein ausgewählt</h3>
      <p>Bitte zuerst einen Verein auswählen, um das Archiv zu laden.</p>
    </section>

    <template v-else>
      <p v-if="loadError" class="state-banner state-banner-error">{{ loadError }}</p>

      <section class="archive-stats-grid">
        <article class="card stat-card">
          <span class="stat-label">Ehemalige Mitglieder</span>
          <strong class="stat-value">{{ archive.summary?.inactiveMembers ?? 0 }}</strong>
        </article>
        <article class="card stat-card">
          <span class="stat-label">Archivierte Anfragen</span>
          <strong class="stat-value">{{ archive.summary?.archivedRequests ?? 0 }}</strong>
        </article>
        <article class="card stat-card">
          <span class="stat-label">Archivierte Aufgaben</span>
          <strong class="stat-value">{{ archive.summary?.archivedTasks ?? 0 }}</strong>
        </article>
        <article class="card stat-card">
          <span class="stat-label">Historische Forderungen</span>
          <strong class="stat-value">{{ archive.summary?.archivedClaims ?? 0 }}</strong>
        </article>
      </section>

      <section class="archive-notes card" v-if="archive.notes?.length">
        <h3>Hinweise</h3>
        <ul>
          <li v-for="note in archive.notes" :key="note">{{ note }}</li>
        </ul>
      </section>

      <section class="archive-section card">
        <div class="section-header">
          <div>
            <h3>Ehemalige Mitglieder</h3>
            <p>Mitglieder, die nicht mehr aktiv geführt werden.</p>
          </div>
          <button type="button" class="btn-secondary" @click="openMembersArchive">
            Mitglieder öffnen
          </button>
        </div>

        <p v-if="archive.inactiveMembers.length === 0" class="state-banner">Keine inaktiven Mitglieder im Archiv.</p>
        <div v-else class="table-wrap">
          <table class="archive-table">
            <thead>
              <tr>
                <th>Name</th>
                <th>E-Mail</th>
                <th>Ort</th>
                <th>Zuletzt geändert</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="member in archive.inactiveMembers" :key="`member-${member.id}`">
                <td>{{ member.displayName }}</td>
                <td>{{ member.email || '–' }}</td>
                <td>{{ member.city || '–' }}</td>
                <td>{{ formatDateTime(member.updatedAt || member.createdAt) }}</td>
                <td class="actions-cell">
                  <button type="button" class="btn-secondary" @click="openMember(member)">Öffnen</button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </section>

      <section class="archive-section card">
        <div class="section-header">
          <div>
            <h3>Archivierte Anfragen</h3>
            <p>Abgelegte Vorgänge aus Kontakt, Probetraining, Mitgliedschaft oder Sponsoring.</p>
          </div>
          <button type="button" class="btn-secondary" @click="openRequestsArchive">
            Anfragen öffnen
          </button>
        </div>

        <p v-if="archive.archivedRequests.length === 0" class="state-banner">Keine archivierten Anfragen vorhanden.</p>
        <div v-else class="table-wrap">
          <table class="archive-table">
            <thead>
              <tr>
                <th>Typ</th>
                <th>Betreff</th>
                <th>Person</th>
                <th>Zuletzt geändert</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="request in archive.archivedRequests" :key="`request-${request.id}`">
                <td>{{ displayRequestType(request.requestType) }}</td>
                <td>{{ request.subject || '–' }}</td>
                <td>{{ request.personName || request.email || '–' }}</td>
                <td>{{ formatDateTime(request.updatedAt || request.createdAt) }}</td>
                <td class="actions-cell">
                  <button type="button" class="btn-secondary" @click="openRequest(request)">Öffnen</button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </section>

      <section class="archive-section card">
        <div class="section-header">
          <div>
            <h3>Archivierte Aufgaben</h3>
            <p>Aufgaben, die bewusst aus dem aktiven Arbeitsvorrat ins Archiv verschoben wurden.</p>
          </div>
          <button type="button" class="btn-secondary" @click="openTasksArchive">
            Aufgaben öffnen
          </button>
        </div>

        <p v-if="archive.archivedTasks.length === 0" class="state-banner">Keine archivierten Aufgaben vorhanden.</p>
        <div v-else class="table-wrap">
          <table class="archive-table">
            <thead>
              <tr>
                <th>Titel</th>
                <th>Typ</th>
                <th>Priorität</th>
                <th>Archiviert am</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="task in archive.archivedTasks" :key="`task-${task.id}`">
                <td>{{ task.title }}</td>
                <td>{{ task.taskType || '–' }}</td>
                <td>{{ displayPriority(task.priority) }}</td>
                <td>{{ formatDateTime(task.archivedAt || task.updatedAt) }}</td>
                <td class="actions-cell">
                  <button type="button" class="btn-secondary" @click="openTask(task)">Öffnen</button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </section>

      <section class="archive-section card">
        <div class="section-header">
          <div>
            <h3>Historische Forderungen</h3>
            <p>Stornierte, abgeschriebene oder ausdrücklich archivierte Forderungen.</p>
          </div>
        </div>

        <p v-if="archive.archivedClaims.length === 0" class="state-banner">Keine historischen Forderungen vorhanden.</p>
        <div v-else class="table-wrap">
          <table class="archive-table">
            <thead>
              <tr>
                <th>Mitglied</th>
                <th>Typ</th>
                <th>Status</th>
                <th>Fällig</th>
                <th>Betrag</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="claim in archive.archivedClaims" :key="`claim-${claim.id}`">
                <td>{{ claim.memberName || '–' }}</td>
                <td>{{ claim.claimType || '–' }}</td>
                <td>{{ displayClaimStatus(claim.status) }}</td>
                <td>{{ formatDate(claim.dueOn) }}</td>
                <td>{{ formatCurrency(claim.amountCents, claim.currencyCode) }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </section>
    </template>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import apiClient from '../apiClient.js';
import { safeErrorMessage } from '../utils/dialogUtils.js';

function createEmptyArchive() {
  return {
    summary: {
      inactiveMembers: 0,
      archivedRequests: 0,
      archivedTasks: 0,
      archivedClaims: 0,
    },
    inactiveMembers: [],
    archivedRequests: [],
    archivedTasks: [],
    archivedClaims: [],
    notes: [],
  };
}

export default {
  name: 'ClubArchiveView',
  data() {
    return {
      loading: false,
      loadError: '',
      archive: createEmptyArchive(),
    };
  },
  computed: {
    ...mapGetters(['currentClub']),
  },
  watch: {
    currentClub: {
      immediate: true,
      async handler(newClub) {
        if (!newClub) {
          this.archive = createEmptyArchive();
          return;
        }
        await this.loadArchive();
      },
    },
  },
  methods: {
    async loadArchive() {
      if (!this.currentClub) return;
      this.loading = true;
      this.loadError = '';
      try {
        const response = await apiClient.get(`/club-archive/${this.currentClub}`);
        if (!response || response.status < 200 || response.status >= 300) {
          throw new Error(response?.data?.error || 'Archiv konnte nicht geladen werden.');
        }
        this.archive = response.data || createEmptyArchive();
      } catch (error) {
        this.archive = createEmptyArchive();
        this.loadError = safeErrorMessage(error, 'Archiv konnte nicht geladen werden.');
      } finally {
        this.loading = false;
      }
    },
    formatDate(value) {
      if (!value) return '–';
      const date = new Date(value);
      if (Number.isNaN(date.getTime())) return '–';
      return new Intl.DateTimeFormat('de-DE', { dateStyle: 'medium' }).format(date);
    },
    formatDateTime(value) {
      if (!value) return '–';
      const date = new Date(value);
      if (Number.isNaN(date.getTime())) return '–';
      return new Intl.DateTimeFormat('de-DE', {
        dateStyle: 'medium',
        timeStyle: 'short',
      }).format(date);
    },
    formatCurrency(amountCents, currencyCode = 'EUR') {
      return new Intl.NumberFormat('de-DE', {
        style: 'currency',
        currency: currencyCode || 'EUR',
      }).format(Number(amountCents || 0) / 100);
    },
    displayRequestType(type) {
      return {
        contact: 'Kontakt',
        trial_training: 'Probetraining',
        membership: 'Mitgliedschaft',
        sponsoring: 'Sponsoring',
      }[type] || type || 'Anfrage';
    },
    displayPriority(priority) {
      return {
        low: 'Niedrig',
        normal: 'Normal',
        high: 'Hoch',
        urgent: 'Dringend',
      }[priority] || priority || '–';
    },
    displayClaimStatus(status) {
      return {
        cancelled: 'Storniert',
        written_off: 'Abgeschrieben',
        paid: 'Bezahlt',
        open: 'Offen',
        partially_paid: 'Teilbezahlt',
      }[status] || status || '–';
    },
    openMembersArchive() {
      this.$router.push({ path: '/members', query: { scope: 'inactive' } });
    },
    openMember(member) {
      this.$router.push({ path: '/members', query: { scope: 'inactive', memberId: String(member.id) } });
    },
    openRequestsArchive() {
      this.$router.push({ path: '/club-requests', query: { status: 'archived' } });
    },
    openRequest(request) {
      this.$router.push({ path: '/club-requests', query: { status: 'archived', requestId: String(request.id) } });
    },
    openTasksArchive() {
      this.$router.push({ path: '/club-tasks', query: { status: 'archived' } });
    },
    openTask(task) {
      this.$router.push({ path: '/club-tasks', query: { status: 'archived', taskId: String(task.id) } });
    },
  },
};
</script>

<style scoped>
.club-archive-page {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.page-header,
.empty-state,
.archive-notes,
.archive-section {
  padding: 1.25rem;
}

.page-header {
  display: flex;
  justify-content: space-between;
  gap: 1rem;
  align-items: flex-start;
}

.page-eyebrow {
  margin: 0 0 0.35rem;
  color: var(--text-light);
  text-transform: uppercase;
  letter-spacing: 0.08em;
  font-size: 0.8rem;
  font-weight: 700;
}

.page-header h2,
.archive-section h3,
.archive-notes h3 {
  margin: 0;
}

.page-subtitle,
.section-header p {
  margin: 0.35rem 0 0;
  color: var(--text-secondary);
}

.archive-stats-grid {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 1rem;
}

.stat-card {
  padding: 1rem;
}

.stat-label {
  display: block;
  color: var(--text-light);
  font-size: 0.9rem;
}

.stat-value {
  display: block;
  margin-top: 0.35rem;
  font-size: 1.6rem;
}

.archive-notes ul {
  margin: 0.75rem 0 0;
  padding-left: 1.25rem;
}

.archive-notes li + li {
  margin-top: 0.35rem;
}

.section-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 1rem;
  margin-bottom: 1rem;
}

.table-wrap {
  overflow-x: auto;
}

.archive-table {
  width: 100%;
  border-collapse: collapse;
}

.archive-table th,
.archive-table td {
  padding: 0.8rem 0.9rem;
  border-bottom: 1px solid rgba(24, 70, 54, 0.08);
  text-align: left;
  vertical-align: top;
}

.archive-table th {
  color: var(--text-primary);
  font-size: 0.86rem;
  font-weight: 700;
  background: rgba(24, 70, 54, 0.06);
}

.actions-cell {
  width: 1%;
  white-space: nowrap;
}

@media (max-width: 960px) {
  .archive-stats-grid {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}

@media (max-width: 640px) {
  .page-header,
  .section-header {
    flex-direction: column;
  }

  .archive-stats-grid {
    grid-template-columns: 1fr;
  }
}
</style>
