<template>
  <BaseDialog
    :model-value="modelValue"
    @update:model-value="$emit('update:modelValue', $event)"
    :title="$t('memberTransferDialog.title')"
    size="large"
    :close-on-overlay="false"
    @close="handleClose"
  >
    <div v-if="loadingConfig" class="loading-config">
      {{ $t('memberTransferDialog.loadingConfig') }}
    </div>
    
    <div v-else class="transfer-form">
      <div v-if="!hasConfig" class="config-missing">
        <p><strong>{{ $t('memberTransferDialog.noConfigFound') }}</strong></p>
        <p>{{ $t('memberTransferDialog.noConfigMessage') }}</p>
        <router-link to="/member-transfer-settings" class="btn-link" @click="handleClose">
          {{ $t('memberTransferDialog.goToSettings') }}
        </router-link>
      </div>

      <div v-else>
        <div class="config-summary">
          <h4>{{ $t('memberTransferDialog.transferConfiguration') }}</h4>
          <p class="active-members-hint">Es werden nur aktive Mitglieder übertragen.</p>
          <div class="summary-info">
            <div class="summary-row">
              <span class="summary-label">{{ $t('memberTransferDialog.server') }}:</span>
              <span class="summary-value">{{ config.server }}</span>
            </div>
            <div class="summary-row">
              <span class="summary-label">{{ $t('memberTransferDialog.endpoint') }}:</span>
              <span class="summary-value">{{ config.transferEndpoint }}</span>
            </div>
            <div class="summary-row">
              <span class="summary-label">{{ $t('memberTransferDialog.method') }}:</span>
              <span class="summary-value">{{ config.transferMethod }}</span>
            </div>
            <div class="summary-row">
              <span class="summary-label">{{ $t('memberTransferDialog.format') }}:</span>
              <span class="summary-value">{{ config.transferFormat }}</span>
            </div>
            <div class="summary-row">
              <span class="summary-label">{{ $t('memberTransferDialog.mode') }}:</span>
              <span class="summary-value">{{ config.useBulkMode ? $t('memberTransferDialog.bulkImport') : $t('memberTransferDialog.single') }}</span>
            </div>
          </div>
          <router-link to="/member-transfer-settings" class="btn-link-small" @click="handleClose">
            {{ $t('memberTransferDialog.editConfig') }}
          </router-link>
        </div>

        <div v-if="config.loginEndpoint" class="form-section">
          <h4>{{ $t('memberTransferDialog.loginDataOverride') }}</h4>
          <p class="section-hint">{{ $t('memberTransferDialog.loginDataHint') }}</p>
          
          <div class="form-group">
            <label>{{ $t('memberTransferDialog.loginData') }}:</label>
            <div class="credentials-group">
              <div class="credential-row">
                <!-- Dummy-Felder, um Browser-Autofill zu verhindern (ausgeblendet) -->
                <input type="text" style="position: absolute; left: -9999px; opacity: 0;" tabindex="-1" autocomplete="off" />
                <input type="password" style="position: absolute; left: -9999px; opacity: 0;" tabindex="-1" autocomplete="off" />
                
                <input
                  type="text"
                  v-model="loginCredentials.username"
                  :placeholder="$t('memberTransferDialog.usernameEmail')"
                  class="form-input"
                  autocomplete="off"
                  name="transfer-username"
                  id="transfer-username"
                />
                <input
                  type="password"
                  v-model="loginCredentials.password"
                  :placeholder="$t('memberTransferDialog.passwordPlaceholder')"
                  class="form-input"
                  autocomplete="new-password"
                  name="transfer-password"
                  id="transfer-password"
                />
              </div>
              <div class="credential-row">
                <input
                  type="text"
                  v-model="loginCredentials.additionalField1"
                  :placeholder="additionalField1Placeholder"
                  class="form-input"
                  autocomplete="off"
                  name="transfer-additional1"
                />
                <input
                  type="text"
                  v-model="loginCredentials.additionalField2"
                  :placeholder="additionalField2Placeholder"
                  class="form-input"
                  autocomplete="off"
                  name="transfer-additional2"
                />
              </div>
            </div>
            <span class="hint">{{ $t('memberTransferDialog.loginDataOverrideHint') }}</span>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <button class="btn-secondary" @click="handleClose">{{ $t('memberTransferDialog.cancel') }}</button>
      <button 
        class="btn-primary" 
        @click="handleTransfer" 
        :disabled="!isValid || isTransferring"
      >
        {{ isTransferring ? $t('memberTransferDialog.transferring') : $t('memberTransferDialog.transfer') }}
      </button>
    </template>
  </BaseDialog>
