<template>
  <div class="modal-overlay" @click.self="$emit('close')">
    <div class="modal">
      <div class="modal-header">
        <h3>{{ loginMode ? $t('myTischtennisDialog.login') : (account ? $t('myTischtennisDialog.editAccount') : $t('myTischtennisDialog.linkAccount')) }}</h3>
      </div>
      
      <div class="modal-body">
        <!-- Im Login-Modus: lokales Formular, Login serverseitig via Playwright-Fallback -->
        <template v-if="loginMode">
          <div class="form-group">
            <label for="mtt-login-email">{{ $t('myTischtennisDialog.email') }}:</label>
            <input
              type="email"
              id="mtt-login-email"
              v-model="formData.email"
              readonly
            />
          </div>

          <div class="form-group">
            <label for="mtt-login-password">{{ $t('myTischtennisDialog.password') }}:</label>
            <input
              type="password"
              id="mtt-login-password"
              v-model="formData.password"
              :placeholder="$t('myTischtennisDialog.passwordPlaceholder')"
              required
            />
          </div>
        </template>
        
        <!-- Im Bearbeiten-Modus: Zeige normales Formular -->
        <template v-else>
          <div class="form-group">
            <label for="mtt-email">{{ $t('myTischtennisDialog.email') }}:</label>
            <input
              type="email"
              id="mtt-email"
              v-model="formData.email"
              :placeholder="$t('myTischtennisDialog.emailPlaceholder')"
              required
            />
          </div>
          
          <div class="form-group">
            <label for="mtt-password">{{ $t('myTischtennisDialog.password') }}:</label>
            <input
              type="password"
              id="mtt-password"
              v-model="formData.password"
              :placeholder="account && account.savePassword ? $t('myTischtennisDialog.passwordPlaceholderKeep') : $t('myTischtennisDialog.passwordPlaceholder')"
            />
          </div>
          
          <div class="form-group checkbox-group">
            <label>
              <input
                type="checkbox"
                v-model="formData.savePassword"
              />
              <span>{{ $t('myTischtennisDialog.savePassword') }}</span>
            </label>
            <p class="hint">
              {{ $t('myTischtennisDialog.savePasswordHint') }}
            </p>
          </div>
          
          <div class="form-group checkbox-group">
            <label>
              <input
                type="checkbox"
                v-model="formData.autoUpdateRatings"
                :disabled="!formData.savePassword"
              />
              <span>{{ $t('myTischtennisDialog.autoUpdateRatings') }}</span>
            </label>
            <p class="hint">
              {{ $t('myTischtennisDialog.autoUpdateRatingsHint') }}
            </p>
            <p v-if="formData.autoUpdateRatings && !formData.savePassword" class="warning">
              {{ $t('myTischtennisDialog.autoUpdateWarning') }}
            </p>
          </div>
          
          <div class="form-group" v-if="formData.password">
            <label for="app-password">{{ $t('myTischtennisDialog.appPassword') }}:</label>
            <input
              type="password"
              id="app-password"
              v-model="formData.userPassword"
              :placeholder="$t('myTischtennisDialog.appPasswordPlaceholder')"
              required
            />
            <p class="hint">
              {{ $t('myTischtennisDialog.appPasswordHint') }}
            </p>
          </div>
        </template>
        
        <div v-if="error" class="error-message">
          {{ error }}
        </div>
      </div>
      
      <div class="modal-footer">
        <button class="btn-secondary" @click="$emit('close')" :disabled="saving">
          {{ $t('myTischtennisDialog.cancel') }}
        </button>
        <button v-if="loginMode" class="btn-primary" @click="performLogin" :disabled="!canLogin || saving">
          {{ saving ? $t('myTischtennisDialog.saving') : $t('myTischtennisDialog.login') }}
        </button>
        <button v-if="!loginMode" class="btn-primary" @click="saveAccount()" :disabled="!canSave || saving">
          {{ saving ? $t('myTischtennisDialog.saving') : $t('myTischtennisDialog.save') }}
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import apiClient from '../apiClient.js';

