//
//  XXGCountryCodeSelectorViewController.m
//  XXGPlayKit
//
//  Created by apple on 2025/3/16.
//

#import "XXGCountryCodeSelectorViewController.h"
#import "XXGUIDriver.h"

@interface XXGCountryCodeSelectorViewController () <UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate>
@property (nonatomic, strong) UITableView *xxpk_tableView;
@property (nonatomic, strong) UISearchBar *xxpk_searchBar;
@property (nonatomic, strong) NSArray<XXGCountry *> *xxpk_allCountries;     // 完整数据源
@property (nonatomic, strong) NSArray<XXGCountry *> *xxpk_filteredCountries; // 搜索结果数据源
@end

@implementation XXGCountryCodeSelectorViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self xxpk_loadCountryData];
    [self xxpk_setupViews];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    [self.view endEditing:YES];
}

#pragma mark - 数据加载

- (void)xxpk_loadCountryData {
    NSArray *countries = [XXGLocaleString xxpk_loadCountries:[XXGCountry class]];
    
    // 按国家名称排序
    self.xxpk_allCountries = [countries sortedArrayUsingComparator:^NSComparisonResult(XXGCountry *c1, XXGCountry *c2) {
        return [c1.xxpk_name compare:c2.xxpk_name options:NSCaseInsensitiveSearch];
    }];
    
    self.xxpk_filteredCountries = self.xxpk_allCountries;
    
    // 获取当前地区代码
    NSString *currentCountryCode = [[NSLocale currentLocale] objectForKey:NSLocaleCountryCode];
    
    // 查找匹配的国家及其索引
    __block XXGCountry *matchedCountry = nil;
    __block NSUInteger matchedIndex = NSNotFound;
    [self.xxpk_allCountries enumerateObjectsUsingBlock:^(XXGCountry *country, NSUInteger idx, BOOL *stop) {
        if ([country.xxpk_countryCode caseInsensitiveCompare:currentCountryCode] == NSOrderedSame) {
            matchedCountry = country;
            matchedIndex = idx;
            *stop = YES; // 找到第一个匹配项后停止遍历
        }
    }];
    
    // 如果找到匹配项，移动到数组首位
    if (matchedCountry) {
        NSLog(@"默认国家: %@, 区号: %@", matchedCountry.xxpk_name, matchedCountry.xxpk_dialCode);
        
        // 创建可变数组并调整顺序
        NSMutableArray *mutableCountries = [self.xxpk_allCountries mutableCopy];
        [mutableCountries removeObjectAtIndex:matchedIndex];    // 移除原位置
        [mutableCountries insertObject:matchedCountry atIndex:0]; // 插入到首位
        
        // 更新数组
        self.xxpk_allCountries = [mutableCountries copy];
        self.xxpk_filteredCountries = self.xxpk_allCountries; // 同步更新过滤后的数组
    }
}

#pragma mark - UI Setup

- (void)xxpk_setupViews {
    self.view.clipsToBounds = YES;
    
    // 搜索栏
    self.xxpk_searchBar = [[UISearchBar alloc] init];
    self.xxpk_searchBar.delegate = self;
    self.xxpk_searchBar.placeholder = XXGUIDriver.xxpk_string_ui.xxpk_country_searchBar_placeholder;
    self.xxpk_searchBar.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.xxpk_searchBar];
    
    // 表格视图
    self.xxpk_tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.xxpk_tableView.delegate = self;
    self.xxpk_tableView.dataSource = self;
    self.xxpk_tableView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.xxpk_tableView];
    
    // Auto Layout 布局
    UILayoutGuide *guide = self.view.safeAreaLayoutGuide;
    UILayoutGuide *guide1 = self.xxpk_backButton.safeAreaLayoutGuide;
    UILayoutGuide *guide2 = self.xxpk_closeButton.safeAreaLayoutGuide;
    [NSLayoutConstraint activateConstraints:@[
        [self.xxpk_searchBar.topAnchor constraintEqualToAnchor:guide.topAnchor],
        [self.xxpk_searchBar.leadingAnchor constraintEqualToAnchor:guide1.trailingAnchor],
        [self.xxpk_searchBar.trailingAnchor constraintEqualToAnchor:guide2.leadingAnchor],
        
        [self.xxpk_tableView.topAnchor constraintEqualToAnchor:self.xxpk_searchBar.bottomAnchor],
        [self.xxpk_tableView.leadingAnchor constraintEqualToAnchor:guide.leadingAnchor],
        [self.xxpk_tableView.trailingAnchor constraintEqualToAnchor:guide.trailingAnchor],
        [self.xxpk_tableView.bottomAnchor constraintEqualToAnchor:guide.bottomAnchor]
    ]];
}

- (void)xxpk_cancelAction {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - UITableView DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.xxpk_filteredCountries.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(self.class)];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:NSStringFromClass(self.class)];
    }
    XXGCountry *country = self.xxpk_filteredCountries[indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"%@ %@", [self __xxpk_emojiFlagForISOCountryCode:country.xxpk_countryCode],country.xxpk_name];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ %@",XXGUIDriver.xxpk_data_ui.xxpk_code_jia,country.xxpk_dialCode];
    return cell;
}

#pragma mark - UITableView Delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    XXGCountry *selectedCountry = self.xxpk_filteredCountries[indexPath.row];
    if ([self.xxpk_codeDelegate respondsToSelector:@selector(xxpk_countryCodeSelectorDidSelectCountry:)]) {
        [self.xxpk_codeDelegate xxpk_countryCodeSelectorDidSelectCountry:selectedCountry];
    }
    [self xxpk_backButtonAction:nil];
}

#pragma mark - UISearchBar Delegate
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    if (searchText.length == 0) {
        self.xxpk_filteredCountries = self.xxpk_allCountries;
    } else {
        NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(XXGCountry *evaluatedObject, NSDictionary *bindings) {
            BOOL a1 = [evaluatedObject.xxpk_name rangeOfString:searchText options:NSCaseInsensitiveSearch].location != NSNotFound;
            BOOL a2 = [evaluatedObject.xxpk_dialCode rangeOfString:searchText options:NSCaseInsensitiveSearch].location != NSNotFound;
            return a1 || a2;
        }];
        self.xxpk_filteredCountries = [self.xxpk_allCountries filteredArrayUsingPredicate:predicate];
    }
    [self.xxpk_tableView reloadData];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [self.view endEditing:YES];
}

- (NSString *)__xxpk_emojiFlagForISOCountryCode:(NSString *)countryCode {
    
    if(![countryCode isKindOfClass:[NSString class]] || countryCode.length != 2 || [countryCode isEqualToString:@"TW"]) return @"";
    int base = 127397;
    
    wchar_t bytes[2] = {
        base +[countryCode characterAtIndex:0],
        base +[countryCode characterAtIndex:1]
    };
    
    return [[NSString alloc] initWithBytes:bytes
                                    length:countryCode.length *sizeof(wchar_t)
                                  encoding:NSUTF32LittleEndianStringEncoding];
}

- (void)dealloc {
    NSLog(@"%s", __func__);
}
@end
