//
//  XXGAppInfoViewController.m
//  XXGPlayKit
//
//  Created by apple on 2025/4/29.
//

#import "XXGAppInfoViewController.h"
#import "XXGPlayKitConfig.h"
#import "NSObject+XXGModel.h"
#import "UIColor+XXGColor.h"
#import "XXGToast.h"

@interface XXGAppInfoViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray<NSDictionary *> *additionalSections; // 新增 Section 数据
@property (nonatomic, strong) NSArray<NSArray<NSString *> *> *additionalKeys; // 每个新增 Section 的 Key
@property (nonatomic, strong) NSMutableArray<NSString *> *sectionTitles; // Section 标题

@end

@implementation XXGAppInfoViewController

#pragma mark - Lifecycle
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 初始化数据
    _additionalSections = [NSMutableArray array];
    _additionalKeys = @[];
    _sectionTitles = [NSMutableArray array];
    
    [self setupTableView];
}

- (void)viewWillAppear:(BOOL)animated {
    
    UIEdgeInsets safeInsets = [[XXGWindowManager shared] xxpk_currentWindow].safeAreaInsets;
    
    safeInsets.top    += 10;
    safeInsets.left   += 10;
    safeInsets.bottom += 10;
    safeInsets.right  += 10;

    [self.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(safeInsets);
    }];
}

#pragma mark - UI Setup
- (void)setupTableView {
    _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    _tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.xxpk_backButton.mas_bottom);
        make.left.right.bottom.equalTo(self.view);
    }];
    
    // 使用自定义单元格样式
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:NSStringFromClass(self.class)];
}

#pragma mark - Data Management
- (NSArray<NSString *> *)sortedKeysFromDictionary:(NSDictionary *)dict {
    return [[dict allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
}

- (void)addAdditionalInfo:(NSDictionary *)info withTitle:(NSString *)title {
    if (!info || ![info isKindOfClass:[NSDictionary class]]) {
        return;
    }
    
    // 确保在主线程上执行所有UI和数据更新
    dispatch_async(dispatch_get_main_queue(), ^{
        @synchronized (self) {
            // 每个新增字典作为独立 Section
            [self->_additionalSections addObject:[info copy]];
            NSArray *sortedKeys = [self sortedKeysFromDictionary:info];
            self->_additionalKeys = [self->_additionalKeys arrayByAddingObject:sortedKeys];
            [self->_sectionTitles addObject:title];
            
            // 确保在主线程上刷新表格
            [self.tableView reloadData];
        }
    });
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _additionalSections.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _additionalKeys[section].count;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return _sectionTitles[section];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(self.class) forIndexPath:indexPath];
    
    NSString *key;
    id value;
    NSInteger sectionIndex = indexPath.section;
    key = _additionalKeys[sectionIndex][indexPath.row];
    value = _additionalSections[sectionIndex][key];
    BOOL isNested = [value isKindOfClass:[NSDictionary class]] || [value isKindOfClass:[NSArray class]];
    cell.backgroundColor = [UIColor clearColor];
    
    // 清除之前可能存在的子视图
    for (UIView *subview in cell.contentView.subviews) {
        [subview removeFromSuperview];
    }
    
    // 创建左侧 key 标签
    UILabel *keyLabel = [[UILabel alloc] init];
    keyLabel.font = [UIFont monospacedSystemFontOfSize:14 weight:UIFontWeightMedium];
    keyLabel.textColor = [UIColor darkGrayColor];
    keyLabel.text = key;
    keyLabel.numberOfLines = 0;
    [cell.contentView addSubview:keyLabel];
    
    // 创建右侧 value 标签
    UILabel *valueLabel = [[UILabel alloc] init];
    valueLabel.font = [UIFont monospacedSystemFontOfSize:14 weight:UIFontWeightRegular];
    valueLabel.textColor = [UIColor blackColor];
    valueLabel.numberOfLines = 0;
    valueLabel.textAlignment = NSTextAlignmentRight;
    [cell.contentView addSubview:valueLabel];
    
    // 使用 Masonry 设置约束
    [keyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(cell.contentView).offset(XXGUIDriver.xxpk_data_ui.xxpk_float15);
        make.top.equalTo(cell.contentView).offset(XXGUIDriver.xxpk_data_ui.xxpk_float10);
        make.bottom.equalTo(cell.contentView).offset(-XXGUIDriver.xxpk_data_ui.xxpk_float10);
        make.width.equalTo(cell.contentView.mas_width).multipliedBy(isNested?XXGUIDriver.xxpk_data_ui.xxpk_float09:XXGUIDriver.xxpk_data_ui.xxpk_float045);
    }];
    
    [valueLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(cell.contentView).offset(-XXGUIDriver.xxpk_data_ui.xxpk_float15);
        make.top.equalTo(cell.contentView).offset(XXGUIDriver.xxpk_data_ui.xxpk_float10);
        make.bottom.equalTo(cell.contentView).offset(-XXGUIDriver.xxpk_data_ui.xxpk_float10);
        make.left.equalTo(keyLabel.mas_right).offset(XXGUIDriver.xxpk_data_ui.xxpk_float10);
    }];
    
    // 处理嵌套字典或数组
    if (isNested) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    } else {
        valueLabel.text = [value description];
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    return cell;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    id value;
    NSString *key;
    
    NSInteger sectionIndex = indexPath.section;
    key = _additionalKeys[sectionIndex][indexPath.row];
    value = _additionalSections[sectionIndex][key];
    
    // 如果是嵌套字典或数组，显示详细内容
    if ([value isKindOfClass:[NSDictionary class]]) {
        [self showNestedDictionary:value withTitle:key];
    } else if ([value isKindOfClass:[NSArray class]]) {
        [self showNestedArray:value withTitle:key];
    } else {
        // 复制内容到剪贴板
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        [pasteboard setString:[value description]];
        [XXGToast showTop:XXGUIDriver.xxpk_data_ui.xxpk_ui_appinfo_copytip];
    }
}

#pragma mark - 处理嵌套数据
- (void)showNestedDictionary:(NSDictionary *)dict withTitle:(NSString *)title {
    XXGAppInfoViewController *detailVC = [[XXGAppInfoViewController alloc] init];
    [self.navigationController pushViewController:detailVC animated:NO];
    [detailVC addAdditionalInfo:dict withTitle:title];
}

- (void)showNestedArray:(NSArray *)array withTitle:(NSString *)title {
    // 将数组转换为字典格式以便显示
    NSMutableDictionary *arrayDict = [NSMutableDictionary dictionary];
    for (NSInteger i = 0; i < array.count; i++) {
        arrayDict[[NSString stringWithFormat:@"[%ld]", (long)i]] = array[i];
    }
    
    XXGAppInfoViewController *detailVC = [[XXGAppInfoViewController alloc] init];
    [self.navigationController pushViewController:detailVC animated:NO];
    [detailVC addAdditionalInfo:arrayDict withTitle:[NSString stringWithFormat:@"%@ (Array)", title]];
}

@end