export default {
  name: 'MyTischtennisDialog',
  props: {
    account: {
      type: Object,
      default: null
    },
    loginMode: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        email: this.account?.email || '',
        password: '',
        savePassword: this.account?.savePassword || false,
        autoUpdateRatings: this.account?.autoUpdateRatings || false,
        userPassword: ''
      },
      saving: false,
      error: null
    };
  },
  computed: {
    canLogin() {
      return !!this.formData.password;
    },
    canSave() {
      // E-Mail ist erforderlich
      if (!this.formData.email.trim()) {
        return false;
      }
      
      // Wenn ein Passwort eingegeben wurde, muss auch das App-Passwort eingegeben werden
      if (this.formData.password && !this.formData.userPassword) {
        return false;
      }
      
      return true;
    }
  },
  methods: {
    async performLogin() {
      if (!this.canLogin) return;
      this.error = null;
      this.saving = true;
      try {
        const response = await apiClient.post('/mytischtennis/verify', {
          password: this.formData.password
        });
        if (response.status >= 400 || response?.data?.success === false) {
          const requestError = new Error('myTischtennis verify failed');
          requestError.response = response;
          throw requestError;
        }
        this.$emit('logged-in');
      } catch (error) {
        console.error('Fehler beim Login:', error);
        this.error = error.response?.data?.error
          || error.response?.data?.message
          || this.$t('myTischtennisDialog.errorSaving');
      } finally {
        this.saving = false;
      }
    },
    
    async saveAccount() {
      if (!this.canSave) return;
      
      this.error = null;
      this.saving = true;
      
      try {
        const payload = {
          email: this.formData.email,
          savePassword: this.formData.savePassword,
          autoUpdateRatings: this.formData.savePassword ? this.formData.autoUpdateRatings : false
        };
        
        // Nur password und userPassword hinzufügen, wenn ein Passwort eingegeben wurde
        if (this.formData.password) {
          payload.password = this.formData.password;
          payload.userPassword = this.formData.userPassword;
        }
        
        const response = await apiClient.post('/mytischtennis/account', payload);
        if (response.status >= 400 || response?.data?.success === false) {
          const requestError = new Error('myTischtennis account save failed');
          requestError.response = response;
          throw requestError;
        }
        this.$emit('saved');
      } catch (error) {
        console.error('Fehler beim Speichern:', error);
        this.error = error.response?.data?.error
          || error.response?.data?.message
          || this.$t('myTischtennisDialog.errorSaving');
      } finally {
        this.saving = false;
      }
    }
  }
};
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(15, 23, 42, 0.38);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal {
  background: var(--surface-color);
  border: 1px solid var(--border-color);
  border-radius: 14px;
  box-shadow: 0 18px 48px rgba(15, 23, 42, 0.18);
  max-width: 600px;
  width: 90%;
  max-height: 90vh;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

.modal-header {
  padding: 1.5rem;
  border-bottom: 1px solid var(--border-color);
  background: linear-gradient(180deg, rgba(47, 122, 95, 0.12), rgba(47, 122, 95, 0.04));
}

.modal-header h3 {
  margin: 0;
  color: var(--text-color);
}

.modal-body {
  padding: 1.5rem;
  flex: 1;
}

.modal-footer {
  padding: 1rem 1.5rem;
  border-top: 1px solid var(--border-color);
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  background: var(--surface-muted);
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 600;
  color: var(--text-color);
}

.form-group input[type="text"],
.form-group input[type="email"],
.form-group input[type="password"] {
  width: 100%;
  padding: 0.75rem 0.875rem;
  border: 1px solid var(--border-color);
  border-radius: 10px;
  font-size: 1rem;
  box-sizing: border-box;
  background: var(--surface-muted);
  color: var(--text-color);
}

.form-group input[type="text"]:focus,
.form-group input[type="email"]:focus,
.form-group input[type="password"]:focus {
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 0 3px rgba(47, 122, 95, 0.16);
}

.checkbox-group label {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-weight: normal;
  cursor: pointer;
}

.checkbox-group input[type="checkbox"] {
  width: auto;
  margin: 0;
  cursor: pointer;
}

.hint {
  margin-top: 0.5rem;
  font-size: 0.875rem;
  color: var(--text-muted);
}

.warning {
  margin-top: 0.5rem;
  font-size: 0.875rem;
  color: var(--danger-color);
  font-weight: 600;
}

.error-message {
  padding: 0.75rem;
  background: rgba(200, 74, 56, 0.12);
  border: 1px solid rgba(200, 74, 56, 0.24);
  border-radius: 10px;
  color: #7a2e21;
  margin-top: 1rem;
}

.btn-primary, .btn-secondary {
  padding: 0.75rem 1.5rem;
  border: 1px solid transparent;
  border-radius: 10px;
  font-size: 0.95rem;
  font-weight: 600;
  cursor: pointer;
  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:not(:disabled) {
  transform: translateY(-1px);
}

.btn-primary:disabled {
  cursor: not-allowed;
  opacity: 0.55;
}

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

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

.btn-secondary:disabled {
  cursor: not-allowed;
  opacity: 0.6;
}
</style>
