//
//  KBSkinCenterVC.m
//

#import "KBSkinCenterVC.h"
#import "Masonry.h"
#import "KBNetworkManager.h"
#import "KBSkinManager.h"
#import "KBHUD.h"

@interface KBSkinCell : UITableViewCell
@property (nonatomic, strong) UIButton *applyBtn;
@end

@implementation KBSkinCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        _applyBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        [_applyBtn setTitle:@"下载并应用" forState:UIControlStateNormal];
        _applyBtn.layer.cornerRadius = 6; _applyBtn.layer.borderWidth = 1;
        _applyBtn.layer.borderColor = [UIColor colorWithWhite:0.85 alpha:1].CGColor;
        [self.contentView addSubview:_applyBtn];
        [_applyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self.contentView).offset(-16);
            make.centerY.equalTo(self.contentView);
            make.width.mas_equalTo(110);
            make.height.mas_equalTo(34);
        }];
    }
    return self;
}
@end

@interface KBSkinCenterVC () <UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, copy) NSArray<NSDictionary *> *skins; // id, name, img(url relative to KB_BASE_URL)
@end

@implementation KBSkinCenterVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"皮肤中心";
    self.view.backgroundColor = [UIColor whiteColor];
    // 绝对 URL 的测试皮肤图片（无需 KB_BASE_URL）。
    // 说明：使用 picsum.photos 的固定 id，稳定可直接访问。
    self.skins = @[
        @{ @"id": @"aurora", @"name": @"极光",   @"img": @"https://picsum.photos/id/1018/1600/900.jpg" },
        @{ @"id": @"alps",   @"name": @"雪山",   @"img": @"https://picsum.photos/id/1016/1600/900.jpg" },
        @{ @"id": @"lake",   @"name": @"湖面",   @"img": @"https://picsum.photos/id/1039/1600/900.jpg" },
    ];

    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleInsetGrouped];
    self.tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.tableView.delegate = self; self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
}

#pragma mark - UITableView

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; }
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.skins.count; }

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cid = @"skin.cell";
    KBSkinCell *cell = [tableView dequeueReusableCellWithIdentifier:cid];
    if (!cell) { cell = [[KBSkinCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cid]; }
    NSDictionary *skin = self.skins[indexPath.row];
    cell.textLabel.text = skin[@"name"]; cell.detailTextLabel.text = skin[@"id"];
    [cell.applyBtn removeTarget:nil action:NULL forControlEvents:UIControlEventTouchUpInside];
    [cell.applyBtn addTarget:self action:@selector(onApplyBtn:) forControlEvents:UIControlEventTouchUpInside];
    cell.applyBtn.tag = indexPath.row;
    return cell;
}

- (void)onApplyBtn:(UIButton *)sender {
    NSInteger idx = sender.tag;
    if (idx < 0 || idx >= self.skins.count) return;
    NSDictionary *skin = self.skins[idx];
    NSString *path = skin[@"img"] ?: @""; // 相对 KB_BASE_URL

    // 下载图片数据（非 JSON 将以 NSData 返回）
    [[KBNetworkManager shared] GET:path parameters:nil headers:nil completion:^(id jsonOrData, NSURLResponse *response, NSError *error) {
        NSData *data = ([jsonOrData isKindOfClass:NSData.class] ? (NSData *)jsonOrData : nil);
        // 尝试压缩尺寸，避免 Keychain 过大：将宽度限制到 1500px
        if (data && data.length > 0) {
            UIImage *img = [UIImage imageWithData:data];
            if (img) {
                CGFloat maxW = 1500.0;
                if (img.size.width > maxW) {
                    CGFloat scale = maxW / img.size.width;
                    CGSize newSize = CGSizeMake(maxW, floor(img.size.height * scale));
                    UIGraphicsBeginImageContextWithOptions(newSize, YES, 1.0);
                    [img drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
                    UIImage *resized = UIGraphicsGetImageFromCurrentImageContext();
                    UIGraphicsEndImageContext();
                    img = resized ?: img;
                }
                data = UIImageJPEGRepresentation(img, 0.85) ?: data; // 压成 JPEG
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            NSData *payload = data;
            if (payload.length == 0) {
                // 兜底：生成一张简单渐变图片
                CGSize size = CGSizeMake(1200, 600);
                UIGraphicsBeginImageContextWithOptions(size, YES, 1.0);
                CGContextRef ctx = UIGraphicsGetCurrentContext();
                UIColor *c1 = [UIColor colorWithRed:0.76 green:0.91 blue:0.86 alpha:1];
                UIColor *c2 = [UIColor colorWithRed:0.93 green:0.97 blue:0.91 alpha:1];
                if ([skin[@"id"] hasPrefix:@"dark"]) {
                    c1 = [UIColor colorWithRed:0.1 green:0.12 blue:0.16 alpha:1];
                    c2 = [UIColor colorWithRed:0.22 green:0.24 blue:0.28 alpha:1];
                }
                CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
                NSArray *colors = @[(__bridge id)c1.CGColor, (__bridge id)c2.CGColor];
                CGFloat locs[] = {0,1};
                CGGradientRef grad = CGGradientCreateWithColors(space, (__bridge CFArrayRef)colors, locs);
                CGContextDrawLinearGradient(ctx, grad, CGPointZero, CGPointMake(size.width, size.height), 0);
                CGGradientRelease(grad); CGColorSpaceRelease(space);
                UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
                UIGraphicsEndImageContext();
                payload = UIImageJPEGRepresentation(img, 0.9);
            }
            BOOL ok = (payload.length > 0) ? [[KBSkinManager shared] applyImageSkinWithData:payload skinId:skin[@"id"] name:skin[@"name"]] : NO;
            [KBHUD showInfo:(ok ? @"已应用，切到键盘查看" : @"应用失败")];
        });
    }];
}

@end
