'use strict';
angular.module('create-team', [])

    .controller('CreateTeamCtrl', ['$scope', 'AppUtil', 'APIName', '$http', 'APIStatus', 'app', '$state', 'util',
        'session', '$stateParams', 'userConfig', 'exchangeRate', '$window', 'configServer', '$',
        function ($scope, AppUtil, APIName, $http, APIStatus, app, $state, util,
                  session, $stateParams, userConfig, exchangeRate, $window, configServer, $) {
            $scope.script_pattern = app.SCRIPT_PATTERN;

            $scope.currentLang = session.getCurrentLanguage();
            $scope.currencies = [
                {id: 1, value: "USD"},
                {id: 2, value: "YEN"}
            ];
            $scope.billingCycles = [
                {id: 1, value: "MONTHLY"},
                {id: 2, value: "ANNUALLY"}
            ];
            $scope.featureType = [
                {type: 'upload', name: util.translate('label.team.drm')},
                {type: 'non-drm', name: util.translate('label.team.non_drm')}
            ];

            $scope.newTeam = {
                firstName: "",
                lastName: "",
                mailAddress: "",
                password: "",
                confirmPassword: "",
                teamName: "",
                isUseSecureDrive: false,
                isUseSecureMail: false,
                featureSetting: $scope.featureType[0],
                numberTransmission: null,
                isTrial: false,
                currency: null,
                business_size: '1-50 employees',
                phone_number: '0',
                time_zone: 0,
                use_google_translate: true
            };

            $scope.pattern = app.EMAIL_PATTERN;
            $scope.currentUser = session.getUser();
            $scope.isJapaneseLang = session.isJapanese();
            $scope.totalPrice = 0;
            $scope.doBack = function () {
                $window.history.back();
            };
            var params = {};
            if ($scope.currentUser.role_id === userConfig.SUPER_ADMIN.role) {
                params = {
                    company_id: $stateParams.id
                }
            }

            // Filter options for pricing package

            $scope.consoleTypes = [
                {id: 1, value: "SECURE_DRIVE"},
                {id: 2, value: "SECURE_MAIL"}
            ];
            
            //$scope.selectedBillingCycle = $scope.billingCycles[0];

            $scope.selectedBillingCycle = null;
            $scope.selectedConsoleType = null;


            $scope.pricingPackages = [];
            $scope.selectedPricingPackage = null;
            
            $scope.formInitialized = false;
            $scope.packagesLoaded = false;

            $scope.filteredPricingPackages = [];

            $scope.$watch('newTeam.currency', function(newVal, oldVal) {
                if (newVal && newVal.value) {
                    $scope.filteredPricingPackages = $scope.pricingPackages.filter(function(pkg) {
                        return pkg.currency === newVal.value;
                    });
                } else {
                    $scope.filteredPricingPackages = $scope.pricingPackages;
                }

                $scope.selectedPricingPackage = null;
            });

            function getPackageField(pkg, fieldType) {
                if (!pkg) return null;
                switch (fieldType) {
                    case 'billingCycle':
                        return pkg.billing_cycle;
                    case 'consoleType':
                        return pkg.type;
                    case 'currency':
                        return pkg.currency;
                    default:
                        return null;
                }
            }

            function normalize(val) {
                if (val && typeof val === 'object' && val.value !== undefined) {
                    val = val.value;
                }
                return (val || '').toString().trim().toUpperCase().replace(/\s+/g, '_');
            }

            $scope.loadPricingPackages = function() {
                var params = {
                    asc_sort: true,
                    page_number: 1,
                    page_size: 100,
                    sort_field: 'createdTime',
                    statuses: 'ACTIVE'
                };
                
                AppUtil.createRequest({method: 'GET', name: 'api/pricing/package'}, params, function(res) {
                    try {
                        if (res.data && res.data.content && Array.isArray(res.data.content)) {
                            $scope.pricingPackages = res.data.content;
                            $scope.packagesLoaded = true;
                            console.log('Loaded pricing packages:', $scope.pricingPackages.length);
                            console.log('List pricingPackages:', $scope.pricingPackages);
                            
                            if ($scope.formInitialized) {
                                setTimeout(function() {
                                    $scope.$apply(function() {
                                        $scope.filterPricingPackages();
                                    });
                                }, 100);
                            }
                        } else {
                            console.warn('No pricing packages found in response');
                            $scope.pricingPackages = [];
                            $scope.selectedPricingPackage = null;
                            $scope.packagesLoaded = true;
                        }
                    } catch (error) {
                        console.error('Error processing pricing packages response:', error);
                        $scope.pricingPackages = [];
                        $scope.selectedPricingPackage = null;
                        $scope.packagesLoaded = true;
                    }
                }, function(error) {
                    console.error('Failed to load pricing packages:', error);
                    $scope.pricingPackages = [];
                    $scope.selectedPricingPackage = null;
                    $scope.packagesLoaded = true;
                });
            };

            $scope.calculateTotalPrice = function() {
                if ($scope.selectedPricingPackage && $scope.selectedPricingPackage.price) {
                    var price = parseFloat($scope.selectedPricingPackage.price) || 0;
                    $scope.totalPrice = price.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
                } else {
                    $scope.totalPrice = '0.00';
                }
            };

            // Safe watch functions với proper checks
            $scope.$watch('selectedBillingCycle', function(newVal, oldVal) {
                if (normalize(newVal) !== normalize(oldVal) && $scope.formInitialized && $scope.packagesLoaded) {
                    console.log('Billing cycle changed from', (oldVal && oldVal.value), 'to', (newVal && newVal.value));
                    $scope.filterPricingPackages();
                }
            }, true);

            $scope.$watch('selectedConsoleType', function(newVal, oldVal) {
                if (normalize(newVal) !== normalize(oldVal) && $scope.formInitialized && $scope.packagesLoaded) {
                    console.log('Console type changed from', (oldVal && oldVal.value), 'to', (newVal && newVal.value));
                    $scope.filterPricingPackages();
                }
            }, true);

            $scope.$watch('selectedPricingPackage', function(newPkg, oldPkg) {
                if (newPkg) {
                    console.log('You have just selected a package:', newPkg.name, '| ID:', newPkg.id);
                } else {
                    console.log('No package selected yet');
                }
                $scope.calculateTotalPrice();
            });

            $scope.validatePricingSelection = function() {
                if (!$scope.selectedPricingPackage) {
                    AppUtil.showError({
                        text: util.translate("error.pricing_package.not_found") || "Please select a pricing package"
                    });
                    return false;
                }
                return true;
            };

            // Submit create team
            $scope.submit = false;
            $scope.createTeam = function(valid) {
                if (!valid) {
                    console.log('Form validation failed');
                    return;
                }
                console.log('Package selected when submitting:', $scope.selectedPricingPackage);
                if ($scope.selectedPricingPackage) {
                    console.log('Package ID:', $scope.selectedPricingPackage.id, '| Name:', $scope.selectedPricingPackage.name);
                }
                if (!$scope.validatePricingSelection()) {
                    return;
                }
                
                $scope.submit = true;
                
                var paramsCreate = {
                    company_id: $stateParams.id,
                    first_name: $scope.newTeam.firstName,
                    last_name: $scope.newTeam.lastName,
                    email_address: $scope.newTeam.mailAddress,
                    name: $scope.newTeam.teamName,
                    password_hash: AppUtil.MD5($scope.newTeam.password),
                    confirm_password: AppUtil.MD5($scope.newTeam.confirmPassword),
                    trial: $scope.newTeam.isTrial,
                    pricing_package_id: $scope.selectedPricingPackage.id,
                    use_secure_drive: $scope.newTeam.isUseSecureDrive,
                    use_secure_mail: $scope.newTeam.isUseSecureMail,
                    business_size: $scope.newTeam.business_size,
                    phone_number: $scope.newTeam.phone_number,
                    time_zone: $scope.newTeam.time_zone,
                    use_google_translate: $scope.newTeam.use_google_translate
                };
                
                if ($scope.newTeam.isUseSecureMail) {
                    paramsCreate.feature_setting = $scope.newTeam.featureSetting.type;
                    paramsCreate.transmission_point = $scope.newTeam.numberTransmission;
                }
                
                console.log('Creating team with params:', paramsCreate);
                
                AppUtil.createRequest(APIName.ADMIN_CREATE_TEAM, paramsCreate, function () {
                    AppUtil.createToast({
                        'text': util.translate('default_toast.create_success'),
                        'type': 'success'
                    });
                    if ($scope.currentUser.role_id === userConfig.SUPER_ADMIN.role) {
                        $state.go("companyProfile", {id: $stateParams.id});
                    } else {
                        $state.go("teamList");
                    }
                    $scope.submit = false;
                }, function (error) {
                    console.error('Error creating team:', error);
                    AppUtil.showError({
                        text: util.translate("sever_errors." + error.status)
                    });
                    $scope.submit = false;
                });
            };

            $scope.fileTemplatePath = (session.getCurrentLanguage() === 'ja') ? "data/CSVFile_Template_Import_Team_JA.csv" : "data/CSVFile_Template_Import_Team.csv";
            var param = {
                file_name: 'CSVFile_Template_Import_Team.csv', 
                require_auth: false
            };
            
            // Detect language to change order first name, last name
            if (session.getCurrentLanguage() === 'ja') {
                $('#ja-language-name').show();
                $('#en-language-name').hide();
                param.file_name = 'CSVFile_Template_Import_Team_JA.csv';
            } else {
                $('#ja-language-name').hide();
            }

            // Handle download file
            $scope.downloadCsv = function () {
                var url = 'api/download/files/csv/template' + '?' + $.param(param);
                $.fileDownload(url, {httpMethod: 'get'});
            };
            
            // Import users from csv file
            $scope.importCSVUrl = configServer.BACKEND_API_URL + APIName.CHECK_TEAM_FROM_CSV.name +
                "?auth_token=" + session.getToken() +
                "&company_id=" + (($scope.currentUser.role_id === userConfig.SUPER_ADMIN.role)
                    ? $stateParams.id : $scope.currentUser.company_id);
            
            $('#link_password').on('keypress', function (e) {
                if (e.which === 32) return false;
            });

            // IMPROVED INITIALIZATION: wait form really ready
            var initTimeout = setTimeout(function() {
                $scope.$apply(function() {
                    $scope.formInitialized = true;
                    console.log('Form initialized');
                    
                    $scope.newTeam.currency = '';
                    $scope.selectedConsoleType = '';
                    $scope.selectedBillingCycle = '';
                    $scope.filterPricingPackages();
                    $scope.loadPricingPackages();
                });
            }, 300);

            // Cleanup timeout when destroy scope
            $scope.$on('$destroy', function() {
                if (initTimeout) {
                    clearTimeout(initTimeout);
                }
            });

            $scope.filterPricingPackages = function() {
                var currency = $scope.newTeam.currency && $scope.newTeam.currency.value ? $scope.newTeam.currency.value : $scope.newTeam.currency;
                var billingCycle = $scope.selectedBillingCycle;
                var consoleType = $scope.selectedConsoleType;
                var hasFilter = currency || billingCycle || consoleType;
                if (!hasFilter) {
                    $scope.filteredPricingPackages = $scope.pricingPackages;
                } else {
                    $scope.filteredPricingPackages = $scope.pricingPackages.filter(function(pkg) {
                        var matchCurrency = currency ? pkg.currency === currency : true;
                        var matchType = consoleType ? pkg.type === consoleType : true;
                        var matchBilling = billingCycle ? pkg.billing_cycle === billingCycle : true;
                        return matchCurrency && matchType && matchBilling;
                    });
                }
                $scope.selectedPricingPackage = null;
            };
        }])

    // Create directive to watch list change
    .directive('planitemdirective', function () {
        return {
            restrict: 'A',
            link: function ($scope, element, attrs) {
                $scope.$watch(attrs.value, function (v) {
                    if (attrs.value === '20')
                        $scope.initDefaultPlan();
                });
            }
        };
    });