<template>
  <div class="logs-view">
    <div class="header">
      <h1>{{ t('logs.title') }}</h1>
      <p class="subtitle">{{ t('logs.subtitle') }}</p>
    </div>

    <div class="filters-section">
      <div class="filter-controls">
        <div class="filter-group">
          <label>{{ t('logs.backend') }}:</label>
          <select v-model="filters.backend" class="filter-select">
            <option value="">{{ t('logs.all') }}</option>
            <option value="mytischtennis">{{ t('logs.mytischtennis') }}</option>
            <option value="own">{{ t('logs.ownBackend') }}</option>
          </select>
        </div>
        
        <div class="filter-group">
          <label>{{ t('logs.logType') }}:</label>
          <select v-model="filters.logType" class="filter-select">
            <option value="">{{ t('logs.all') }}</option>
            <option value="api_request">{{ t('logs.apiRequests') }}</option>
            <option value="scheduler">{{ t('logs.scheduler') }}</option>
            <option value="cron_job">{{ t('logs.cronJobs') }}</option>
            <option value="manual">{{ t('logs.manual') }}</option>
          </select>
        </div>
        
        <div class="filter-group">
          <label>{{ t('logs.httpMethod') }}:</label>
          <select v-model="filters.method" class="filter-select">
            <option value="">{{ t('logs.all') }}</option>
            <option value="GET">GET</option>
            <option value="POST">POST</option>
            <option value="PUT">PUT</option>
            <option value="DELETE">DELETE</option>
            <option value="PATCH">PATCH</option>
          </select>
        </div>
        
        <div class="filter-group">
          <label>{{ t('logs.status') }}:</label>
          <select v-model="filters.statusCode" class="filter-select">
            <option value="">{{ t('logs.all') }}</option>
            <option value="200">200 - OK</option>
            <option value="400">400 - Bad Request</option>
            <option value="401">401 - Unauthorized</option>
            <option value="403">403 - Forbidden</option>
            <option value="404">404 - Not Found</option>
            <option value="500">500 - Server Error</option>
          </select>
        </div>
        
        <div class="filter-group">
          <label>{{ t('logs.path') }}:</label>
          <input 
            type="text" 
            v-model="filters.path" 
            :placeholder="t('logs.pathPlaceholder')"
            class="filter-input"
          />
        </div>
        
        <div class="filter-group">
          <label>{{ t('logs.from') }}:</label>
          <input type="date" v-model="filters.startDate" class="filter-input" />
        </div>
        
        <div class="filter-group">
          <label>{{ t('logs.to') }}:</label>
          <input type="date" v-model="filters.endDate" class="filter-input" />
        </div>
        
        <button @click="applyFilters" class="btn-primary">{{ t('logs.applyFilters') }}</button>
        <button @click="clearFilters" class="btn-secondary">{{ t('logs.clearFilters') }}</button>
      </div>
    </div>

    <!-- Status-Banner -->
    <div v-if="lastLoadTime" class="status-banner" :class="statusBannerClass">
      <div class="status-content">
        <span class="status-icon">{{ statusIcon }}</span>
        <span class="status-text">
          <template v-if="!loading && !error">
            <strong>{{ t('logs.successfullyLoaded') }}</strong> – {{ total }} {{ t('logs.recordsFound') }}, {{ logs.length }} {{ t('logs.displayed') }}
          </template>
          <template v-else-if="loading">
            {{ t('logs.loadingLogs') }}
          </template>
          <template v-else-if="error">
            <strong>{{ t('logs.error') }}:</strong> {{ error }}
          </template>
        </span>
        <span class="status-time">{{ formatLastLoadTime(lastLoadTime) }}</span>
      </div>
    </div>

    <div v-if="loading && !lastLoadTime" class="loading">{{ t('logs.loadingLogs') }}</div>
    <div v-else-if="error && !lastLoadTime" class="error">{{ error }}</div>
    <div v-else class="logs-content">
      <div class="logs-stats">
        <div class="stat-item">
          <span class="stat-label">{{ t('logs.total') }}:</span>
          <span class="stat-value">{{ total }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">{{ t('logs.displayedLabel') }}:</span>
          <span class="stat-value">{{ logs.length }}</span>
        </div>
      </div>

      <div class="logs-table-container">
        <table class="logs-table">
          <thead>
            <tr>
              <th>{{ t('logs.time') }}</th>
              <th>{{ t('logs.type') }}</th>
              <th>{{ t('logs.method') }}</th>
              <th>{{ t('logs.path') }}</th>
              <th>{{ t('logs.status') }}</th>
              <th>{{ t('logs.executionTime') }}</th>
              <th>{{ t('logs.errorLabel') }}</th>
              <th>{{ t('logs.actions') }}</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="log in logs" :key="log.id" :class="getLogRowClass(log)">
              <td>{{ formatDate(log.createdAt) }}</td>
              <td>
                <span class="log-type-badge" :class="`log-type-${log.logType}`">
                  {{ getLogTypeLabel(log.logType) }}
                </span>
              </td>
              <td>
                <span v-if="log.method !== 'SCHEDULER'" class="method-badge" :class="`method-${log.method}`">
                  {{ log.method }}
                </span>
                <span v-else class="scheduler-badge">⏰</span>
              </td>
              <td class="path-cell">{{ log.path }}</td>
              <td>
                <span class="status-badge" :class="getStatusClass(log.statusCode)">
                  {{ log.statusCode || '-' }}
                </span>
              </td>
              <td>{{ formatExecutionTime(log.executionTime) }}</td>
              <td>
                <span v-if="log.errorMessage" class="error-indicator" :title="log.errorMessage">
                  ⚠️ {{ truncate(log.errorMessage, 50) }}
                </span>
                <span v-else>-</span>
              </td>
              <td>
                <button @click="viewLogDetails(log)" class="btn-view">{{ t('logs.details') }}</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <div class="pagination">
        <button 
          @click="previousPage" 
          :disabled="offset === 0"
          class="btn-pagination"
        >
          ← {{ t('logs.previous') }}
        </button>
        <span class="page-info">
          {{ t('logs.page') }} {{ currentPage }} {{ t('logs.of') }} {{ totalPages }}
        </span>
        <button 
          @click="nextPage" 
          :disabled="offset + logs.length >= total"
          class="btn-pagination"
        >
          {{ t('logs.next') }} →
        </button>
      </div>
    </div>

    <!-- Log Details Dialog -->
    <InfoDialog
      v-model="logDetailsDialog.isOpen"
      :title="logDetailsDialog.title"
      :message="logDetailsDialog.message"
      :details="logDetailsDialog.details"
      :type="logDetailsDialog.type"
    />
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import i18n from '../i18n';
import apiClient from '../apiClient.js';
import InfoDialog from '../components/InfoDialog.vue';

export default {
  name: 'LogsView',
  components: {
    InfoDialog
  },
  setup() {
    const t = (key, params) => i18n.global.t(key, params);
    const logs = ref([]);
    const total = ref(0);
    const loading = ref(false);
    const error = ref(null);
    const limit = ref(50);
    const offset = ref(0);
    const lastLoadTime = ref(null);
    
    const filters = ref({
      backend: '',
      logType: '',
      method: '',
      statusCode: '',
      path: '',
      startDate: '',
      endDate: ''
    });

    const logDetailsDialog = ref({
      isOpen: false,
      title: '',
      message: '',
      details: '',
      type: 'info'
    });

    const currentPage = computed(() => Math.floor(offset.value / limit.value) + 1);
    const totalPages = computed(() => Math.ceil(total.value / limit.value));

    const loadLogs = async () => {
      loading.value = true;
      error.value = null;

      try {
        const params = {
          limit: limit.value,
          offset: offset.value,
          ...filters.value
        };

        // Convert backend filter to path filter
        if (params.backend === 'mytischtennis') {
          params.path = '/mytischtennis';
          delete params.backend;
        } else if (params.backend === 'own') {
          // Exclude myTischtennis paths
          params.path = 'NOT:/mytischtennis';
          delete params.backend;
        } else {
          delete params.backend;
        }

        // Remove empty filters
        Object.keys(params).forEach(key => {
          if (params[key] === '' || params[key] === null) {
            delete params[key];
          }
        });

        const response = await apiClient.get('/logs', { params });
        
        if (response.data.success) {
          logs.value = response.data.data.logs;
          total.value = response.data.data.total;
          error.value = null;
          lastLoadTime.value = new Date();
        } else {
          error.value = t('logs.errorLoading');
          lastLoadTime.value = new Date();
        }
      } catch (err) {
        console.error('Error loading logs:', err);
        error.value = err.response?.data?.error || t('logs.errorLoading');
        lastLoadTime.value = new Date();
      } finally {
        loading.value = false;
      }
    };

    const applyFilters = () => {
      offset.value = 0;
      loadLogs();
    };

    const clearFilters = () => {
      filters.value = {
        backend: '',
        logType: '',
        method: '',
        statusCode: '',
        path: '',
        startDate: '',
        endDate: ''
      };
      offset.value = 0;
      loadLogs();
    };

    const previousPage = () => {
      if (offset.value >= limit.value) {
        offset.value -= limit.value;
        loadLogs();
      }
    };

    const nextPage = () => {
      if (offset.value + logs.value.length < total.value) {
        offset.value += limit.value;
        loadLogs();
      }
    };

    const viewLogDetails = async (log) => {
      try {
        const response = await apiClient.get(`/logs/${log.id}`);
        
        if (response.data.success) {
          const logDetails = response.data.data;
          logDetailsDialog.value = {
            isOpen: true,
            title: `${t('logs.logDetails')} #${log.id}`,
            message: `${logDetails.method} ${logDetails.path}`,
            details: formatLogDetails(logDetails),
            type: logDetails.statusCode >= 400 ? 'error' : 'info'
          };
        }
      } catch (err) {
        console.error('Error loading log details:', err);
      }
    };

    const formatLogDetails = (log) => {
      let details = `${t('logs.logDetailsLabels.time')}: ${formatDate(log.createdAt)}\n`;
      details += `${t('logs.logDetailsLabels.type')}: ${getLogTypeLabel(log.logType)}\n`;
      details += `${t('logs.logDetailsLabels.method')}: ${log.method}\n`;
      details += `${t('logs.logDetailsLabels.path')}: ${log.path}\n`;
      
      if (log.statusCode) {
        details += `${t('logs.logDetailsLabels.status')}: ${log.statusCode}\n`;
      }
      
      if (log.executionTime) {
        details += `${t('logs.logDetailsLabels.executionTime')}: ${formatExecutionTime(log.executionTime)}\n`;
      }
      
      if (log.ipAddress) {
        details += `${t('logs.logDetailsLabels.ip')}: ${log.ipAddress}\n`;
      }
      
      if (log.schedulerJobType) {
        details += `${t('logs.logDetailsLabels.schedulerJob')}: ${log.schedulerJobType}\n`;
      }
      
      if (log.errorMessage) {
        details += `\n${t('logs.logDetailsLabels.error')}:\n${log.errorMessage}\n`;
      }
      
      if (log.requestBody) {
        details += `\n${t('logs.logDetailsLabels.requestBody')}:\n${log.requestBody}\n`;
      }
      
      if (log.responseBody) {
        details += `\n${t('logs.logDetailsLabels.responseBody')}:\n${log.responseBody}\n`;
      }
      
      return details;
    };

    const 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',
        second: '2-digit'
      });
    };

    const formatExecutionTime = (time) => {
      if (!time) return '-';
      if (time < 1000) return `${time}ms`;
      return `${(time / 1000).toFixed(2)}s`;
    };

    const getLogTypeLabel = (type) => {
      const labels = {
        api_request: t('logs.logTypeLabels.api_request'),
        scheduler: t('logs.logTypeLabels.scheduler'),
        cron_job: t('logs.logTypeLabels.cron_job'),
        manual: t('logs.logTypeLabels.manual')
      };
      return labels[type] || type;
    };

    const getLogRowClass = (log) => {
      return {
        'log-error': log.statusCode >= 400,
        'log-success': log.statusCode >= 200 && log.statusCode < 300,
        'log-scheduler': log.logType === 'scheduler'
      };
    };

    const getStatusClass = (statusCode) => {
      if (!statusCode) return 'status-unknown';
      if (statusCode >= 200 && statusCode < 300) return 'status-success';
      if (statusCode >= 400 && statusCode < 500) return 'status-client-error';
      if (statusCode >= 500) return 'status-server-error';
      return 'status-info';
    };

    const truncate = (str, maxLen) => {
      if (!str) return '';
      return str.length > maxLen ? str.substring(0, maxLen) + '...' : str;
    };

    const statusBannerClass = computed(() => {
      if (loading.value) return 'status-loading';
      if (error.value) return 'status-error';
      return 'status-success';
    });

    const statusIcon = computed(() => {
      if (loading.value) return '⏳';
      if (error.value) return '❌';
      return '✅';
    });

    const formatLastLoadTime = (date) => {
      if (!date) return '';
      const now = new Date();
      const diff = Math.floor((now - date) / 1000);
      
      if (diff < 5) return t('logs.justNow');
      if (diff < 60) return t('logs.secondsAgo', { n: diff });
      if (diff < 3600) return t('logs.minutesAgo', { n: Math.floor(diff / 60) });
      return date.toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' });
    };

    onMounted(() => {
      loadLogs();
    });

    return {
      t,
      logs,
      total,
      loading,
      error,
      filters,
      logDetailsDialog,
      currentPage,
      totalPages,
      applyFilters,
      clearFilters,
      previousPage,
      nextPage,
      viewLogDetails,
      formatDate,
      formatExecutionTime,
      getLogTypeLabel,
      getLogRowClass,
      getStatusClass,
      truncate,
      lastLoadTime,
      statusBannerClass,
      statusIcon,
      formatLastLoadTime
    };
  }
};
</script>

