angular.module('edecApp')
    .controller('ExportController', function($scope, $http, $window, $rootScope, $timeout, $location, ConfigService, TranslationService) {
        
        function initScope() {
            $scope.step = 1;
            $scope.method = null;
            $scope.vehicle = {};
            $scope.parties = {
                consignor: { name: '', firstname: '', address: '', zip: '', city: '', country: 'CH', ide: '' },
                consignee: { name: '', firstname: '', address: '', zip: '', city: '', country: '', ide: '' },
                declarant: { name: '', firstname: '', address: '', zip: '', city: '', country: '', ide: '' }
            };
            $scope.declarantType = 'consignor';
            $scope.declaration = {
                destination_country: '',
                transport_mode: '9',
                purchase_currency: 'CHF',
                purchase_price: 0,
                language: $rootScope.lang || 'fr'
            };
            $scope.classification = null;
            $scope.ocrLoading = false;
            $scope.preparing = false;
            $scope.ocrAttempted = false;
            $scope.vinValid = null;
            $scope.classificationError = null;
            $scope.reporting = false;
            $scope.sessionToken = null;
            $scope.submissionProgress = 0;
            $scope.submissionStep = '';
            $scope.submissionResult = null;
            $scope.showProgress = false;
            $scope.eventSource = null;
			$scope.origin = null;
            $scope.showStripeButton = false;
            $scope.tooltips = {
                transportMode: false,
                destinationCountry: false
            };
            $scope.ocrCountdown = 0;
            $scope.ocrCountdownActive = false;
        }

        const SESSION_STORAGE_KEY = 'edec_export_form';
        let saveTimeout = null;
        
        // --- DÉBUT CORRECTION STRIPE: Nouvelle fonction utilitaire ---
        function loadStripeBuyButtonScript() {
            $timeout(function() {
                if (!document.getElementById('stripe-buy-button-script')) {
                    const script = document.createElement('script');
                    script.id = 'stripe-buy-button-script';
                    script.src = 'https://js.stripe.com/v3/buy-button.js';
                    script.async = true;
                    document.head.appendChild(script);
                }
            }, 100);
        }
        // --- FIN CORRECTION STRIPE ---

        function saveState() {
            $timeout.cancel(saveTimeout);
            saveTimeout = $timeout(function() {
                const dataToSave = {
                    step: Math.min($scope.step || 1, 3),
                    method: $scope.method,
                    vehicle: angular.copy($scope.vehicle),
                    parties: angular.copy($scope.parties),
                    declarantType: $scope.declarantType,
                    declaration: angular.copy($scope.declaration),
                    sessionToken: $scope.sessionToken
                };
                sessionStorage.setItem(SESSION_STORAGE_KEY, JSON.stringify(dataToSave));
            }, 500);
        }

		// Fonction pour mettre en évidence TOUS les champs obligatoires manquants
		$scope.highlightInvalidFields = function(formName) {
			const form = $scope[formName];
			if (!form) return false;
			
			let hasErrors = false;
			
			// Marquer tous les champs invalides comme "touched" et "dirty"
			angular.forEach(form, function(field, fieldName) {
				if (fieldName.indexOf('$') !== 0) { // Ignorer les propriétés internes d'AngularJS
					if (field && field.$invalid) {
						field.$setDirty();
						field.$setTouched();
						hasErrors = true;
					}
				}
			});
			
			// Forcer un digest pour mettre à jour l'affichage
			if (!$scope.$$phase) {
				$scope.$apply();
			}
			
			// Scroll vers le premier champ invalide après un court délai
			$timeout(function() {
				const firstInvalid = document.querySelector('.ng-invalid.ng-touched:not(form)');
				if (firstInvalid) {
					firstInvalid.scrollIntoView({ behavior: 'smooth', block: 'center' });
					
					// Focus sur le champ si c'est un input/select
					if (firstInvalid.tagName === 'INPUT' || firstInvalid.tagName === 'SELECT') {
						firstInvalid.focus();
					}
				}
			}, 200);
			
			return hasErrors;
		};

        function loadSavedState() {
            const savedData = sessionStorage.getItem(SESSION_STORAGE_KEY);
            if (savedData) {
                try {
                    const parsedData = JSON.parse(savedData);
                    $scope.step = parsedData.step || 1;
                    $scope.method = parsedData.method || null;
                    angular.extend($scope.vehicle, parsedData.vehicle || {});
                    angular.extend($scope.parties, parsedData.parties || {
                        consignor: { country: 'CH' }, consignee: {}, declarant: {}
                    });
                    $scope.declarantType = parsedData.declarantType || 'consignor';
                    angular.extend($scope.declaration, parsedData.declaration || {});
                    $scope.sessionToken = parsedData.sessionToken || null;
                    
                    if ($scope.sessionToken && $scope.step === 3) {
                        $scope.showStripeButton = true;
                        // --- CORRECTION STRIPE APPLIQUÉE ICI ---
                        loadStripeBuyButtonScript();
                        // ----------------------------------------
                    }
                    
                    $rootScope.showNotification($rootScope.t('data_restored'), 'info');
                    return true;
                } catch (e) {
                    sessionStorage.removeItem(SESSION_STORAGE_KEY);
                    return false;
                }
            }
            return false;
        }

        const urlParams = new URLSearchParams($window.location.search);
        if (urlParams.get('payment_cancelled') === 'true') {
            $rootScope.showNotification('Paiement annulé. Vous pouvez réessayer.', 'warning');
            $location.search('payment_cancelled', null);
        }

        initScope();
        loadSavedState();

        ConfigService.getCurrencies().then(data => $scope.currencies = data);

        // Initialiser vide
        $scope.transportModes = [];

        // Attendre que les traductions soient chargées
        TranslationService.getPromise.then(function() {
            // Fonction pour générer les modes de transport traduits
            $scope.getTransportModes = function() {
                return [
                    { value: '9', label: $rootScope.t('transport_mode_9') },
                    { value: '3', label: $rootScope.t('transport_mode_3') },
                    { value: '2', label: $rootScope.t('transport_mode_2') },
                    { value: '4', label: $rootScope.t('transport_mode_4') },
                    { value: '8', label: $rootScope.t('transport_mode_8') },
                    { value: '7', label: $rootScope.t('transport_mode_7') }
                ];
            };
            
            // Initialiser les modes de transport
            $scope.transportModes = $scope.getTransportModes();
            
            // Mettre à jour quand la langue change
            $scope.$watch(() => $rootScope.lang, function(newLang) {
                if (newLang) {
                    $scope.transportModes = $scope.getTransportModes();
                }
            });
        });

        $scope.$watch('parties.consignor.ide', function(newVal) {
            $scope.isCompany = !!newVal && newVal.trim() !== 'CHE222251936';
        });

        $scope.$watch('vehicle', saveState, true);
        $scope.$watch('parties', saveState, true);
        $scope.$watch('declaration', saveState, true);
        $scope.$watch('declarantType', saveState);
        $scope.$watch('step', saveState);
        $scope.$watch('method', saveState);
		// Gestion de l'exclusivité IDE vs Prénom pour tous les parties
		$scope.$watch('parties.consignor.ide', function(newVal) {
			$scope.consignorHasIDE = !!newVal && newVal.trim() !== '';
		});

		$scope.$watch('parties.consignor.firstname', function(newVal) {
			$scope.consignorHasFirstname = !!newVal && newVal.trim() !== '';
		});

		$scope.$watch('parties.consignee.ide', function(newVal) {
			$scope.consigneeHasIDE = !!newVal && newVal.trim() !== '';
		});

		$scope.$watch('parties.consignee.firstname', function(newVal) {
			$scope.consigneeHasFirstname = !!newVal && newVal.trim() !== '';
		});

		$scope.$watch('parties.declarant.ide', function(newVal) {
			$scope.declarantHasIDE = !!newVal && newVal.trim() !== '';
		});

		$scope.$watch('parties.declarant.firstname', function(newVal) {
			$scope.declarantHasFirstname = !!newVal && newVal.trim() !== '';
		});

        $scope.$watch('submissionResult', function(newVal) {
            if (newVal) {
                sessionStorage.removeItem(SESSION_STORAGE_KEY);
            }
        });

        $scope.selectMethod = function(method) {
            $scope.method = method;
            $scope.step = 2;
        };

        $scope.triggerFileInput = () => document.getElementById('file-upload').click();

		$scope.handleFileSelect = function(event) {
			const files = event.target.files;
			if (!files || files.length === 0) return;

			$scope.$apply(() => {
				$scope.ocrLoading = true;
				$scope.ocrAttempted = true;
			});
			
			const formData = new FormData();
			formData.append('registration_card', files[0]);
			
			const context = $window.location.pathname.includes('/export') ? 'export' : 'import';
			formData.append('context', context);

			$http.post('/api/ocr', formData, {
				transformRequest: angular.identity,
				headers: { 'Content-Type': undefined }
			}).then(function(response) {
				const ocrData = response.data;
				// Pour export: ignorer paper_origin, ne pas remplir destination_country
				// Pour import: utiliser paper_origin pour dispatch_country
				if (context === 'import' && ocrData.paper_origin && $rootScope.countries) {
					const ocrCountryName = ocrData.paper_origin.toLowerCase().trim();
					const countryCode = Object.keys($rootScope.countries).find(code => {
						const fullCountryName = $rootScope.countries[code].toLowerCase().trim();
						const mainCountryName = fullCountryName.split('(')[0].trim();
						return mainCountryName === ocrCountryName;
					});
					if (countryCode) {
						$scope.declaration.dispatch_country = countryCode;
					}
				}				
				// Supprimer paper_origin sans l'utiliser
				delete ocrData.paper_origin;
				angular.extend($scope.vehicle, ocrData);
				
				if ($scope.vehicle.vin) $scope.validateVIN();
				$scope.updateClassification();
				$rootScope.showNotification($rootScope.t('ocr_success'), 'success');
				$scope.startOcrCountdown();
			}).catch(function(error) {
				const details = error.data?.details || error.data?.error || 'Erreur inconnue';
				$rootScope.showNotification('Erreur OCR: ' + details, 'error');
			}).finally(() => {
				$scope.ocrLoading = false;
			});
		};

        $scope.startOcrCountdown = function() {
            $scope.ocrCountdown = 30;
            $scope.ocrCountdownActive = true;
            
            const interval = setInterval(function() {
                $scope.$apply(function() {
                    $scope.ocrCountdown--;
                    if ($scope.ocrCountdown <= 0) {
                        $scope.ocrCountdownActive = false;
                        clearInterval(interval);
                    }
                });
            }, 1000);
        };

        $scope.validateVIN = function() {
            if (!$scope.vehicle.vin || $scope.vehicle.vin.length !== 17) {
                $scope.vinValid = false;
                return;
            }
            $http.post('/api/validate-vin', { vin: $scope.vehicle.vin })
                .then(function(response) {
                    $scope.vinValid = response.data.valid;
					if (response.data.valid) {
                        $scope.origin = response.data.country;
                    }
                }).catch(function() {
                    $scope.vinValid = false;
                });
        };

        $scope.updateClassification = function() {
            $scope.classification = null;
            $scope.classificationError = null;

            if (!$scope.vehicle.fuel_type || !$scope.vehicle.weight_empty) return;
            
            $http.post('/api/classify-vehicle', $scope.vehicle)
                .then(function(response) {
                    if (response.data.error) {
                        $scope.classificationError = response.data.message;
                        $rootScope.showNotification(response.data.message, 'error');
                        return;
                    }

                    $scope.classification = response.data;
                    $scope.vehicle.commodity_code = response.data.commodity_code;
                    if (!response.data.needs_user_selection) {
                        $scope.vehicle.statistical_key = response.data.statistical_key;
                    }
                })
                .catch(function(error) {
                    const message = error.data?.message || 'Erreur réseau lors de la classification.';
                    $scope.classificationError = message; 
                    $rootScope.showNotification(message, 'error');
                });
        };

        $scope.reportClassificationError = function() {
            if ($scope.reporting) return;
            
            $scope.reporting = true;
            
            const payload = {
                vehicle: $scope.vehicle,
                classification_error: $scope.classificationError || 'Classification non trouvée (signalement manuel)',
                consignor_ide: $scope.parties.consignor.ide || null,
                user_lang: $scope.declaration.language,
                declaration_type: 'export'
            };

            $http.post('/api/report-classification-error', payload)
                .then(function(response) {
                    if (response.data.success) {
                        $rootScope.showNotification($rootScope.t('error_reported_success') + ' - Merci pour votre aide!', 'success');
                    } else {
                        $rootScope.showNotification(response.data.message || $rootScope.t('error_reporting_failed'), 'error');
                    }
                })
                .catch(function(error) {
                    $rootScope.showNotification($rootScope.t('error_reporting_network') + ': ' + (error.data?.message || 'Erreur réseau'), 'error');
                })
                .finally(() => {
                    $scope.reporting = false;
                });
        };

		$scope.nextStep = function() {
			if ($scope.classificationError) {
				$rootScope.showNotification($rootScope.t('classification_error_block'), 'error');
				return;
			}

			if ($scope.step === 2) {
				const hasErrors = $scope.highlightInvalidFields('vehicleForm');
				
				if (hasErrors || !$scope.vehicle.vin || !$scope.vehicle.brand || !$scope.vehicle.model || 
					!$scope.vehicle.fuel_type || !$scope.vehicle.weight_empty || !$scope.vehicle.weight_total) {
					$rootScope.showNotification($rootScope.t('fill_required_vehicle'), 'error');
					return;
				}
			}
			
			$scope.step++;
			
			$timeout(function() {
				window.scrollTo({ top: 0, behavior: 'smooth' });
			}, 100);
		};

        $scope.prevStep = () => $scope.step--;

        $scope.showTooltip = function(tooltip, show) {
            $scope.tooltips[tooltip] = show;
        };

        $scope.toggleTooltip = function(tooltip) {
            $scope.tooltips[tooltip] = !$scope.tooltips[tooltip];
        };

        $scope.copyLinkToClipboard = function(link) {
            const tempInput = document.createElement('input');
            tempInput.style.position = 'absolute';
            tempInput.style.left = '-9999px';
            tempInput.value = 'myautoimport.ch' + link;

            document.body.appendChild(tempInput);
            tempInput.select();
            document.execCommand('copy');
            document.body.removeChild(tempInput);
            $rootScope.showNotification($rootScope.t('link_copied'), 'success');
        };

		$scope.prepareDeclaration = function() {
			if ($scope.preparing) return;

			const hasErrors = $scope.highlightInvalidFields('exportForm');
			
			const consignor = $scope.parties.consignor;
			if (hasErrors || !consignor.name || !consignor.zip || !consignor.city || !$scope.declaration.destination_country) {
				$rootScope.showNotification($rootScope.t('fill_required_export'), 'error');
				return;
			}

			if (!$scope.declaration.purchase_price || $scope.declaration.purchase_price <= 0) {
				$rootScope.showNotification($rootScope.t('fill_valid_price'), 'error');
				return;
			}
			
			if ($scope.declaration.purchase_price < 2000 && !$scope.declaration.price_confirmation) {
				$rootScope.showNotification($rootScope.t('confirm_low_price'), 'error');
				return;
			}

			$scope.preparing = true;

			const payload = {
				type: 'export',
				vehicle: $scope.vehicle,
				parties: $scope.parties,
				declaration: $scope.declaration,
				declarantType: $scope.declarantType
			};

			$http.post('/api/prepare-declaration', payload)
				.then(function(response) {
					if (response.data.success) {
						$scope.sessionToken = response.data.sessionToken;
						$scope.showStripeButton = true;
						saveState();
						loadStripeBuyButtonScript();
						$rootScope.showNotification('Déclaration prête ! Procédez au paiement.', 'success');
					} else {
						$rootScope.showNotification(response.data.message || 'Erreur de préparation', 'error');
					}
				})
				.catch(function(error) {
					$rootScope.showNotification('Erreur: ' + (error.data?.message || 'Erreur réseau'), 'error');
				})
				.finally(() => {
					$scope.preparing = false;
				});
		};
		
        $scope.listenForSubmissionStatus = function() {
            if (!$scope.sessionToken) return;
            
            if ($scope.eventSource) {
                $scope.eventSource.close();
            }
            
            $scope.step = 4;
            $scope.showProgress = true;
            
            const source = new EventSource('/api/submission-status-sse/' + $scope.sessionToken);
            $scope.eventSource = source;

            source.onmessage = function(event) {
                $scope.$apply(() => {
                    try {
                        const status = JSON.parse(event.data);
                        
                        $scope.submissionProgress = status.progress;
                        $scope.submissionStep = status.step;

                        if (status.status === 'submitted') {
                            $scope.submissionResult = status;
                            $scope.showProgress = false;
                            source.close();
                            sessionStorage.removeItem(SESSION_STORAGE_KEY);
                            $rootScope.showNotification($rootScope.t('submission_success'), 'success');
                        } else if (status.status === 'submission_error') {
                            $scope.showProgress = false;
                            source.close();
                            $rootScope.setErrorContext($scope.sessionToken);
                            $rootScope.showNotification($rootScope.t('submission_error_detected'), 'error');
                        }
                    } catch (e) {
                        console.error('[ExportController-SSE] Erreur:', e);
                    }
                });
            };
            
            source.onerror = function(error) {
                console.error('[ExportController-SSE] Erreur:', error);
                $scope.$apply(() => {
                    $scope.submissionStep = 'Erreur de connexion SSE...';
                });
            };
        };

        $scope.checkPaymentReturn = function() {
            const returnData = sessionStorage.getItem('stripe_payment_return');
            if (returnData) {
                try {
                    const data = JSON.parse(returnData);
                    if (data.sessionToken === $scope.sessionToken) {
                        sessionStorage.removeItem('stripe_payment_return');
                        $scope.listenForSubmissionStatus();
                    }
                } catch (e) {
                    console.error('Erreur parsing returnData:', e);
                }
            }
        };

        $scope.checkPaymentReturn();

        $scope.downloadPDF = function(path) {
            if (!path) return;
            $window.open('/api/download-pdf?path=' + encodeURIComponent(path), '_blank');
        };

        $scope.resetForm = function() {
            if ($scope.eventSource) $scope.eventSource.close();
            sessionStorage.removeItem(SESSION_STORAGE_KEY);
            initScope();
            $rootScope.showNotification($rootScope.t('form_reset'), 'info');
        };
    });