<template>
  <div class="mytt-account-page" :class="{ 'embedded-dialog-view': embedded }">
    <div class="page-container">
      <h1 v-if="!embedded">{{ $t('myTischtennisAccount.title') }}</h1>
      
      <div class="account-container">
        <div v-if="loading" class="loading">{{ $t('myTischtennisAccount.loading') }}</div>
        
        <div v-else-if="account" class="account-info">
          <div class="info-section">
            <h2>{{ $t('myTischtennisAccount.linkedAccount') }}</h2>
            
            <div class="info-row">
              <label>{{ $t('myTischtennisAccount.email') }}</label>
              <span>{{ account.email }}</span>
            </div>
            
            <div class="info-row">
              <label>{{ $t('myTischtennisAccount.passwordSaved') }}</label>
              <span>{{ accountStatus && accountStatus.hasPassword ? $t('myTischtennisAccount.yes') : $t('myTischtennisAccount.no') }}</span>
            </div>
            
            <div class="info-row" v-if="account.clubId">
              <label>{{ $t('myTischtennisAccount.club') }}</label>
              <span>{{ account.clubName }} ({{ account.clubId }}{{ account.fedNickname ? ' - ' + account.fedNickname : '' }})</span>
            </div>
            
            <div class="info-row" v-if="account.lastLoginSuccess">
              <label>{{ $t('myTischtennisAccount.lastSuccessfulLogin') }}</label>
              <span>{{ formatDate(account.lastLoginSuccess) }}</span>
            </div>
            
            <div class="info-row" v-if="account.lastLoginAttempt">
              <label>{{ $t('myTischtennisAccount.lastLoginAttempt') }}</label>
              <span>{{ formatDate(account.lastLoginAttempt) }}</span>
            </div>
            
            <div class="button-group">
              <button class="btn-primary" @click="openEditDialog">{{ $t('myTischtennisAccount.editAccount') }}</button>
              <button type="button" class="btn-secondary" @click="testConnection" :disabled="verifyingLogin">
                {{ verifyingLogin ? 'Login wird durchgeführt…' : $t('myTischtennisAccount.loginAgain') }}
              </button>
              <button class="btn-danger" @click="deleteAccount">{{ $t('myTischtennisAccount.unlinkAccount') }}</button>
            </div>
            <p v-if="loginFeedback.message" class="login-feedback" :class="`login-feedback--${loginFeedback.type}`">
              {{ loginFeedback.message }}
            </p>
          </div>
        </div>
        
        <div v-else class="no-account">
          <p>{{ $t('myTischtennisAccount.noAccountLinked') }}</p>
          <button class="btn-primary" @click="openEditDialog">{{ $t('myTischtennisAccount.linkAccount') }}</button>
        </div>

        <div class="info-box">
          <h3>{{ $t('myTischtennisAccount.aboutMyTischtennis') }}</h3>
          <p>{{ $t('myTischtennisAccount.aboutDescription') }}</p>
          <ul>
            <li>{{ $t('myTischtennisAccount.aboutFeature1') }}</li>
            <li>{{ $t('myTischtennisAccount.aboutFeature2') }}</li>
            <li>{{ $t('myTischtennisAccount.aboutFeature3') }}</li>
          </ul>
          <p><strong>{{ $t('messages.info') }}:</strong> {{ $t('myTischtennisAccount.aboutHint') }}</p>
        </div>
      </div>

      <!-- Edit Dialog -->
      <MyTischtennisDialog
        v-if="showDialog"
        :account="account"
        :login-mode="loginMode"
        @close="closeDialog"
        @saved="onAccountSaved"
        @logged-in="onLoggedIn"
      />
    </div>

    <!-- Info Dialog -->
    <InfoDialog
        v-model="infoDialog.isOpen"
        :title="infoDialog.title"
        :message="infoDialog.message"
        :details="infoDialog.details"
        :type="infoDialog.type"
    />
    
    <!-- Confirm Dialog -->
    <ConfirmDialog
        v-model="confirmDialog.isOpen"
        :title="confirmDialog.title"
        :message="confirmDialog.message"
        :details="confirmDialog.details"
        :type="confirmDialog.type"
        @confirm="handleConfirmResult(true)"
        @cancel="handleConfirmResult(false)"
    />
  </div>
</template>

<script>
import apiClient from '../apiClient.js';
import { getSafeErrorMessage } from '../utils/errorMessages.js';
import MyTischtennisDialog from '../components/MyTischtennisDialog.vue';