<style scoped>
.logs-view {
  padding: 2rem;
  max-width: 1400px;
  margin: 0 auto;
}

.header {
  margin-bottom: 2rem;
}

.header h1 {
  margin: 0 0 0.5rem 0;
  color: var(--text-color, #333);
}

.subtitle {
  color: var(--text-secondary, #666);
  margin: 0;
}

.status-banner {
  padding: 0.75rem 1rem;
  border-radius: 6px;
  margin-bottom: 1.5rem;
  border-left: 4px solid;
}

.status-success {
  background: #dcfce7;
  border-color: #16a34a;
  color: #166534;
}

.status-error {
  background: #fee2e2;
  border-color: #dc2626;
  color: #991b1b;
}

.status-loading {
  background: #fef3c7;
  border-color: #f59e0b;
  color: #92400e;
}

.status-content {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

.status-icon {
  font-size: 1.2em;
}

.status-text {
  flex: 1;
  font-size: 0.95em;
}

.status-time {
  font-size: 0.85em;
  opacity: 0.8;
  white-space: nowrap;
}

.filters-section {
  background: var(--background-light, #f8f9fa);
  padding: 1.5rem;
  border-radius: 8px;
  margin-bottom: 2rem;
}

.filter-controls {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
  align-items: flex-end;
}

.filter-group {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.filter-group label {
  font-size: 0.9em;
  font-weight: 500;
  color: var(--text-color, #333);
}

.filter-select,
.filter-input {
  padding: 0.5rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 0.9em;
  min-width: 120px;
}

.logs-stats {
  display: flex;
  gap: 2rem;
  margin-bottom: 1rem;
}

.stat-item {
  display: flex;
  gap: 0.5rem;
}

.stat-label {
  font-weight: 500;
}

.stat-value {
  font-weight: 600;
  color: var(--primary-strong);
}

.logs-table-container {
  overflow-x: auto;
  background: var(--surface-color);
  border: 1px solid var(--border-color);
  border-radius: 12px;
  box-shadow: 0 10px 24px rgba(15, 23, 42, 0.08);
}

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

.logs-table thead {
  background: var(--surface-muted);
}

.logs-table th {
  padding: 1rem;
  text-align: left;
  font-weight: 600;
  border-bottom: 1px solid var(--border-color);
}

.logs-table td {
  padding: 0.75rem 1rem;
  border-bottom: 1px solid var(--border-color);
}

.logs-table tbody tr:hover {
  background: var(--surface-muted);
}

.log-error {
  background: #fff5f5;
}

.log-success {
  background: #f0fdf4;
}

.log-scheduler {
  background: #fefce8;
}

/* Erfolgreiche Scheduler-Läufe (Status 200) sollen grün sein, nicht gelb */
.log-scheduler.log-success {
  background: #f0fdf4;
}

.log-type-badge {
  display: inline-flex;
  align-items: center;
  padding: 0.25rem 0.55rem;
  border-radius: 999px;
  font-size: 0.8em;
  font-weight: 600;
  border: 1px solid transparent;
}

.log-type-api_request {
  background: rgba(47, 122, 95, 0.1);
  color: var(--primary-strong);
  border-color: rgba(47, 122, 95, 0.18);
}

.log-type-scheduler {
  background: rgba(181, 110, 65, 0.14);
  color: #8a4f28;
  border-color: rgba(181, 110, 65, 0.24);
}

.log-type-cron_job {
  background: rgba(87, 92, 144, 0.12);
  color: #454b79;
  border-color: rgba(87, 92, 144, 0.22);
}

.method-badge {
  display: inline-flex;
  align-items: center;
  padding: 0.25rem 0.55rem;
  border-radius: 999px;
  font-size: 0.8em;
  font-weight: 600;
  font-family: monospace;
  border: 1px solid transparent;
}

.method-GET {
  background: rgba(67, 97, 168, 0.12);
  color: #28457e;
  border-color: rgba(67, 97, 168, 0.24);
}

.method-POST {
  background: rgba(47, 122, 95, 0.12);
  color: #1f5f49;
  border-color: rgba(47, 122, 95, 0.24);
}

.method-PUT {
  background: rgba(181, 110, 65, 0.14);
  color: #8a4f28;
  border-color: rgba(181, 110, 65, 0.24);
}

.method-DELETE {
  background: rgba(200, 74, 56, 0.12);
  color: #8b3327;
  border-color: rgba(200, 74, 56, 0.24);
}

.status-badge {
  display: inline-flex;
  align-items: center;
  padding: 0.25rem 0.55rem;
  border-radius: 999px;
  font-size: 0.8em;
  font-weight: 600;
  border: 1px solid transparent;
}

.status-success {
  background: rgba(47, 122, 95, 0.12);
  color: #1f5f49;
  border-color: rgba(47, 122, 95, 0.24);
}

.status-client-error {
  background: rgba(181, 110, 65, 0.14);
  color: #8a4f28;
  border-color: rgba(181, 110, 65, 0.24);
}

.status-server-error {
  background: rgba(200, 74, 56, 0.12);
  color: #8b3327;
  border-color: rgba(200, 74, 56, 0.24);
}

.path-cell {
  font-family: monospace;
  font-size: 0.9em;
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.error-indicator {
  color: #dc2626;
  font-size: 0.9em;
}

.btn-view {
  padding: 0.25rem 0.75rem;
  background: linear-gradient(135deg, var(--primary-color), var(--primary-hover));
  color: var(--text-on-primary);
  border: 1px solid transparent;
  border-radius: 8px;
  cursor: pointer;
  font-size: 0.85em;
  font-weight: 600;
}

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

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 1rem;
  margin-top: 2rem;
}

.btn-pagination {
  padding: 0.5rem 1rem;
  background: white;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
}

.btn-pagination:hover:not(:disabled) {
  background: var(--background-light, #f8f9fa);
}

.btn-pagination:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-info {
  font-weight: 500;
}
</style>
