angular.module('edecApp')
    .controller('ImportController', function($scope, $http, $window) {
        $scope.step = 1;
        $scope.method = null;
        $scope.vehicle = {};
        $scope.declaration = {
            transport_mode: '9',
            purchase_currency: 'EUR',
            transport_cost: 0,
            other_costs: 0
        };
        $scope.vinValidation = {};
        $scope.classification = null;
        $scope.countries = {};
        $scope.currencies = {};
        $scope.ocrLoading = false;
        $scope.generating = false;
        $scope.totalCHF = 0;
        $scope.exchangeRate = 1;

        // Charger les données de configuration
        $http.get('/api/countries').then(res => $scope.countries = res.data);
        $http.get('/api/currencies').then(res => $scope.currencies = res.data);
        $http.get('/api/exchange-rates').then(res => {
            $scope.exchangeRates = res.data;
        });

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

        $scope.triggerFileInput = function() {
            document.getElementById('file-input').click();
        };

        $scope.handleFileSelect = function(input) {
            const file = input.files[0];
            if (!file) return;

            $scope.ocrLoading = true;
            const formData = new FormData();
            formData.append('registration_card', file);

            $http.post('/api/ocr', formData, {
                transformRequest: angular.identity,
                headers: {'Content-Type': undefined}
            }).then(response => {
                Object.assign($scope.vehicle, response.data);
                $scope.ocrLoading = false;
                $scope.updateClassification();
            }).catch(error => {
                alert('Erreur OCR: ' + (error.data?.error || 'Erreur inconnue'));
                $scope.ocrLoading = false;
            });
        };

        $scope.validateVIN = function() {
            if (!$scope.vehicle.vin || $scope.vehicle.vin.length !== 17) {
                $scope.vinValidation = { invalid: true };
                return;
            }

            $http.post('/api/validate-vin', { vin: $scope.vehicle.vin })
                .then(response => {
                    $scope.vinValidation = response.data;
                    if (response.data.country) {
                        $scope.declaration.dispatch_country = response.data.country;
                    }
                });
        };

        $scope.updateClassification = function() {
            if (!$scope.vehicle.fuel_type || !$scope.vehicle.weight_empty) return;

            $http.post('/api/classify-vehicle', $scope.vehicle)
                .then(response => {
                    $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;
                    }
                });
        };

        $scope.calculateTotal = function() {
            const price = parseFloat($scope.declaration.purchase_price) || 0;
            const transport = parseFloat($scope.declaration.transport_cost) || 0;
            const other = parseFloat($scope.declaration.other_costs) || 0;
            const currency = $scope.declaration.purchase_currency;

            $http.post('/api/convert-currency', {
                amount: price + transport + other,
                from: currency,
                to: 'CHF'
            }).then(response => {
                $scope.totalCHF = response.data.converted;
                $scope.exchangeRate = $scope.exchangeRates[currency]?.rate || 1;
            });
        };

        $scope.nextStep = function() {
            $scope.step++;
        };

        $scope.generateDeclaration = function() {
            $scope.generating = true;

            const data = {
                ...$scope.vehicle,
                ...$scope.declaration,
                language: 'fr'
            };

            $http.post('/api/generate-import', data, {
                responseType: 'blob'
            }).then(response => {
                const blob = new Blob([response.data], { type: 'application/xml' });
                const url = $window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `edec-import-${Date.now()}.xml`;
                a.click();
                $window.URL.revokeObjectURL(url);

                $scope.step = 4;
                $scope.generating = false;
            }).catch(error => {
                alert('Erreur: ' + (error.data?.error || 'Erreur de génération'));
                $scope.generating = false;
            });
        };

        $scope.resetForm = function() {
            $scope.step = 1;
            $scope.vehicle = {};
            $scope.declaration = {
                transport_mode: '9',
                purchase_currency: 'EUR',
                transport_cost: 0,
                other_costs: 0
            };
            $scope.classification = null;
        };
    });
