<template>
  <div class="generator-card">
    <h2>Wygeneruj Fakturę PDF</h2>
    
    <div class="upload-section">
      <label for="invoiceFile" class="file-input-label">
        <span class="upload-icon">📁</span>
        <span v-if="!selectedFile" class="upload-text">
          Kliknij aby wybrać plik XML
        </span>
        <span v-else class="file-name">
          {{ selectedFile.name }}
        </span>
      </label>
      <input
        id="invoiceFile"
        type="file"
        accept=".xml"
        @change="onFileSelected"
        class="file-input-hidden"
      />
    </div>

    <div v-if="selectedFile" class="file-info">
      <p class="file-size">Rozmiar: {{ fileSize }}</p>
      <p class="file-type">Format: XML</p>
    </div>

    <div class="button-group">
      <button
        @click="generatePdf"
        :disabled="!selectedFile || isLoading"
        class="btn btn-primary"
      >
        <span v-if="!isLoading" class="btn-text">🚀 Wygeneruj PDF</span>
        <span v-else class="btn-text">⏳ Generowanie...</span>
      </button>
      <button
        v-if="selectedFile"
        @click="clearFile"
        class="btn btn-secondary"
      >
        🗑️ Wyczyść
      </button>
    </div>

    <div v-if="progress" class="progress-section">
      <div class="progress-bar">
        <div class="progress-fill" :style="{ width: progress + '%' }"></div>
      </div>
      <p class="progress-text">{{ progress }}%</p>
    </div>

    <div v-if="additionalData" class="data-preview">
      <h3>Dane Dodatkowe</h3>
      <div class="data-item">
        <span class="data-label">Nr KSeF:</span>
        <span class="data-value">{{ additionalData.nrKSeF }}</span>
      </div>
      <div class="data-item">
        <span class="data-label">QR Code:</span>
        <span class="data-value data-value-url">{{ additionalData.qrCode }}</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { generateInvoice } from '../../lib-public';
import type { AdditionalDataTypes } from '../../lib-public/types/common.types';

const emit = defineEmits<{
  'pdf-generated': [filename: string];
  'error': [error: string];
}>();

const selectedFile = ref<File | null>(null);
const isLoading = ref(false);
const progress = ref(0);

const additionalData: AdditionalDataTypes = {
  nrKSeF: '5555555555-20250808-9231003CA67B-BE',
  qrCode: 'https://ksef-test.mf.gov.pl/invoice/5265877635/26-10-2025/HS5E1zrA8WVjDNq_xMVIN5SD6nyRymmQ-BcYHReUAa0',
};

const fileSize = computed(() => {
  if (!selectedFile.value) return '0 B';
  const bytes = selectedFile.value.size;
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return Math.round((bytes / Math.pow(k, i)) * 100) / 100 + ' ' + sizes[i];
});

const onFileSelected = (event: Event) => {
  const target = event.target as HTMLInputElement;
  const file = target.files?.[0];
  if (file && file.type === 'text/xml') {
    selectedFile.value = file;
  } else {
    emit('error', 'Wybierz prawidłowy plik XML');
    selectedFile.value = null;
  }
};

const clearFile = () => {
  selectedFile.value = null;
  progress.value = 0;
};

const generatePdf = async () => {
  if (!selectedFile.value) {
    emit('error', 'Brak wybranego pliku');
    return;
  }

  try {
    isLoading.value = true;
    progress.value = 20;

    // Symulacja postępu
    const progressInterval = setInterval(() => {
      progress.value = Math.min(progress.value + Math.random() * 30, 90);
    }, 300);

    // Generowanie PDF
    const pdfBlob = await generateInvoice(
      selectedFile.value,
      additionalData,
      'blob'
    );

    clearInterval(progressInterval);
    progress.value = 100;

    // Download PDF
    const url = URL.createObjectURL(pdfBlob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `faktura-${Date.now()}.pdf`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);

    emit('pdf-generated', link.download);

    // Reset po 1 sekundzie
    setTimeout(() => {
      clearFile();
      isLoading.value = false;
    }, 1000);
  } catch (error) {
    emit('error', error instanceof Error ? error.message : 'Nieznanego błędu');
    clearFile();
    isLoading.value = false;
  }
};
</script>

<style scoped>
.generator-card {
  background: white;
  border-radius: 12px;
  padding: 2rem;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  animation: slideUp 0.5s ease-out;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.generator-card h2 {
  margin: 0 0 1.5rem 0;
  color: #333;
  font-size: 1.5rem;
}

.upload-section {
  margin-bottom: 1.5rem;
}

.file-input-label {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 1rem;
  padding: 2rem;
  border: 2px dashed #667eea;
  border-radius: 8px;
  background: #f8f9ff;
  cursor: pointer;
  transition: all 0.3s ease;
}

.file-input-label:hover {
  background: #f0f2ff;
  border-color: #764ba2;
}

.upload-icon {
  font-size: 2rem;
}

.upload-text,
.file-name {
  font-weight: 500;
  color: #667eea;
}

.file-name {
  color: #764ba2;
  overflow: hidden;
  text-overflow: ellipsis;
}

.file-input-hidden {
  display: none;
}

.file-info {
  display: flex;
  gap: 1rem;
  padding: 1rem;
  background: #f0f2ff;
  border-radius: 8px;
  margin-bottom: 1rem;
  font-size: 0.9rem;
}

.file-info p {
  margin: 0;
  color: #667eea;
}

.file-size {
  font-weight: 600;
}

.button-group {
  display: flex;
  gap: 1rem;
  margin-bottom: 1.5rem;
  flex-wrap: wrap;
}

.btn {
  flex: 1;
  min-width: 150px;
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
}

.btn-primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.btn-primary:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
}

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

.btn-secondary {
  background: #e0e0e0;
  color: #333;
}

.btn-secondary:hover {
  background: #d0d0d0;
  transform: translateY(-2px);
}

.btn-text {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.progress-section {
  margin-bottom: 1.5rem;
}

.progress-bar {
  width: 100%;
  height: 8px;
  background: #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 0.5rem;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
  transition: width 0.3s ease;
}

.progress-text {
  text-align: center;
  font-size: 0.9rem;
  color: #667eea;
  font-weight: 600;
  margin: 0;
}

.data-preview {
  padding: 1rem;
  background: #f8f9ff;
  border-radius: 8px;
  border-left: 4px solid #667eea;
}

.data-preview h3 {
  margin: 0 0 1rem 0;
  color: #667eea;
  font-size: 1rem;
}

.data-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 0.75rem;
  gap: 1rem;
}

.data-label {
  font-weight: 600;
  color: #667eea;
}

.data-value {
  color: #666;
  word-break: break-word;
}

.data-value-url {
  font-size: 0.85rem;
  opacity: 0.8;
}

@media (max-width: 768px) {
  .generator-card {
    padding: 1.5rem;
  }

  .button-group {
    flex-direction: column;
  }

  .btn {
    min-width: unset;
  }

  .file-info {
    flex-direction: column;
  }
}
</style>
