---
// src/pages/contribute/knowledgebase.astro
import BaseLayout from '../../layouts/BaseLayout.astro';
import { withAuth } from '../../utils/auth.js';
import { getToolsData } from '../../utils/dataService.js';

export const prerender = false;

const authResult = await withAuth(Astro, 'contributions');
if (authResult instanceof Response) {
  return authResult;
}

const { authenticated, userEmail, userId } = authResult;

const data = await getToolsData();
const sortedTools = data.tools.sort((a: any, b: any) => a.name.localeCompare(b.name));
---

<BaseLayout title="Contribute Knowledge Base Article">
  <div class="container" style="max-width: 900px; margin: 0 auto; padding: 2rem 1rem;">
    
    <div class="header-center header-primary rounded-xl">
      <h1 style="margin-bottom: 1rem; font-size: 2rem;">Knowledgebase-Artikel</h1>
      <p style="margin: 0.5rem 0; opacity: 0.9;">Danke für deinen Beitrag!</p>
      {userEmail && <p style="margin: 0.5rem 0; opacity: 0.8;"><strong>Eingeloggt als:</strong> {userEmail}</p>}
    </div>

    <div class="card">
      <form id="kb-form" novalidate>
        
        <div class="form-section">
          <h3 class="section-title">Grundinformationen</h3>
          
          <div class="form-grid-2">
            <div class="form-group">
              <label for="tool-name" class="form-label">Zusammenhang zu Tool / Methode / Konzept (Optional)</label>
              <select id="tool-name" name="toolName" class="form-input">
                <option value="">Auswählen...</option>
                {sortedTools.map(tool => (
                  <option value={tool.name}>{tool.name} ({tool.type})</option>
                ))}
              </select>
            </div>
            
            <div class="form-group">
              <label for="difficulty" class="form-label">Schwierigkeitsniveau (Optional)</label>
              <select id="difficulty" name="difficulty" class="form-input">
                <option value="">Niveau wählen...</option>
                <option value="novice">Novice</option>
                <option value="beginner">Beginner</option>
                <option value="intermediate">Intermediate</option>
                <option value="advanced">Advanced</option>
                <option value="expert">Expert</option>
              </select>
            </div>
          </div>
          <br>

          <div class="form-group">
            <label for="title" class="form-label">Titel des Artikels (Optional)</label>
            <input 
              type="text" 
              id="title" 
              name="title"  
              maxlength="100"
              placeholder="Klarer, deskriptiver Titel"
              class="form-input"
            />
          </div>

          <div class="form-group">
            <label for="description" class="form-label">Kurzbeschreibung (Optional)</label>
            <textarea 
              id="description" 
              name="description"  
              maxlength="300"
              rows="3"
              placeholder="Kurze Zusammenfassung, worum es in dem Artikel geht"
              class="form-input"
            ></textarea>
          </div>
        </div>

        <div class="form-section">
          <h3 class="section-title">Inhalt</h3>
          
          <div class="form-group">
            <label for="content" class="form-label">Inhalt (Optional)</label>
            <textarea 
              id="content" 
              name="content" 
              rows="8"
              placeholder="Schreibt hier so viel Text, wie ihr wollt. Die Formatierung wird später redaktionell angepasst."
              class="form-input"
            ></textarea>
          </div>

          <div class="form-group">
            <label for="external-link" class="form-label">Link (z.B. Primärquelle) (Optional)</label>
            <input 
              type="url" 
              id="external-link" 
              name="externalLink" 
              placeholder="https://example.com/documentation"
              class="form-input"
            />
          </div>
        </div>

        <div class="form-section">
          <h3 class="section-title">Dateien hochladen</h3>
          
          <div class="form-group">
            <label class="form-label">Dokumente, Bilder, Videos (Optional)</label>
            <div class="upload-area" id="upload-area">
              <input 
                type="file" 
                id="file-input" 
                multiple 
                accept=".pdf,.doc,.docx,.txt,.md,.markdown,.csv,.json,.xml,.html,.rtf,.yaml,.yml,.zip,.tar,.gz,.rar,.7z,.png,.jpg,.jpeg,.gif,.webp,.svg,.mp4,.webm,.mov,.avi" 
                class="hidden"
              >              <div class="upload-placeholder">
                <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1">
                  <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
                  <polyline points="7 10 12 15 17 10"/>
                  <line x1="12" y1="15" x2="12" y2="3"/>
                </svg>
                <p>Klicken, um Dateien auszuwählen oder Drag&Drop</p>
                <small>Die Dateien landen in der CC24-Cloud. Keine Malware.</small>
              </div>
            </div>
            <div id="file-list" class="file-list hidden">
              <h5>Ausgewählte Dateien</h5>
              <div id="files-container"></div>
            </div>
          </div>
        </div>

        <div class="form-section">
          <h3 class="section-title">Zusatzinformation</h3>
          
          <div class="form-grid-2">
            <div class="form-group">
              <label for="categories" class="form-label">Kategorien (Optional)</label>
              <input 
                type="text" 
                id="categories" 
                name="categories" 
                placeholder="setup, configuration, troubleshooting"
                class="form-input"
              />
              <small class="form-help">Komma-getrennte Kategorien</small>
            </div>
            
            <div class="form-group">
              <label for="tags" class="form-label">Tags (Optional)</label>
              <input 
                type="text" 
                id="tags" 
                name="tags" 
                placeholder="installation, docker, linux, windows"
                class="form-input"
              />
              <small class="form-help">Komma-getrennte Tags</small>
            </div>
          </div>

          <div class="form-group">
            <label for="reason" class="form-label">Grund für den Beitrag (Optional)</label>
            <textarea 
              id="reason" 
              name="reason" 
              rows="3"
              placeholder="Möchtest du sonst noch etwas mitteilen? Welches Problem wurde für dich gelöst??"
              class="form-input"
            ></textarea>
          </div>
          
          <div class="form-group">
            <label for="contact" class="form-label">Kontakt (Optional)</label>
            <input 
              type="text" 
              id="contact" 
              name="contact" 
              placeholder="Discord: @username, Telegram: @username, oder andere Kontaktmöglichkeit"
              class="form-input"
            />
            <small class="form-help">Wird nur im Git-Issue angezeigt, falls Nachfragen entstehen</small>
          </div>
        </div>

        <div class="form-actions">
          <a href="/" class="btn btn-secondary">Abbruch</a>
          <button type="submit" id="submit-btn" class="btn btn-accent">
            <span id="submit-text">Abschicken</span>
            <span id="submit-spinner" class="hidden">⏳</span>
          </button>
        </div>
      </form>
    </div>

    <div id="success-modal"
        style="display:none; position:fixed; top:0; left:0; width:100%; height:100%;
                background:rgba(0,0,0,.5); z-index:1000; align-items:center; justify-content:center;">
      <div class="card" style="max-width:500px; width:90%; margin:2rem; text-align:center;">
        <div style="font-size:3rem; margin-bottom:1rem;">✅</div>
        <h3 style="margin-bottom:1rem;">Article Submitted!</h3>
        <p id="success-message" style="margin-bottom:1.5rem;">
          Your knowledge‑base article has been submitted as an issue for review by maintainers.
        </p>
        <div style="display:flex; gap:1rem; justify-content:center;">
          <a id="issue-link" href="#" target="_blank" class="btn btn-primary hidden">View Issue</a>
          <a href="/" class="btn btn-secondary">Back to Home</a>
        </div>
      </div>
    </div>

    <div id="message-container" class="message-container"></div>
  </div>