</template>

<script>
import BaseDialog from './BaseDialog.vue';
import apiClient from '../apiClient.js';
import { getSafeErrorMessage, getSafeMessage, sanitizeText } from '../utils/errorMessages.js';
import { mapGetters } from 'vuex';

export default {
  name: 'MemberTransferDialog',
  components: {
    BaseDialog
  },
  props: {
    modelValue: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    ...mapGetters(['currentClub']),
    
    isValid() {
      return this.hasConfig && !!(this.config.server && this.config.transferEndpoint && this.config.transferTemplate);
    },
    
    hasConfig() {
      return !!(this.config.server && this.config.transferEndpoint && this.config.transferTemplate);
    },
    
    additionalField1Placeholder() {
      if (this.config.loginFormat === 'form-data' || this.config.loginFormat === 'x-www-form-urlencoded') {
        return this.$t('memberTransferDialog.additionalFieldPlaceholderForm');
      }
      return this.$t('memberTransferDialog.additionalFieldPlaceholder');
    },
    
    additionalField2Placeholder() {
      if (this.config.loginFormat === 'form-data' || this.config.loginFormat === 'x-www-form-urlencoded') {
        return this.$t('memberTransferDialog.additionalFieldPlaceholderForm');
      }
      return this.$t('memberTransferDialog.additionalFieldPlaceholder');
    }
  },
  data() {
    return {
      config: {
        server: '',
        loginEndpoint: '',
        loginFormat: 'json',
        transferEndpoint: '',
        transferMethod: 'POST',
        transferFormat: 'json',
        transferTemplate: '',
        useBulkMode: false,
        bulkWrapperTemplate: ''
      },
      loginCredentials: {
        username: '',
        password: '',
        additionalField1: '',
        additionalField2: ''
      },
      isTransferring: false,
      loadingConfig: false
    };
  },
  watch: {
    modelValue(newVal) {
      if (newVal) {
        // WICHTIG: Felder sofort leeren, bevor Konfiguration geladen wird
        // Verwende $nextTick, um sicherzustellen, dass Vue die Änderungen verarbeitet
        this.$nextTick(() => {
          this.loginCredentials = {
            username: '',
            password: '',
            additionalField1: '',
            additionalField2: ''
          };
        });
        this.loadSavedConfig();
      } else {
        // Beim Schließen auch leeren
        this.resetForm();
      }
    }
  },
  methods: {
    async loadSavedConfig() {
      if (!this.currentClub) {
        // Login-Credentials leeren, auch wenn kein Club vorhanden
        this.loginCredentials = {
          username: '',
          password: '',
          additionalField1: '',
          additionalField2: ''
        };
        return;
      }

      // WICHTIG: Login-Credentials sofort leeren, damit sie nicht vorausgefüllt werden
      // Verwende $nextTick, um sicherzustellen, dass Vue die Änderungen verarbeitet
      this.$nextTick(() => {
        this.loginCredentials = {
          username: '',
          password: '',
          additionalField1: '',
          additionalField2: ''
        };
      });

      this.loadingConfig = true;
      try {
        const response = await apiClient.get(`/member-transfer-config/${this.currentClub}`);
        
        if (response.data.success && response.data.config) {
          const savedConfig = response.data.config;
          
          // Konfiguration aus gespeicherten Daten laden
          this.config.server = savedConfig.server || '';
          this.config.loginEndpoint = savedConfig.loginEndpoint || '';
          this.config.loginFormat = savedConfig.loginFormat || 'json';
          this.config.transferEndpoint = savedConfig.transferEndpoint || '';
          this.config.transferMethod = savedConfig.transferMethod || 'POST';
          this.config.transferFormat = savedConfig.transferFormat || 'json';
          this.config.transferTemplate = savedConfig.transferTemplate || '';
          this.config.useBulkMode = savedConfig.useBulkMode || false;
          this.config.bulkWrapperTemplate = savedConfig.bulkWrapperTemplate || '';
          
          // Login-Credentials bleiben leer (werden nur verwendet, wenn im Dialog eingegeben)
          // Gespeicherte Credentials werden vom Backend verwendet, wenn keine eingegeben werden
        }
      } catch (error) {
        // Keine Konfiguration vorhanden - das ist OK, Dialog bleibt leer
        if (error.response?.status !== 404) {
          console.error('Fehler beim Laden der gespeicherten Konfiguration:', error);
        }
      } finally {
        // Sicherstellen, dass Login-Credentials leer sind
        // Verwende $nextTick, um sicherzustellen, dass Vue die Änderungen verarbeitet
        this.$nextTick(() => {
          this.loginCredentials = {
            username: '',
            password: '',
            additionalField1: '',
            additionalField2: ''
          };
        });
        this.loadingConfig = false;
      }
    },
    handleClose() {
      this.$emit('update:modelValue', false);
      this.resetForm();
    },
    
    resetForm() {
      this.config = {
        server: '',
        loginEndpoint: '',
        loginFormat: 'json',
        transferEndpoint: '',
        transferMethod: 'POST',
        transferFormat: 'json',
        transferTemplate: '',
        useBulkMode: false,
        bulkWrapperTemplate: ''
      };
      this.loginCredentials = {
        username: '',
        password: '',
        additionalField1: '',
        additionalField2: ''
      };
      this.isTransferring = false;
    },
    
    async handleTransfer() {
      if (!this.isValid) {
        return;
      }

      this.isTransferring = true;

      try {
        // Login-Credentials zusammenstellen
        // WICHTIG: Nur nicht-leere Werte hinzufügen (nach Trimmen)
        // Leere Strings würden die gespeicherten Credentials überschreiben
        const loginCredentials = {};
        const trimmedUsername = this.loginCredentials.username?.trim();
        const trimmedPassword = this.loginCredentials.password?.trim();
        
        if (trimmedUsername) {
          loginCredentials.username = trimmedUsername;
        }
        if (trimmedPassword) {
          loginCredentials.password = trimmedPassword;
        }
        
        // Zusätzliche Felder verarbeiten (nur wenn nicht leer)
        const trimmedAdditional1 = this.loginCredentials.additionalField1?.trim();
        if (trimmedAdditional1) {
          const parts1 = trimmedAdditional1.split(':').map(s => s.trim());
          if (parts1.length === 2 && parts1[0] && parts1[1]) {
            loginCredentials[parts1[0]] = parts1[1];
          } else if (parts1.length === 1 && parts1[0]) {
            // Falls kein Doppelpunkt, verwende den gesamten Wert als Feldname
            loginCredentials[parts1[0]] = parts1[0];
          }
        }
        
        const trimmedAdditional2 = this.loginCredentials.additionalField2?.trim();
        if (trimmedAdditional2) {
          const parts2 = trimmedAdditional2.split(':').map(s => s.trim());
          if (parts2.length === 2 && parts2[0] && parts2[1]) {
            loginCredentials[parts2[0]] = parts2[1];
          } else if (parts2.length === 1 && parts2[0]) {
            loginCredentials[parts2[0]] = parts2[0];
          }
        }

        // Konfiguration zusammenstellen
        const transferConfig = {
          transferEndpoint: this.config.transferEndpoint,
          transferMethod: this.config.transferMethod,
          transferFormat: this.config.transferFormat,
          transferTemplate: this.config.transferTemplate,
          useBulkMode: this.config.useBulkMode,
          bulkWrapperTemplate: this.config.bulkWrapperTemplate || null
        };

        // Login-Konfiguration nur hinzufügen, wenn Endpoint vorhanden
        if (this.config.loginEndpoint) {
          transferConfig.loginEndpoint = this.config.loginEndpoint;
          transferConfig.loginFormat = this.config.loginFormat;
          
          // Nur Login-Credentials hinzufügen, wenn welche eingegeben wurden
          // Wenn keine eingegeben wurden, werden die gespeicherten verwendet (Backend holt diese)
          if (Object.keys(loginCredentials).length > 0) {
            transferConfig.loginCredentials = loginCredentials;
          }
        }

        const response = await apiClient.post(
          `/clubmembers/transfer/${this.currentClub}`,
          transferConfig
        );

        if (response.data.success) {
          const message = getSafeMessage(
            response.data.message,
            this.$t('memberTransferDialog.transferSuccess', { transferred: response.data.transferred, total: response.data.total })
          );
          
          let details = '';
          
          // Zeige ausgeschlossene Mitglieder an
          if (response.data.invalidMembers && response.data.invalidMembers.length > 0) {
            details += this.$t('memberTransferDialog.excludedMembers') + ':\n';
            details += response.data.invalidMembers.map(inv => {
              const name = sanitizeText(`${inv.member.firstName || ''} ${inv.member.lastName || ''}`.trim(), `ID: ${inv.member.id}`);
              const errorText = sanitizeText(inv.errors.join(', '), 'Unbekannter Fehler');
              return `${name}: ${errorText}`;
            }).join('\n');
            details += '\n\n';
          }
          
          // Zeige weitere Fehler an
          if (response.data.errors && response.data.errors.length > 0) {
            details += this.$t('memberTransferDialog.additionalErrors') + ':\n';
            details += response.data.errors.map((e) => {
              const memberName = sanitizeText(e.member, 'Unbekanntes Mitglied');
              const err = sanitizeText(e.error, 'Unbekannter Fehler');
              return `${memberName}: ${err}`;
            }).join('\n');
          }

          this.$emit('success', {
            message: message,
            details: details.trim(),
            results: response.data
          });

          this.handleClose();
        } else {
          // Bei Fehlern auch ausgeschlossene Mitglieder anzeigen
          let errorDetails = getSafeMessage(response.data.error, this.$t('memberTransferDialog.transferFailed'));
          
          if (response.data.invalidMembers && response.data.invalidMembers.length > 0) {
            errorDetails += '\n\n' + this.$t('memberTransferDialog.excludedMembers') + ':\n';
            errorDetails += response.data.invalidMembers.map(inv => {
              const name = sanitizeText(`${inv.member.firstName || ''} ${inv.member.lastName || ''}`.trim(), `ID: ${inv.member.id}`);
              const err = sanitizeText(inv.errors.join(', '), 'Unbekannter Fehler');
              return `${name}: ${err}`;
            }).join('\n');
          }
          
          this.$emit('error', {
            message: getSafeMessage(response.data.message, this.$t('memberTransferDialog.transferFailed')),
            error: errorDetails
          });
          
          this.handleClose();
        }
      } catch (error) {
        console.error('Transfer error:', error);
        const errorMessage = getSafeErrorMessage(error, this.$t('memberTransferDialog.transferError'));
        
        this.$emit('error', {
          message: this.$t('memberTransferDialog.transferError'),
          error: errorMessage
        });
        
        this.handleClose();
      } finally {
        this.isTransferring = false;
      }
    }
  }
};
</script>

