define([
    'uiComponent',
    'ko',
    'Magento_Checkout/js/model/quote',
    'Magento_Checkout/js/checkout-data'
], function (Component, ko, quote, checkoutData) {
    'use strict';

    return Component.extend({
        defaults: {
            template: 'PortalPeople_GetAddressAutocomplete/address-autocomplete'
        },

        searchTerm: ko.observable(''),
        addresses: ko.observableArray([]),
        selectedAddress: ko.observable(null),
        isLoading: ko.observable(false),
        errorMessage: ko.observable(''),
        showAddressList: ko.observable(false),
        isEnabled: ko.observable(false),

        initialize: function () {
            this._super();

            console.log('========================================');
            console.log('Address Autocomplete Component: Initializing...');
            console.log('window.checkoutConfig exists:', !!window.checkoutConfig);
            
            if (window.checkoutConfig) {
                console.log('checkoutConfig keys:', Object.keys(window.checkoutConfig));
                console.log('getaddress_autocomplete config:', window.checkoutConfig.getaddress_autocomplete);
            }
            
            // Use fallback global config if checkoutConfig does not include our section
            if (window.checkoutConfig &&
                !window.checkoutConfig.getaddress_autocomplete &&
                window.getAddressAutocompleteConfig) {
                window.checkoutConfig.getaddress_autocomplete = window.getAddressAutocompleteConfig;
            }

            // Check if module is enabled via window checkout config
            // This is populated by ConfigProvider or injected config block
            if (window.checkoutConfig && 
                window.checkoutConfig.getaddress_autocomplete &&
                window.checkoutConfig.getaddress_autocomplete.enabled) {
                this.isEnabled(true);
                console.log('✓ Address Autocomplete Component Loaded and ENABLED');
                console.log('  - Full Config:', window.checkoutConfig.getaddress_autocomplete);
            } else {
                this.isEnabled(false);
                console.log('✗ Address Autocomplete Component DISABLED');
                if (!window.checkoutConfig) {
                    console.log('  - Reason: window.checkoutConfig not found');
                } else if (!window.checkoutConfig.getaddress_autocomplete) {
                    console.log('  - Reason: getaddress_autocomplete config section not found');
                    console.log('  - Available keys:', Object.keys(window.checkoutConfig).join(', '));
                } else {
                    console.log('  - Reason: Module not enabled or API key not configured');
                    console.log('  - Config:', window.checkoutConfig.getaddress_autocomplete);
                    console.log('  - enabled flag:', window.checkoutConfig.getaddress_autocomplete.enabled);
                    console.log('  - has_api_key:', window.checkoutConfig.getaddress_autocomplete.has_api_key);
                    console.log('  - is_enabled_flag:', window.checkoutConfig.getaddress_autocomplete.is_enabled_flag);
                }
            }
            console.log('========================================');

            return this;
        },

        visible: function () {
            return this.isEnabled();
        },

        searchAddresses: function () {
            var self = this;
            var term = this.searchTerm().trim();

            if (term.length < 2) {
                this.addresses([]);
                this.showAddressList(false);
                return;
            }

            this.isLoading(true);
            this.errorMessage('');

            // Test data for demonstration
            var testData = [
                { 
                    address: '10 Downing Street, London', 
                    postcode: 'SW1A 2AA', 
                    Label: '10 DOWNING STREET, LONDON SW1A 2AA',
                    AddressId: 1 
                },
                { 
                    address: '100 Parliament Street, London', 
                    postcode: 'SW1A 2AA', 
                    Label: '100 PARLIAMENT STREET, LONDON SW1A 2AA',
                    AddressId: 2 
                },
                { 
                    address: 'Westminster Abbey, London', 
                    postcode: 'SW1P 3PA', 
                    Label: 'WESTMINSTER ABBEY, LONDON SW1P 3PA',
                    AddressId: 3 
                }
            ];

            // Filter based on search term
            var filtered = testData.filter(function(addr) {
                return addr.address.toLowerCase().includes(term.toLowerCase()) || 
                       addr.postcode.toLowerCase().includes(term.toLowerCase());
            });

            // Simulate API call delay
            setTimeout(function() {
                self.isLoading(false);
                
                if (filtered.length > 0) {
                    self.addresses(filtered);
                    self.showAddressList(true);
                } else {
                    self.errorMessage('No addresses found for "' + term + '". Try another search.');
                }
            }, 500);
        },

        selectAddress: function (address) {
            this.selectedAddress(address);
            this.showAddressList(false);
            this.populateAddress(address);
        },

        populateAddress: function (address) {
            var shippingAddress = quote.shippingAddress();

            if (shippingAddress) {
                // Parse address and populate fields
                var addressParts = address.address ? address.address.split(', ') : [];
                
                shippingAddress.street = addressParts.length > 0 ? [addressParts[0]] : [''];
                shippingAddress.city = addressParts[addressParts.length - 1] || '';
                shippingAddress.postcode = address.postcode || '';
                shippingAddress.countryId = 'GB';
                shippingAddress.region = '';
                
                quote.shippingAddress(shippingAddress);
                console.log('Address populated:', address);
            }
        },

        clearSelection: function () {
            this.searchTerm('');
            this.selectedAddress(null);
            this.addresses([]);
            this.showAddressList(false);
            this.errorMessage('');
        }
    });
});