</BaseLayout>

<script>
interface UploadedFile {
  id: string;
  file: File;
  name: string;
  uploaded: boolean;
  url?: string;
}

declare global {
  interface Window {
    removeFile: (fileId: string) => void;
  }
}

class KnowledgebaseForm {
  private uploadedFiles: UploadedFile[] = [];
  private isSubmitting = false;
  private elements: Record<string, HTMLElement | null> = {};

  constructor() {
    this.init();
  }

  private init() {
    this.elements = {
      form: document.getElementById('kb-form'),
      submitBtn: document.getElementById('submit-btn'),
      submitText: document.getElementById('submit-text'),
      submitSpinner: document.getElementById('submit-spinner'),
      fileInput: document.getElementById('file-input'),
      uploadArea: document.getElementById('upload-area'),
      fileList: document.getElementById('file-list'),
      filesContainer: document.getElementById('files-container'),
      successModal: document.getElementById('success-modal')
    };

    if (!this.elements.form || !this.elements.submitBtn) {
      console.error('[KB FORM] Critical elements missing');
      return;
    }

    this.setupEventListeners();
    this.setupFileUpload();
  }

  private setupEventListeners() {
    this.elements.form?.addEventListener('submit', (e) => {
      e.preventDefault();
      if (!this.isSubmitting) {
        this.handleSubmit();
      }
    });
  }