<style scoped>
.transfer-form {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.form-section {
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  padding: 1.5rem;
  background-color: #fafafa;
}

.form-section h4 {
  margin: 0 0 1rem 0;
  color: #333;
  font-size: 1.1em;
  border-bottom: 2px solid #007bff;
  padding-bottom: 0.5rem;
}

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

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
  color: #333;
}

.form-group .required {
  color: #dc3545;
}

.form-input,
.form-select,
.form-textarea {
  width: 100%;
  padding: 0.5rem;
  border: 1px solid #ced4da;
  border-radius: 4px;
  font-size: 0.9em;
  font-family: inherit;
}

.form-input[readonly] {
  background-color: #f8f9fa;
  cursor: not-allowed;
  color: #6c757d;
}

.form-textarea {
  font-family: 'Courier New', monospace;
  resize: vertical;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
}

.credentials-group {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.credential-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 0.5rem;
}

.hint {
  display: block;
  margin-top: 0.25rem;
  font-size: 0.85em;
  color: #666;
  font-style: italic;
}

.template-help {
  margin-top: 0.75rem;
  padding: 1rem;
  background-color: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #e9ecef;
  font-size: 0.85em;
}

.template-help strong {
  display: block;
  margin-bottom: 0.5rem;
  color: #333;
}

