import { defineStore } from 'pinia';
import { useNotifications } from '../../../../shared/composables/useNotifications';
import { FileImport } from '../../domain/entities/FileImport';
import { ApiImportRepository } from '../../infrastructure/api/apiImportRepository';

const importRepository = new ApiImportRepository();
const { showSuccess, showError, showInfo } = useNotifications();

export const useNewImportStore = defineStore('newImport', {
    state: () => ({
        // Files being processed
        files: [], // Array of FileImport entities

        // Loading states
        analyzingFiles: new Set(), // File IDs being analyzed
        importingFiles: new Set(), // File IDs being imported

        // Global states
        isLoading: false,
        globalError: null,
    }),

    getters: {
        // File status getters
        pendingFiles: (state) => state.files.filter(f => f.isPending()),
        analyzedFiles: (state) => state.files.filter(f => f.isAnalyzed()),
        readyFiles: (state) => state.files.filter(f => f.isReadyForImport()),
        importedFiles: (state) => state.files.filter(f => f.isImported()),
        errorFiles: (state) => state.files.filter(f => f.hasError()),

        // Counts
        totalFiles: (state) => state.files.length,
        readyCount: (state) => state.files.filter(f => f.isReadyForImport()).length,
        importedCount: (state) => state.files.filter(f => f.isImported()).length,
        errorCount: (state) => state.files.filter(f => f.hasError()).length,

        // Status helpers
        hasFiles: (state) => state.files.length > 0,
        hasReadyFiles: (state) => state.files.some(f => f.isReadyForImport()),
        allFilesProcessed: (state) => {
            return state.files.length > 0 &&
                   state.files.every(f => f.isImported() || f.hasError());
        },

        // Progress
        progressPercentage: (state) => {
            if (state.files.length === 0) return 0;
            const processed = state.files.filter(f => f.isImported() || f.hasError()).length;
            return Math.round((processed / state.files.length) * 100);
        },

        // Specific file finders
        getFileById: (state) => (id) => {
            return state.files.find(f => f.id === id);
        }
    },

    actions: {
        // === FILE MANAGEMENT ===

        /**
         * Add files to the import queue
         */
        addFiles(fileList) {
            const validFiles = Array.from(fileList).filter(file => {
                const extension = file.name.split('.').pop().toLowerCase();
                return ['cbz', 'cbr'].includes(extension);
            });

            if (validFiles.length === 0) {
                showError('Aucun fichier CBZ/CBR valide sélectionné');
                return;
            }

            const newFiles = validFiles.map(file => FileImport.create(file));
            this.files.push(...newFiles);

            showInfo(`${newFiles.length} fichier(s) ajouté(s) à la queue d'import`);

            // Auto-analyze all new files
            this.analyzeAllPendingFiles();
        },

        /**
         * Remove a file from the queue
         */
        removeFile(fileId) {
            const index = this.files.findIndex(f => f.id === fileId);
            if (index !== -1) {
                this.files.splice(index, 1);
            }
        },

        /**
         * Clear all files
         */
        clearFiles() {
            this.files = [];
            this.analyzingFiles.clear();
            this.importingFiles.clear();
            this.globalError = null;
        },

        // === ANALYSIS ACTIONS ===

        /**
         * Analyze all pending files
         */
        async analyzeAllPendingFiles() {
            const pendingFiles = this.pendingFiles;
            if (pendingFiles.length === 0) return;

            this.isLoading = true;
            try {
                await Promise.all(
                    pendingFiles.map(file => this.analyzeFile(file.id))
                );
                showSuccess(`${pendingFiles.length} fichier(s) analysé(s) avec succès`);
            } catch (error) {
                console.error('Error analyzing files:', error);
                this.globalError = 'Erreur lors de l\'analyse des fichiers';
            } finally {
                this.isLoading = false;
            }
        },

        /**
         * Analyze a specific file
         */
        async analyzeFile(fileId) {
            const fileIndex = this.files.findIndex(f => f.id === fileId);
            if (fileIndex === -1) return;

            const file = this.files[fileIndex];
            if (!file.isPending()) return;

            this.analyzingFiles.add(fileId);

            try {
                const analysis = await importRepository.analyzeFilename(file.filename);
                file.setAnalysis(analysis);

                // Force reactivity by replacing the object in the array
                this.files[fileIndex] = file;

                if (!file.hasMatches()) {
                    showError(`Aucun manga trouvé pour le fichier: ${file.filename}`);
                }
            } catch (error) {
                console.error(`Error analyzing file ${file.filename}:`, error);
                file.setError(`Erreur d'analyse: ${error.message}`);
                this.files[fileIndex] = file;
                showError(`Erreur lors de l'analyse de ${file.filename}`);
            } finally {
                this.analyzingFiles.delete(fileId);
            }
        },

        // === SELECTION ACTIONS ===

        /**
         * Update manga selection for a file
         */
        setFileManga(fileId, manga) {
            const fileIndex = this.files.findIndex(f => f.id === fileId);
            if (fileIndex !== -1) {
                this.files[fileIndex].setSelectedManga(manga);
                // Force reactivity
                this.files[fileIndex] = this.files[fileIndex];
            }
        },

        /**
         * Update chapter number for a file
         */
        setFileChapterNumber(fileId, chapterNumber) {
            const fileIndex = this.files.findIndex(f => f.id === fileId);
            if (fileIndex !== -1) {
                this.files[fileIndex].setSelectedChapterNumber(chapterNumber);
                // Force reactivity
                this.files[fileIndex] = this.files[fileIndex];
            }
        },

        /**
         * Update volume number for a file
         */
        setFileVolumeNumber(fileId, volumeNumber) {
            const fileIndex = this.files.findIndex(f => f.id === fileId);
            if (fileIndex !== -1) {
                this.files[fileIndex].setSelectedVolumeNumber(volumeNumber);
                // Force reactivity
                this.files[fileIndex] = this.files[fileIndex];
            }
        },

        // === IMPORT ACTIONS ===

        /**
         * Import all ready files
         */
        async importAllReadyFiles() {
            const readyFiles = this.readyFiles;
            if (readyFiles.length === 0) {
                showError('Aucun fichier prêt pour l\'import');
                return;
            }

            this.isLoading = true;
            let successCount = 0;
            let errorCount = 0;

            try {
                for (const file of readyFiles) {
                    try {
                        await this.importFile(file.id);
                        successCount++;
                    } catch (error) {
                        errorCount++;
                        console.error(`Failed to import file ${file.filename}:`, error);
                    }
                }

                if (successCount > 0) {
                    showSuccess(`${successCount} fichier(s) importé(s) avec succès`);
                }
                if (errorCount > 0) {
                    showError(`${errorCount} fichier(s) ont échoué lors de l'import`);
                }
            } finally {
                this.isLoading = false;
            }
        },

        /**
         * Import a specific file
         */
        async importFile(fileId) {
            const file = this.getFileById(fileId);
            if (!file || !file.isReadyForImport()) {
                throw new Error('File is not ready for import');
            }

            this.importingFiles.add(fileId);
            file.setImporting();

            try {
                const importData = file.getImportData();
                await importRepository.importFile(
                    file.file,
                    importData.mangaId,
                    importData.chapterNumber,
                    importData.volumeNumber
                );

                file.setImported();
                showSuccess(`Fichier ${file.filename} importé avec succès`);
            } catch (error) {
                console.error(`Error importing file ${file.filename}:`, error);
                file.setError(`Erreur d'import: ${error.message}`);
                throw error;
            } finally {
                this.importingFiles.delete(fileId);
            }
        },

        /**
         * Retry import for a failed file
         */
        async retryFile(fileId) {
            const file = this.getFileById(fileId);
            if (!file) return;

            if (file.hasError() && file.selectedManga) {
                // If the file had an import error but has selections, retry import
                await this.importFile(fileId);
            } else {
                // If the file had an analysis error, retry analysis
                file.status = 'pending';
                file.errorMessage = null;
                await this.analyzeFile(fileId);
            }
        },

        // === UTILITY ACTIONS ===

        /**
         * Auto-select best matches for all files
         */
        autoSelectBestMatches() {
            let selectedCount = 0;

            this.analyzedFiles.forEach(file => {
                const bestMatch = file.getBestMatch();
                if (bestMatch) {
                    file.setSelectedManga(bestMatch);
                    selectedCount++;
                }
            });

            if (selectedCount > 0) {
                showInfo(`${selectedCount} correspondance(s) automatique(s) effectuée(s)`);
            }
        },

        /**
         * Reset global state
         */
        resetGlobalState() {
            this.globalError = null;
            this.isLoading = false;
            this.analyzingFiles.clear();
            this.importingFiles.clear();
        }
    }
});