  private setupFileUpload() {
    if (!this.elements.fileInput || !this.elements.uploadArea) return;

    this.elements.uploadArea.addEventListener('click', () => {
      (this.elements.fileInput as HTMLInputElement)?.click();
    });
    
    this.elements.uploadArea.addEventListener('dragover', (e) => {
      e.preventDefault();
      this.elements.uploadArea?.classList.add('drag-over');
    });
    
    this.elements.uploadArea.addEventListener('dragleave', () => {
      this.elements.uploadArea?.classList.remove('drag-over');
    });
    
    this.elements.uploadArea.addEventListener('drop', (e) => {
      e.preventDefault();
      this.elements.uploadArea?.classList.remove('drag-over');
      if (e.dataTransfer?.files) {
        this.handleFiles(Array.from(e.dataTransfer.files));
      }
    });

    this.elements.fileInput.addEventListener('change', (e) => {
      const target = e.target as HTMLInputElement;
      if (target?.files) {
        this.handleFiles(Array.from(target.files));
      }
    });
  }

  private handleFiles(files: File[]) {
    files.forEach(file => {
      const validation = this.validateFileBeforeUpload(file);
      if (!validation.valid) {
        console.log('[UPLOAD]Cannot upload ', file.name, ' Error: ', validation.error);
        return;
      }

      const fileId = Date.now() + '-' + Math.random().toString(36).substr(2, 9);
      const newFile: UploadedFile = {
        id: fileId,
        file,
        name: file.name,
        uploaded: false
      };
      this.uploadedFiles.push(newFile);
      this.uploadFile(fileId);
    });
    this.renderFileList();
  }

  private validateFileBeforeUpload(file: File): { valid: boolean; error?: string } {
    const maxSizeBytes = 50 * 1024 * 1024; // 50MB
    if (file.size > maxSizeBytes) {
      const sizeMB = (file.size / 1024 / 1024).toFixed(1);
      const maxMB = (maxSizeBytes / 1024 / 1024).toFixed(0);
      return { 
        valid: false, 
        error: `File too large (${sizeMB}MB). Maximum size: ${maxMB}MB` 
      };
    }

    const allowedExtensions = [
      '.pdf', '.doc', '.docx', '.txt', '.md', '.markdown', '.csv', '.json', 
      '.xml', '.html', '.rtf', '.yaml', '.yml', '.zip', '.tar', '.gz', 
      '.rar', '.7z', '.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg', 
      '.mp4', '.webm', '.mov', '.avi'
    ];
    
    const fileName = file.name.toLowerCase();
    const hasValidExtension = allowedExtensions.some(ext => fileName.endsWith(ext));
    
    if (!hasValidExtension) {
      return {
        valid: false,
        error: `File type not allowed. Allowed: ${allowedExtensions.join(', ')}`
      };
    }

    return { valid: true };
  }

  private async uploadFile(fileId: string) {
    const fileItem = this.uploadedFiles.find(f => f.id === fileId);
    if (!fileItem) {
      console.error('[UPLOAD] File item not found for ID:', fileId);
      return;
    }

    console.log('[UPLOAD] Starting upload for:', fileItem.name, 'Size:', fileItem.file.size, 'Type:', fileItem.file.type);

    const formData = new FormData();
    formData.append('file', fileItem.file);
    formData.append('type', 'knowledgebase');

    try {
      console.log('[UPLOAD] Sending request to /api/upload/media');
      
      const response = await fetch('/api/upload/media', {
        method: 'POST',
        body: formData
      });

      console.log('[UPLOAD] Response status:', response.status);

      let responseText: string;
      let responseData: any;
      
      try {
        responseText = await response.text();
        console.log('[UPLOAD] Raw response:', responseText.substring(0, 200));
        
        try {
          responseData = JSON.parse(responseText);
        } catch (parseError) {
          responseData = { error: responseText };
        }
      } catch (readError) {
        console.error('[UPLOAD] Failed to read response:', readError);
        throw new Error('Failed to read server response');
      }

      if (response.ok) {
        console.log('[UPLOAD] Success result:', responseData);
        
        fileItem.uploaded = true;
        fileItem.url = responseData.url;
        this.renderFileList();
        
      } else {
        
        if (responseData && responseData.details) {
          console.error('[UPLOAD] Error details:', responseData.details);
        }
        
      }
    } catch (error) {
      console.error('[UPLOAD] Upload error for', fileItem.name, ':', error);
      
      const errorMessage = error instanceof Error 
        ? error.message 
        : 'Unknown upload error';
      
      this.removeFile(fileId);
    }
  }