.template-help ul {
  margin: 0.5rem 0;
  padding-left: 1.5rem;
}

.template-help li {
  margin: 0.25rem 0;
}

.template-help code {
  background-color: #e9ecef;
  padding: 0.2rem 0.4rem;
  border-radius: 3px;
  font-family: 'Courier New', monospace;
  font-size: 0.9em;
}

.template-help pre {
  background-color: #282c34;
  color: #abb2bf;
  padding: 0.75rem;
  border-radius: 4px;
  overflow-x: auto;
  margin-top: 0.5rem;
  font-size: 0.85em;
}

.bulk-hint {
  margin-top: 0.75rem;
  padding: 0.75rem;
  background-color: #e7f3ff;
  border-left: 4px solid #007bff;
  border-radius: 4px;
  color: #004085;
}

.bulk-hint code {
  background-color: #cce5ff;
  padding: 0.2rem 0.4rem;
  border-radius: 3px;
}

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

.config-missing {
  text-align: center;
  padding: 2rem;
  background-color: #fff3cd;
  border: 1px solid #ffc107;
  border-radius: 6px;
  color: #856404;
}

.config-missing p {
  margin: 0.5rem 0;
}

.btn-link {
  display: inline-block;
  margin-top: 1rem;
  padding: 0.75rem 1.5rem;
  background: linear-gradient(135deg, var(--primary-color), var(--primary-hover));
  color: var(--text-on-primary);
  text-decoration: none;
  border-radius: 10px;
  font-weight: 600;
  transition: transform 0.2s ease, opacity 0.2s ease;
}

