<template>
    <div class="container mx-auto px-4 py-8">
        <!-- Header -->
        <div class="mb-8">
            <h1 class="text-3xl font-bold text-gray-900 mb-2">Import de Bibliothèque</h1>
            <p class="text-gray-600">
                Importez vos fichiers CBZ/CBR dans votre bibliothèque Mangarr
            </p>
        </div>

        <!-- Progress Bar (if files are being processed) -->
        <div v-if="store.hasFiles && !store.allFilesProcessed" class="mb-8">
            <div class="bg-white rounded-lg shadow-sm p-6">
                <div class="flex items-center justify-between mb-2">
                    <span class="text-sm font-medium text-gray-700">Progression</span>
                    <span class="text-sm text-gray-500">{{ store.progressPercentage }}%</span>
                </div>
                <div class="w-full bg-gray-200 rounded-full h-2">
                    <div
                        class="bg-blue-600 h-2 rounded-full transition-all duration-300"
                        :style="{ width: store.progressPercentage + '%' }"
                    ></div>
                </div>
                <div class="flex justify-between text-xs text-gray-500 mt-2">
                    <span>{{ store.importedCount }} importés</span>
                    <span>{{ store.errorCount }} erreurs</span>
                    <span>{{ store.totalFiles }} total</span>
                </div>
            </div>
        </div>

        <!-- File Upload Zone -->
        <div v-if="!store.hasFiles || store.allFilesProcessed" class="mb-8">
            <FileUpload
                label="Importer des fichiers CBZ/CBR"
                accept=".cbz,.cbr"
                :multiple="true"
                description="Formats CBZ ou CBR uniquement"
                @files-selected="handleFilesSelected"
            />
        </div>

        <!-- Files List -->
        <div v-if="store.hasFiles" class="space-y-6">
            <!-- Action Buttons -->
            <div class="flex flex-wrap gap-4 mb-6">
                <button
                    v-if="store.hasReadyFiles"
                    @click="importAllFiles"
                    :disabled="store.isLoading"
                    class="bg-green-600 hover:bg-green-700 disabled:bg-gray-400 text-white px-4 py-2 rounded-md font-medium"
                >
                    <LoadingSpinner v-if="store.isLoading" class="w-4 h-4 mr-2" />
                    Importer tous les fichiers prêts ({{ store.readyCount }})
                </button>

                <button
                    v-if="store.analyzedFiles.length > 0"
                    @click="autoSelectMatches"
                    class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-md font-medium"
                >
                    Sélection automatique
                </button>

                <button
                    @click="clearAllFiles"
                    class="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-md font-medium"
                >
                    Effacer tout
                </button>
            </div>

            <!-- Files Grid -->
            <div class="grid gap-6">
                <FileImportCard
                    v-for="file in store.files"
                    :key="file.id"
                    :file="file"
                    :is-analyzing="store.analyzingFiles.has(file.id)"
                    :is-importing="store.importingFiles.has(file.id)"
                    @manga-selected="(manga) => store.setFileManga(file.id, manga)"
                    @chapter-number-selected="(chapterNumber) => store.setFileChapterNumber(file.id, chapterNumber)"
                    @volume-number-selected="(volumeNumber) => store.setFileVolumeNumber(file.id, volumeNumber)"
                    @import-file="() => importSingleFile(file.id)"
                    @retry-file="() => retryFile(file.id)"
                    @remove-file="() => store.removeFile(file.id)"
                />
            </div>
        </div>

        <!-- Results Summary (when all files are processed) -->
        <div v-if="store.allFilesProcessed" class="mt-8">
            <ImportResults />
        </div>
    </div>
</template>

<script setup>
import { onUnmounted } from 'vue';
import FileUpload from '../../../../shared/components/ui/FileUpload.vue';
import LoadingSpinner from '../../../../shared/components/ui/LoadingSpinner.vue';
import { useNewImportStore } from '../../application/store/newImportStore';
import FileImportCard from '../components/FileImportCard.vue';
import ImportResults from '../components/ImportResults.vue';

const store = useNewImportStore();

// === EVENT HANDLERS ===

const handleFilesSelected = (files) => {
    store.addFiles(files);
};

const importAllFiles = async () => {
    try {
        await store.importAllReadyFiles();
    } catch (error) {
        console.error('Error importing files:', error);
    }
};

const importSingleFile = async (fileId) => {
    try {
        await store.importFile(fileId);
    } catch (error) {
        console.error('Error importing file:', error);
    }
};

const retryFile = async (fileId) => {
    try {
        await store.retryFile(fileId);
    } catch (error) {
        console.error('Error retrying file:', error);
    }
};

const autoSelectMatches = () => {
    store.autoSelectBestMatches();
};

const clearAllFiles = () => {
    if (confirm('Êtes-vous sûr de vouloir effacer tous les fichiers ?')) {
        store.clearFiles();
    }
};

// === LIFECYCLE ===

// Reset state when component unmounts
onUnmounted(() => {
    store.resetGlobalState();
});
</script>
