<template>
  <div class="mytt-account-page" :class="{ 'embedded-dialog-view': embedded }">
    <div class="page-container">
      <h1 v-if="!embedded">{{ $t('navigation.clickTtAccount') }}</h1>

      <div class="account-container">
        <div v-if="loading" class="loading">Lade Account…</div>

        <div v-else-if="account" class="account-info">
          <div class="info-section">
            <h2>Verknüpfter Account</h2>

            <div class="info-row">
              <label>Benutzername</label>
              <span>{{ account.username }}</span>
            </div>

            <div class="info-row">
              <label>Passwort gespeichert</label>
              <span>{{ accountStatus && accountStatus.hasPassword ? 'Ja' : 'Nein' }}</span>
            </div>

            <div class="info-row" v-if="account.lastLoginSuccess">
              <label>Letzter erfolgreicher Login</label>
              <span>{{ formatDate(account.lastLoginSuccess) }}</span>
            </div>

            <div class="info-row" v-if="account.lastLoginAttempt">
              <label>Letzter Login-Versuch</label>
              <span>{{ formatDate(account.lastLoginAttempt) }}</span>
            </div>

            <div class="button-group">
              <button class="btn-primary" @click="openEditDialog">Account bearbeiten</button>
              <button type="button" class="btn-secondary" @click="testConnection" :disabled="verifyingLogin">
                {{ verifyingLogin ? 'Login wird durchgeführt…' : 'Login erneut testen' }}
              </button>
              <button class="btn-danger" @click="deleteAccount">Account löschen</button>
            </div>
          </div>
        </div>

        <div v-else class="no-account">
          <p>Es ist noch kein HTTV-/click-TT-Account hinterlegt.</p>
          <button class="btn-primary" @click="openEditDialog">Account verknüpfen</button>
        </div>
      </div>

      <ClickTtAccountDialog
        v-if="showDialog"
        :account="account"
        :login-mode="loginMode"
        @close="closeDialog"
        @saved="onAccountSaved"
        @logged-in="onLoggedIn"
      />

      <InfoDialog
        v-model="infoDialog.isOpen"
        :title="infoDialog.title"
        :message="infoDialog.message"
        :details="infoDialog.details"
        :type="infoDialog.type"
      />

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

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

export default {
  name: 'ClickTtAccount',
  components: { ClickTtAccountDialog, InfoDialog, ConfirmDialog },
  props: {
    embedded: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: true,
      account: null,
      accountStatus: null,
      showDialog: false,
      loginMode: false,
      verifyingLogin: false,
      infoDialog: { isOpen: false, title: '', message: '', details: '', type: 'info' },
      confirmDialog: { isOpen: false, title: '', message: '', details: '', type: 'info', resolveCallback: null }
    };
  },
  mounted() {
    this.loadAccount();
  },
  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;
    },
    formatDate(dateString) {
      return new Date(dateString).toLocaleString('de-DE');
    },
    async loadAccount() {
      try {
        this.loading = true;
        const [accountResponse, statusResponse] = await Promise.all([
          apiClient.get('/clicktt-account/account'),
          apiClient.get('/clicktt-account/status')
        ]);
        this.account = accountResponse.data.account;
        this.accountStatus = statusResponse.data;
      } catch (error) {
        this.account = null;
        this.accountStatus = null;
        await this.showInfo('Fehler', 'HTTV-/click-TT-Account konnte nicht geladen werden', '', '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('Erfolg', 'HTTV-/click-TT-Account gespeichert', '', 'success');
    },
    async onLoggedIn() {
      this.closeDialog();
      await this.loadAccount();
      await this.showInfo('Erfolg', 'Login erfolgreich', '', 'success');
    },
    async testConnection() {
      if (this.verifyingLogin) return;
      this.verifyingLogin = true;
      try {
        await apiClient.post('/clicktt-account/verify', {});
        await this.loadAccount();
        await this.showInfo('Erfolg', 'HTTV-/click-TT-Login erfolgreich', '', 'success');
      } catch (error) {
        const needsPassword = error?.response?.status === 400;
        if (needsPassword) {
          this.showDialog = true;
          this.loginMode = true;
        } else {
          await this.showInfo('Fehler', getSafeErrorMessage(error, 'HTTV-/click-TT-Login fehlgeschlagen'), '', 'error');
        }
      } finally {
        this.verifyingLogin = false;
      }
    },
    async deleteAccount() {
      const confirmed = await this.showConfirm('Account löschen', 'Soll der HTTV-/click-TT-Account wirklich gelöscht werden?', '', 'warning');
      if (!confirmed) return;

      try {
        await apiClient.delete('/clicktt-account/account');
        await this.loadAccount();
        await this.showInfo('Erfolg', 'HTTV-/click-TT-Account gelöscht', '', 'success');
      } catch (error) {
        await this.showInfo('Fehler', getSafeErrorMessage(error, 'Löschen fehlgeschlagen'), '', 'error');
      }
    }
  }
};
</script>

<style scoped>
.page-container { max-width: 900px; margin: 0 auto; padding: 2rem; }
.account-container { background: white; border-radius: 12px; padding: 2rem; box-shadow: 0 2px 12px rgba(0,0,0,0.08); }
.info-row { display: flex; gap: 1rem; margin-bottom: 1rem; }
.info-row label { min-width: 220px; font-weight: 600; }
.button-group { display: flex; gap: 1rem; margin-top: 1.5rem; }
.btn-primary, .btn-secondary, .btn-danger {
  padding: 0.75rem 1rem;
  border: 1px solid transparent;
  border-radius: 10px;
  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-danger {
  background: rgba(200, 74, 56, 0.12);
  border-color: rgba(200, 74, 56, 0.24);
  color: #8b3327;
}
.btn-danger:hover {
  background: rgba(200, 74, 56, 0.18);
}
.embedded-dialog-view .page-container { max-width: none; padding: 0; }
</style>