  private removeFile(fileId: string) {
    this.uploadedFiles = this.uploadedFiles.filter(f => f.id !== fileId);
    this.renderFileList();
  }

  private renderFileList() {
    if (!this.elements.filesContainer || !this.elements.fileList) return;

    if (this.uploadedFiles.length > 0) {
      (this.elements.fileList as HTMLElement).style.display = 'block';
      (this.elements.filesContainer as HTMLElement).innerHTML = this.uploadedFiles.map(file => `
        <div class="file-item">
          <div class="file-info">
            <strong>${file.name}</strong>
            <div class="file-meta">
              ${(file.file.size / 1024 / 1024).toFixed(2)} MB
              ${file.uploaded ? 
                '<span class="file-status success">✓ Uploaded</span>' : 
                '<span class="file-status pending">⏳ Uploading...</span>'
              }
            </div>
          </div>
          <button type="button" onclick="window.removeFile('${file.id}')" class="btn btn-danger btn-small">Remove</button>
        </div>
      `).join('');
    } else {
      (this.elements.fileList as HTMLElement).style.display = 'none';
    }
  }

  private async handleSubmit() {
    if (this.isSubmitting) return;

    this.isSubmitting = true;
    
    (this.elements.submitBtn as HTMLButtonElement).disabled = true;
    (this.elements.submitText as HTMLElement).textContent = 'Submitting...';
    (this.elements.submitSpinner as HTMLElement).style.display = 'inline';

    try {
      const formData = new FormData(this.elements.form as HTMLFormElement);
      
      const categoriesValue = (formData.get('categories') as string) || '';
      const tagsValue = (formData.get('tags') as string) || '';
      
      const categories = categoriesValue.split(',').map(s => s.trim()).filter(s => s);
      const tags = tagsValue.split(',').map(s => s.trim()).filter(s => s);
      formData.set('categories', JSON.stringify(categories));
      formData.set('tags', JSON.stringify(tags));

      formData.set('uploadedFiles', JSON.stringify(this.uploadedFiles.filter(f => f.uploaded)));

      const response = await fetch('/api/contribute/knowledgebase', {
        method: 'POST',
        body: formData
      });

      const result = await response.json();

      if (result.success) {
        this.showSuccess(result);
      } else {
        throw new Error(result.error || 'Submission failed');
      }

    } catch (error) {
      console.error('[KB FORM] Submission error:', error);
    } finally {
      this.isSubmitting = false;
      (this.elements.submitBtn as HTMLButtonElement).disabled = false;
      (this.elements.submitText as HTMLElement).textContent = 'Submit Article';
      (this.elements.submitSpinner as HTMLElement).style.display = 'none';
    }
  }

  private showSuccess(result: any) {
    const successMessage = document.getElementById('success-message');
    const issueLink = document.getElementById('issue-link') as HTMLAnchorElement;
    
    if (successMessage) {
      successMessage.textContent = 'Your knowledge base article has been submitted as an issue for review by maintainers.';
    }
    
    if (result.issueUrl && issueLink) {
      issueLink.href = result.issueUrl;
      issueLink.style.display = 'inline-flex';
    }
    
    (this.elements.successModal as HTMLElement).style.display = 'flex';
    
    (this.elements.form as HTMLFormElement).reset();
    this.uploadedFiles = [];
    this.renderFileList();
  }

  public removeFileById(fileId: string) {
    this.removeFile(fileId);
  }
}

let formInstance: KnowledgebaseForm;

window.removeFile = (fileId: string) => {
  if (formInstance) {
    formInstance.removeFileById(fileId);
  }
};

document.addEventListener('DOMContentLoaded', () => {
  formInstance = new KnowledgebaseForm();
});
</script>