//
//  KBFunctionView.m
//  CustomKeyboard
//
//  Created by Mac on 2025/10/28.
//

#import "KBFunctionView.h"
#import "KBFunctionBarView.h"
#import "KBFunctionPasteView.h"
#import "KBFunctionTagCell.h"
#import "Masonry.h"

static NSString * const kKBFunctionTagCellId = @"KBFunctionTagCellId";

@interface KBFunctionView () <UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, KBFunctionBarViewDelegate>
// UI
@property (nonatomic, strong) KBFunctionBarView *barViewInternal;
@property (nonatomic, strong) KBFunctionPasteView *pasteViewInternal;
@property (nonatomic, strong) UICollectionView *collectionViewInternal;
@property (nonatomic, strong) UIView *rightButtonContainer; // 右侧竖排按钮容器
@property (nonatomic, strong) UIButton *pasteButtonInternal;
@property (nonatomic, strong) UIButton *deleteButtonInternal;
@property (nonatomic, strong) UIButton *clearButtonInternal;
@property (nonatomic, strong) UIButton *sendButtonInternal;

// Data
@property (nonatomic, strong) NSArray<NSString *> *itemsInternal;
@end

@implementation KBFunctionView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        // 整体绿色背景（接近截图效果，项目可自行替换素材）
        self.backgroundColor = [UIColor colorWithRed:0.77 green:0.93 blue:0.82 alpha:1.0];

        [self setupUI];
        [self reloadDemoData];
    }
    return self;
}

#pragma mark - UI

- (void)setupUI {
    // 1. 顶部 Bar
    [self addSubview:self.barViewInternal];
    [self.barViewInternal mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self);
        make.top.equalTo(self.mas_top).offset(6);
        make.height.mas_equalTo(48);
    }];

    // 右侧竖排按钮容器
    [self addSubview:self.rightButtonContainer];
    [self.rightButtonContainer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.mas_right).offset(-12);
        make.top.equalTo(self.barViewInternal.mas_bottom).offset(8);
        make.bottom.equalTo(self.mas_bottom).offset(-10);
        make.width.mas_equalTo(72);
    }];

    // 右侧四个按钮
    [self.rightButtonContainer addSubview:self.pasteButtonInternal];
    [self.rightButtonContainer addSubview:self.deleteButtonInternal];
    [self.rightButtonContainer addSubview:self.clearButtonInternal];
    [self.rightButtonContainer addSubview:self.sendButtonInternal];

    // 竖向排布：粘贴、删除、清空为等高，发送略高
    CGFloat smallH = 44;
    CGFloat bigH = 56;
    CGFloat vSpace = 10;
    [self.pasteButtonInternal mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.rightButtonContainer.mas_top);
        make.left.right.equalTo(self.rightButtonContainer);
        make.height.mas_equalTo(smallH);
    }];
    [self.deleteButtonInternal mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.pasteButtonInternal.mas_bottom).offset(vSpace);
        make.left.right.equalTo(self.rightButtonContainer);
        make.height.equalTo(self.pasteButtonInternal);
    }];
    [self.clearButtonInternal mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.deleteButtonInternal.mas_bottom).offset(vSpace);
        make.left.right.equalTo(self.rightButtonContainer);
        make.height.equalTo(self.pasteButtonInternal);
    }];
    [self.sendButtonInternal mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.clearButtonInternal.mas_bottom).offset(vSpace);
        make.left.right.equalTo(self.rightButtonContainer);
        make.height.mas_equalTo(bigH);
        make.bottom.lessThanOrEqualTo(self.rightButtonContainer.mas_bottom); // 底部可伸缩
    }];

    // 2. 粘贴区（位于右侧按钮左侧）
    [self addSubview:self.pasteViewInternal];
    [self.pasteViewInternal mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.mas_left).offset(12);
        make.right.equalTo(self.rightButtonContainer.mas_left).offset(-12);
        make.top.equalTo(self.barViewInternal.mas_bottom).offset(8);
        make.height.mas_equalTo(48);
    }];

    // 3. CollectionView
    [self addSubview:self.collectionViewInternal];
    [self.collectionViewInternal mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.mas_left).offset(12);
        make.right.equalTo(self.rightButtonContainer.mas_left).offset(-12);
        make.top.equalTo(self.pasteViewInternal.mas_bottom).offset(10);
        make.bottom.equalTo(self.mas_bottom).offset(-10);
    }];
}

#pragma mark - Data

- (void)reloadDemoData {
    // 演示数据（可由外部替换）
    self.itemsInternal = @[@"高情商", @"暖味拉扯", @"风趣幽默", @"撩女生", @"社交惬匿", @"情场高手", @"一枚暖男", @"聊天搭子", @"表达爱意", @"更多话术"];    
    [self.collectionViewInternal reloadData];
}

#pragma mark - UICollectionView

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.itemsInternal.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    KBFunctionTagCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kKBFunctionTagCellId forIndexPath:indexPath];
    cell.titleLabel.text = self.itemsInternal[indexPath.item];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    // 三列等宽
    CGFloat totalW = collectionView.bounds.size.width;
    CGFloat space = 10.0;
    NSInteger columns = 3;
    CGFloat width = floor((totalW - space * (columns - 1)) / columns);
    return CGSizeMake(width, 48);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 10.0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 12.0;
}

#pragma mark - Button Actions

- (void)onTapPaste { NSLog(@"点击：粘贴"); }
- (void)onTapDelete { NSLog(@"点击：删除"); }
- (void)onTapClear { NSLog(@"点击：清空"); }
- (void)onTapSend { NSLog(@"点击：发送"); }