import InfoDialog from '../components/InfoDialog.vue';
import ConfirmDialog from '../components/ConfirmDialog.vue';
export default {
  name: 'MyTischtennisAccount',
  props: {
    embedded: {
      type: Boolean,
      default: false
    }
  },
  components: {
    MyTischtennisDialog,
    InfoDialog,
    ConfirmDialog
  },
  data() {
    return {
            // Dialog States
            infoDialog: {
                isOpen: false,
                title: '',
                message: '',
                details: '',
                type: 'info'
            },
            confirmDialog: {
                isOpen: false,
                title: '',
                message: '',
                details: '',
                type: 'info',
                resolveCallback: null
            },
      loading: true,
      account: null,
      accountStatus: null,
      showDialog: false,
      loginMode: false,
      verifyingLogin: false,
      loginFeedback: {
        type: '',
        message: ''
      }
    };
  },
  mounted() {
    this.loadAccount();
  },
  methods: {
        // Dialog Helper Methods
        async showInfo(title, message, details = '', type = 'info') {
            this.infoDialog = {
                isOpen: true,
                title,
                message,
                details,
                type
            };
        },
        
        async showConfirm(title, message, details = '', type = 'info') {
            return new Promise((resolve) => {
                this.confirmDialog = {
                    isOpen: true,
                    title,
                    message,
                    details,
                    type,
                    resolveCallback: resolve
                };
            });
        },
        
        handleConfirmResult(confirmed) {
            if (this.confirmDialog.resolveCallback) {
                this.confirmDialog.resolveCallback(confirmed);
                this.confirmDialog.resolveCallback = null;
            }
            this.confirmDialog.isOpen = false;
        },
        
    async loadAccount() {
      try {
        this.loading = true;
        const [accountResponse, statusResponse] = await Promise.all([
          apiClient.get('/mytischtennis/account'),
          apiClient.get('/mytischtennis/status')
        ]);
        this.account = accountResponse.data.account;
        this.accountStatus = statusResponse.data;
      } catch (error) {
        console.error('Fehler beim Laden des Accounts:', error);
        this.account = null;
        this.accountStatus = null;
        await this.showInfo(
          this.$t('messages.error'),
          this.$t('myTischtennisAccount.errorLoadingAccount'),
          '',
          'error'
        );
      } finally {
        this.loading = false;
      }
    },
    
    openEditDialog() {
      this.loginMode = false;
      this.showDialog = true;
    },
    
    closeDialog() {
      this.showDialog = false;
      this.loginMode = false;
    },
    
    async onAccountSaved() {
      this.closeDialog();
      await this.loadAccount();
      await this.showInfo(this.$t('messages.success'), this.$t('myTischtennisAccount.accountSaved'), '', 'success');
    },
    
    async onLoggedIn() {
      this.closeDialog();
      await this.loadAccount();
      await this.showInfo(this.$t('messages.success'), this.$t('myTischtennisAccount.loginSuccessful'), '', 'success');
    },
    
    async testConnection() {
      if (this.verifyingLogin) return;
      this.verifyingLogin = true;
      this.loginFeedback = {
        type: 'info',
        message: 'Login wird durchgeführt...'
      };
      try {
        // 1-Klick-Re-Login: zuerst gespeicherte Session/Passwort serverseitig verwenden
        const response = await apiClient.post('/mytischtennis/verify', {});
        if (response.status >= 400 || response?.data?.success === false) {
          const requestError = new Error('myTischtennis verify failed');
          requestError.response = response;
          throw requestError;
        }
        await this.loadAccount();
        this.loginFeedback = {
          type: 'success',
          message: 'Login erfolgreich.'
        };
        await this.showInfo(this.$t('messages.success'), this.$t('myTischtennisAccount.loginSuccessful'), '', 'success');
      } catch (error) {
        // Falls gespeicherte Daten nicht ausreichen, Passwort-Dialog öffnen
        const needsPassword = error?.response?.status === 400;

        if (needsPassword) {
          this.loginFeedback = {
            type: 'error',
            message: 'Bitte Passwort eingeben, um den Login erneut durchzuführen.'
          };
          this.showDialog = true;
          this.loginMode = true;
          this.verifyingLogin = false;
          return;
        }

        const message = getSafeErrorMessage(error, this.$t('myTischtennisAccount.errorLoadingAccount'));
        this.loginFeedback = {
          type: 'error',
          message
        };
        await this.showInfo(this.$t('messages.error'), message, '', 'error');
      } finally {
        this.verifyingLogin = false;
      }
    },
    
    async deleteAccount() {
      const confirmed = await this.showConfirm(
        this.$t('myTischtennisAccount.unlinkAccountTitle'),
        this.$t('myTischtennisAccount.unlinkAccountConfirm'),
        '',
        'danger'
      );
      
      if (!confirmed) return;
      
      try {
        await apiClient.delete('/mytischtennis/account');
        this.account = null;
        this.accountStatus = null;
        this.showInfo(this.$t('messages.success'), this.$t('myTischtennisAccount.accountUnlinked'), '', 'success');
      } catch (error) {
        console.error('Fehler beim Löschen des Accounts:', error);
        this.showInfo(this.$t('messages.error'), this.$t('myTischtennisAccount.errorUnlinking'), error.message, 'error');
      }
    },
    
    formatDate(dateString) {
      if (!dateString) return '-';
      const date = new Date(dateString);
      return date.toLocaleString('de-DE', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    },
    
    formatDateRelative(dateString) {
      if (!dateString) return this.$t('myTischtennisAccount.never');
      
      const date = new Date(dateString);
      const now = new Date();
      const diffMs = now - date;
      const diffMins = Math.floor(diffMs / 60000);
      const diffHours = Math.floor(diffMs / 3600000);
      const diffDays = Math.floor(diffMs / 86400000);
      
      if (diffMins < 1) return this.$t('myTischtennisAccount.justNow');
      if (diffMins < 60) return this.$t('myTischtennisAccount.minutesAgo', { count: diffMins });
      if (diffHours < 24) return this.$t('myTischtennisAccount.hoursAgo', { count: diffHours });
      if (diffDays === 1) return this.$t('myTischtennisAccount.yesterday');
      if (diffDays < 7) return this.$t('myTischtennisAccount.daysAgo', { count: diffDays });
      
      return date.toLocaleDateString('de-DE', {
        day: '2-digit',
        month: '2-digit',
        year: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      });
    }
  }
};
</script>

<style scoped>
.page-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 2rem;
}

