<template>
    <div class="flex flex-col h-full">
        <Toolbar :config="toolbarConfig" />

        <div class="overflow-y-auto flex-1">
            <div class="px-6 py-8">

                <!-- Zone de dépôt -->
                <section v-if="!store.hasFiles" class="border-t border-gray-200 dark:border-gray-700 pt-6">
                    <h2 class="text-xs font-semibold text-gray-400 dark:text-gray-500 uppercase tracking-wider mb-4">Fichiers</h2>
                    <FileUpload
                        label="Importer des fichiers CBZ/CBR"
                        accept=".cbz,.cbr"
                        :multiple="true"
                        description="Formats CBZ ou CBR uniquement"
                        @files-selected="store.addFiles($event)"
                    />
                </section>

                <!-- Fichiers en cours -->
                <template v-if="store.hasFiles && !store.allFilesProcessed">
                    <section class="border-t border-gray-200 dark:border-gray-700 pt-6">
                        <div class="flex items-center justify-between mb-3">
                            <h2 class="text-xs font-semibold text-gray-400 dark:text-gray-500 uppercase tracking-wider">
                                {{ store.totalFiles }} fichier(s)
                            </h2>
                            <span class="text-xs text-gray-500 dark:text-gray-400">
                                {{ store.importedCount }}/{{ store.totalFiles }}
                                <span v-if="store.errorCount > 0" class="text-red-500 ml-1">· {{ store.errorCount }} erreur(s)</span>
                            </span>
                        </div>
                        <div class="bg-gray-200 dark:bg-gray-700 h-1.5 mb-4">
                            <div
                                class="bg-green-600 h-1.5 transition-all duration-300"
                                :style="{ width: store.progressPercentage + '%' }"
                            />
                        </div>
                        <div class="divide-y divide-gray-100 dark:divide-gray-700/50">
                            <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="(n) => store.setFileChapterNumber(file.id, n)"
                                @volume-number-selected="(n) => store.setFileVolumeNumber(file.id, n)"
                                @import-file="() => importSingleFile(file.id)"
                                @retry-file="() => retryFile(file.id)"
                                @remove-file="() => store.removeFile(file.id)"
                            />
                        </div>
                    </section>
                </template>

                <!-- Résultats -->
                <ImportResults v-if="store.allFilesProcessed" />

            </div>
        </div>
    </div>
</template>

<script setup>
import { ArrowUpTrayIcon, SparklesIcon, TrashIcon } from '@heroicons/vue/24/outline';
import { computed, onUnmounted } from 'vue';
import FileUpload from '../../../../shared/components/ui/FileUpload.vue';
import Toolbar from '../../../../shared/components/ui/Toolbar.vue';
import { useNewImportStore } from '../../application/store/newImportStore';
import FileImportCard from '../components/FileImportCard.vue';
import ImportResults from '../components/ImportResults.vue';

const store = useNewImportStore();

const toolbarConfig = computed(() => ({
    leftSection: [
        { type: 'label', text: 'Import de bibliothèque', class: 'text-sm font-medium' },
    ],
    rightSection: [
        ...(store.analyzedFiles.length > 0 ? [{
            type: 'button',
            icon: SparklesIcon,
            label: 'Sélection auto',
            onClick: () => store.autoSelectBestMatches(),
        }] : []),
        ...(store.hasReadyFiles ? [{
            type: 'button',
            icon: ArrowUpTrayIcon,
            label: `Importer (${store.readyCount})`,
            onClick: importAllFiles,
            disabled: store.isLoading,
        }] : []),
        {
            type: 'button',
            icon: TrashIcon,
            label: 'Effacer',
            onClick: () => store.clearFiles(),
        },
    ],
}));

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);
    }
};

onUnmounted(() => {
    store.resetGlobalState();
});
</script>