.btn-link:hover {
  opacity: 0.95;
  transform: translateY(-1px);
}

.config-summary {
  background-color: #f8f9fa;
  border: 1px solid #dee2e6;
  border-radius: 6px;
  padding: 1.5rem;
  margin-bottom: 1.5rem;
}

.config-summary h4 {
  margin: 0 0 1rem 0;
  color: #333;
  font-size: 1.1em;
}

.summary-info {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  margin-bottom: 1rem;
}

.active-members-hint {
  margin: 0 0 1rem 0;
  padding: 0.55rem 0.75rem;
  border-left: 3px solid #2f7a5f;
  background: #eef8f3;
  color: #1f5f49;
  font-size: 0.9rem;
}

.summary-row {
  display: flex;
  gap: 1rem;
}

.summary-label {
  font-weight: 600;
  color: #555;
  min-width: 100px;
}

.summary-value {
  color: #333;
  font-family: 'Courier New', monospace;
  font-size: 0.9em;
}

.btn-link-small {
  display: inline-block;
  color: var(--primary-color);
  text-decoration: none;
  font-size: 0.9em;
  font-weight: 600;
}

.btn-link-small:hover {
  text-decoration: underline;
}

.section-hint {
  margin: 0 0 1rem 0;
  font-size: 0.9em;
  color: #666;
  font-style: italic;
}

.btn-primary {
  background: linear-gradient(135deg, var(--primary-color), var(--primary-hover));
  color: var(--text-on-primary);
  border: 1px solid transparent;
  padding: 0.5rem 1.5rem;
  border-radius: 10px;
  cursor: pointer;
  font-weight: 600;
  transition: transform 0.2s ease, opacity 0.2s ease;
}

.btn-primary:hover:not(:disabled) {
  opacity: 0.95;
  transform: translateY(-1px);
}

.btn-primary:disabled {
  background-color: #6c757d;
  cursor: not-allowed;
  opacity: 0.6;
}

.btn-secondary {
  background: var(--surface-color);
  color: var(--text-color);
  border: 1px solid var(--border-color);
  padding: 0.5rem 1.5rem;
  border-radius: 10px;
  cursor: pointer;
  font-weight: 600;
  transition: background-color 0.2s ease, border-color 0.2s ease;
}

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