#pragma mark - Lazy

- (KBFunctionBarView *)barViewInternal {
    if (!_barViewInternal) {
        _barViewInternal = [[KBFunctionBarView alloc] init];
        _barViewInternal.delegate = self; // 顶部功能Bar事件下发到本View
    }
    return _barViewInternal;
}

#pragma mark - KBFunctionBarViewDelegate

- (void)functionBarView:(KBFunctionBarView *)bar didTapLeftAtIndex:(NSInteger)index {
    // 将事件继续透传给上层（如键盘控制器），用于切换界面或其它业务
    if ([self.delegate respondsToSelector:@selector(functionView:didTapToolActionAtIndex:)]) {
        [self.delegate functionView:self didTapToolActionAtIndex:index];
    }
}

- (void)functionBarView:(KBFunctionBarView *)bar didTapRightAtIndex:(NSInteger)index {
    // 右侧按钮点击，如收藏/宫格等，按需继续向外抛出（这里暂不定义单独协议方法，可在此内部处理或扩展）
}

- (KBFunctionPasteView *)pasteViewInternal {
    if (!_pasteViewInternal) {
        _pasteViewInternal = [[KBFunctionPasteView alloc] init];
    }
    return _pasteViewInternal;
}

- (UICollectionView *)collectionViewInternal {
    if (!_collectionViewInternal) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.sectionInset = UIEdgeInsetsZero; // 外边距交由约束控制
        _collectionViewInternal = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionViewInternal.backgroundColor = [UIColor clearColor];
        _collectionViewInternal.dataSource = self;
        _collectionViewInternal.delegate = self;
        [_collectionViewInternal registerClass:[KBFunctionTagCell class] forCellWithReuseIdentifier:kKBFunctionTagCellId];
    }
    return _collectionViewInternal;
}

- (UIView *)rightButtonContainer {
    if (!_rightButtonContainer) {
        _rightButtonContainer = [[UIView alloc] init];
        _rightButtonContainer.backgroundColor = [UIColor clearColor];
    }
    return _rightButtonContainer;
}

- (UIButton *)buildRightButtonWithTitle:(NSString *)title color:(UIColor *)color {
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
    btn.backgroundColor = color;
    btn.layer.cornerRadius = 12.0;
    btn.layer.masksToBounds = YES;
    btn.titleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightSemibold];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    return btn;
}

- (UIButton *)pasteButtonInternal {
    if (!_pasteButtonInternal) {
        _pasteButtonInternal = [self buildRightButtonWithTitle:@"粘贴" color:[UIColor colorWithRed:0.13 green:0.73 blue:0.60 alpha:1.0]];
        [_pasteButtonInternal addTarget:self action:@selector(onTapPaste) forControlEvents:UIControlEventTouchUpInside];
    }
    return _pasteButtonInternal;
}

- (UIButton *)deleteButtonInternal {
    if (!_deleteButtonInternal) {
        // 浅灰底深色文字，更接近截图里“删除”样式
        _deleteButtonInternal = [UIButton buttonWithType:UIButtonTypeSystem];
        _deleteButtonInternal.backgroundColor = [UIColor colorWithWhite:0.92 alpha:1.0];
        _deleteButtonInternal.layer.cornerRadius = 12.0;
        _deleteButtonInternal.layer.masksToBounds = YES;
        _deleteButtonInternal.titleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightSemibold];
        [_deleteButtonInternal setTitle:@"删除" forState:UIControlStateNormal];
        [_deleteButtonInternal setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_deleteButtonInternal addTarget:self action:@selector(onTapDelete) forControlEvents:UIControlEventTouchUpInside];
    }
    return _deleteButtonInternal;
}

- (UIButton *)clearButtonInternal {
    if (!_clearButtonInternal) {
        _clearButtonInternal = [UIButton buttonWithType:UIButtonTypeSystem];
        _clearButtonInternal.backgroundColor = [UIColor colorWithWhite:0.92 alpha:1.0];
        _clearButtonInternal.layer.cornerRadius = 12.0;
        _clearButtonInternal.layer.masksToBounds = YES;
        _clearButtonInternal.titleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightSemibold];
        [_clearButtonInternal setTitle:@"清空" forState:UIControlStateNormal];
        [_clearButtonInternal setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_clearButtonInternal addTarget:self action:@selector(onTapClear) forControlEvents:UIControlEventTouchUpInside];
    }
    return _clearButtonInternal;
}

- (UIButton *)sendButtonInternal {
    if (!_sendButtonInternal) {
        _sendButtonInternal = [self buildRightButtonWithTitle:@"发送" color:[UIColor colorWithRed:0.13 green:0.73 blue:0.60 alpha:1.0]];
        [_sendButtonInternal addTarget:self action:@selector(onTapSend) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sendButtonInternal;
}

#pragma mark - Expose

- (UICollectionView *)collectionView { return self.collectionViewInternal; }
- (NSArray<NSString *> *)items { return self.itemsInternal; }
- (KBFunctionBarView *)barView { return self.barViewInternal; }
- (KBFunctionPasteView *)pasteView { return self.pasteViewInternal; }
- (UIButton *)pasteButton { return self.pasteButtonInternal; }
- (UIButton *)deleteButton { return self.deleteButtonInternal; }
- (UIButton *)clearButton { return self.clearButtonInternal; }
- (UIButton *)sendButton { return self.sendButtonInternal; }

@end