h1 {
  color: var(--text-color, #333);
  margin-bottom: 2rem;
}

.account-container {
  display: flex;
  flex-direction: column;
  gap: 2rem;
}

.loading {
  text-align: center;
  padding: 2rem;
  color: #666;
}

.account-info, .no-account {
  background: white;
  border-radius: 8px;
  padding: 2rem;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.info-section h2 {
  margin-top: 0;
  margin-bottom: 1.5rem;
  color: var(--primary-color, #007bff);
}

.info-row {
  display: flex;
  justify-content: space-between;
  padding: 0.75rem 0;
  border-bottom: 1px solid #eee;
}

.info-row:last-of-type {
  border-bottom: none;
}

.info-row label {
  font-weight: 600;
  color: #555;
}

.info-row span {
  color: #333;
}

.button-group {
  display: flex;
  gap: 1rem;
  margin-top: 2rem;
  flex-wrap: wrap;
}

.no-account {
  text-align: center;
}

.no-account p {
  margin-bottom: 1.5rem;
  color: #666;
}

.info-box {
  background: #f8f9fa;
  border-left: 4px solid var(--primary-color, #007bff);
  padding: 1.5rem;
  border-radius: 4px;
}

.info-box h3 {
  margin-top: 0;
  color: var(--primary-color, #007bff);
}

.info-box ul {
  margin: 1rem 0;
  padding-left: 1.5rem;
}

.info-box li {
  margin: 0.5rem 0;
}

.btn-primary, .btn-secondary, .btn-danger {
  padding: 0.75rem 1.5rem;
  border: 1px solid transparent;
  border-radius: 10px;
  font-size: 1rem;
  cursor: pointer;
  font-weight: 600;
  transition: background-color 0.2s ease, border-color 0.2s ease, transform 0.2s ease;
}

.btn-primary {
  background: linear-gradient(135deg, var(--primary-color), var(--primary-hover));
  color: var(--text-on-primary);
}

.btn-primary:hover {
  transform: translateY(-1px);
}

.btn-secondary {
  background: var(--surface-color);
  border-color: var(--border-color);
  color: var(--text-color);
}

.btn-secondary:hover {
  background: var(--surface-muted);
  border-color: var(--primary-soft);
}

.btn-secondary:disabled {
  cursor: not-allowed;
  opacity: 0.65;
}

.login-feedback {
  margin-top: 0.75rem;
  font-size: 0.95rem;
}

.login-feedback--info {
  color: #0c5460;
}

.login-feedback--success {
  color: #155724;
}

.login-feedback--error {
  color: #721c24;
}

/* Fetch Statistics */
.fetch-stats-section {
  margin-top: 2rem;
}

.loading-stats {
  text-align: center;
  padding: 2rem;
  color: #666;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 1.5rem;
  margin-bottom: 1.5rem;
}

.stat-card {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 1.5rem;
  display: flex;
  align-items: flex-start;
  gap: 1rem;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  font-size: 2.5rem;
  line-height: 1;
}

.stat-content {
  flex: 1;
}

.stat-content h3 {
  margin: 0 0 0.5rem 0;
  font-size: 1rem;
  color: #333;
  font-weight: 600;
}

.stat-date {
  font-weight: 600;
  color: #28a745;
  margin: 0.25rem 0;
}

.stat-detail {
  font-size: 0.9rem;
  color: #666;
  margin: 0.25rem 0;
}

.stat-time {
  font-size: 0.8rem;
  color: #999;
  margin: 0.25rem 0;
}

.stat-never {
  font-style: italic;
  color: #999;
  margin: 0.25rem 0;
}

.refresh-stats-btn {
  width: 100%;
  margin-top: 1rem;
}

.btn-danger {
  background: rgba(200, 74, 56, 0.12);
  color: #8b3327;
  border: 1px solid rgba(200, 74, 56, 0.24);
}

.btn-danger:hover {
  background: rgba(200, 74, 56, 0.18);
}

.btn-info {
  background: rgba(47, 122, 95, 0.12);
  color: var(--primary-strong);
  border: 1px solid rgba(47, 122, 95, 0.24);
}

.btn-info:hover {
  background: rgba(47, 122, 95, 0.18);
}
</style>
