//
//  EZDeviceSearchFilterView.m
//  EZOpenSDKDemo
//
//  搜索筛选视图：包含搜索框、状态筛选、通道筛选、重置按钮
//

#import "EZDeviceSearchFilterView.h"

@interface EZDeviceSearchFilterView () <UITextFieldDelegate>

@property (nonatomic, strong) UITextField *searchTextField;
@property (nonatomic, strong) UIButton *statusFilterBtn;
@property (nonatomic, strong) UIButton *channelFilterBtn;
@property (nonatomic, strong) UIButton *resetBtn;

@property (nonatomic, copy) NSString *searchKeyword;
@property (nonatomic, assign) EZStatusFilter statusFilter;
@property (nonatomic, assign) EZChannelFilter channelFilter;

@end

@implementation EZDeviceSearchFilterView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        _searchKeyword = @"";
        _statusFilter = EZStatusFilterAll;
        _channelFilter = EZChannelFilterAll;
        self.backgroundColor = [UIColor colorWithRed:0.96 green:0.95 blue:0.94 alpha:1.0];
        [self setupSubviews];
    }
    return self;
}

#pragma mark - UI 构建

- (void)setupSubviews {
    CGFloat padding = 12;

    // 第一行：搜索框
    self.searchTextField = [[UITextField alloc] init];
    self.searchTextField.backgroundColor = [UIColor whiteColor];
    self.searchTextField.layer.cornerRadius = 18;
    self.searchTextField.clipsToBounds = YES;
    self.searchTextField.placeholder = NSLocalizedString(@"filter_search_placeholder", @"请输入设备序列号或设备名称，仅针对已加载的设备");
    self.searchTextField.font = [UIFont systemFontOfSize:13];
    self.searchTextField.textColor = [UIColor colorWithWhite:0 alpha:0.88];
    self.searchTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.searchTextField.returnKeyType = UIReturnKeySearch;
    self.searchTextField.delegate = self;

    // 搜索图标
    UIImageView *searchIcon = [[UIImageView alloc] initWithFrame:CGRectMake(8, 0, 20, 16)];
    if (@available(iOS 13.0, *)) {
        searchIcon.image = [UIImage systemImageNamed:@"magnifyingglass"];
    }
    searchIcon.tintColor = [UIColor colorWithWhite:0 alpha:0.3];
    searchIcon.contentMode = UIViewContentModeScaleAspectFit;
    UIView *leftWrapper = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 36, 16)];
    [leftWrapper addSubview:searchIcon];
    self.searchTextField.leftView = leftWrapper;
    self.searchTextField.leftViewMode = UITextFieldViewModeAlways;
    [self.searchTextField addTarget:self action:@selector(searchTextChanged:) forControlEvents:UIControlEventEditingChanged];
    self.searchTextField.translatesAutoresizingMaskIntoConstraints = NO;
    [self addSubview:self.searchTextField];

    // 第二行：状态筛选 + 通道筛选 + 重置
    self.statusFilterBtn = [self createFilterButton];
    [self updateStatusFilterTitle];
    [self.statusFilterBtn addTarget:self action:@selector(onStatusFilterTap:) forControlEvents:UIControlEventTouchUpInside];
    self.statusFilterBtn.translatesAutoresizingMaskIntoConstraints = NO;
    [self addSubview:self.statusFilterBtn];

    self.channelFilterBtn = [self createFilterButton];
    [self updateChannelFilterTitle];
    [self.channelFilterBtn addTarget:self action:@selector(onChannelFilterTap:) forControlEvents:UIControlEventTouchUpInside];
    self.channelFilterBtn.translatesAutoresizingMaskIntoConstraints = NO;
    [self addSubview:self.channelFilterBtn];

    self.resetBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.resetBtn setTitle:NSLocalizedString(@"filter_reset", @"重置") forState:UIControlStateNormal];
    [self.resetBtn setTitleColor:[UIColor colorWithWhite:0 alpha:0.5] forState:UIControlStateNormal];
    self.resetBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    self.resetBtn.backgroundColor = [UIColor whiteColor];
    self.resetBtn.layer.cornerRadius = 16;
    self.resetBtn.layer.borderWidth = 0.5;
    self.resetBtn.layer.borderColor = [UIColor colorWithWhite:0 alpha:0.1].CGColor;
    self.resetBtn.clipsToBounds = YES;
    [self.resetBtn addTarget:self action:@selector(onResetTap) forControlEvents:UIControlEventTouchUpInside];
    self.resetBtn.translatesAutoresizingMaskIntoConstraints = NO;
    [self addSubview:self.resetBtn];

    // 约束布局
    [NSLayoutConstraint activateConstraints:@[
        // 搜索框：左右12，顶部8，高36
        [self.searchTextField.leadingAnchor constraintEqualToAnchor:self.leadingAnchor constant:padding],
        [self.searchTextField.trailingAnchor constraintEqualToAnchor:self.trailingAnchor constant:-padding],
        [self.searchTextField.topAnchor constraintEqualToAnchor:self.topAnchor constant:8],
        [self.searchTextField.heightAnchor constraintEqualToConstant:36],
        // 重置按钮：右侧，宽52，高32
        [self.resetBtn.trailingAnchor constraintEqualToAnchor:self.trailingAnchor constant:-padding],
        [self.resetBtn.topAnchor constraintEqualToAnchor:self.searchTextField.bottomAnchor constant:8],
        [self.resetBtn.widthAnchor constraintEqualToConstant:52],
        [self.resetBtn.heightAnchor constraintEqualToConstant:32],
        // 状态筛选：左侧
        [self.statusFilterBtn.leadingAnchor constraintEqualToAnchor:self.leadingAnchor constant:padding],
        [self.statusFilterBtn.topAnchor constraintEqualToAnchor:self.searchTextField.bottomAnchor constant:8],
        [self.statusFilterBtn.heightAnchor constraintEqualToConstant:32],
        // 通道筛选：状态筛选右侧+8
        [self.channelFilterBtn.leadingAnchor constraintEqualToAnchor:self.statusFilterBtn.trailingAnchor constant:8],
        [self.channelFilterBtn.topAnchor constraintEqualToAnchor:self.statusFilterBtn.topAnchor],
        [self.channelFilterBtn.heightAnchor constraintEqualToConstant:32],
        [self.channelFilterBtn.widthAnchor constraintEqualToAnchor:self.statusFilterBtn.widthAnchor],
        // 通道筛选右侧到重置按钮左侧+8
        [self.resetBtn.leadingAnchor constraintEqualToAnchor:self.channelFilterBtn.trailingAnchor constant:8],
    ]];
}

- (UIButton *)createFilterButton {
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.backgroundColor = [UIColor whiteColor];
    btn.layer.cornerRadius = 16;
    btn.clipsToBounds = YES;
    btn.titleLabel.font = [UIFont systemFontOfSize:12];
    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    btn.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 8);
    [btn setTitleColor:[UIColor colorWithWhite:0 alpha:0.88] forState:UIControlStateNormal];
    // 下拉箭头图标
    if (@available(iOS 13.0, *)) {
        UIImageView *arrow = [[UIImageView alloc] initWithImage:[UIImage systemImageNamed:@"chevron.down"]];
        arrow.tintColor = [UIColor colorWithWhite:0 alpha:0.3];
        arrow.contentMode = UIViewContentModeScaleAspectFit;
        [btn addSubview:arrow];
        arrow.translatesAutoresizingMaskIntoConstraints = NO;
        [NSLayoutConstraint activateConstraints:@[
            [arrow.trailingAnchor constraintEqualToAnchor:btn.trailingAnchor constant:-8],
            [arrow.centerYAnchor constraintEqualToAnchor:btn.centerYAnchor],
            [arrow.widthAnchor constraintEqualToConstant:16],
            [arrow.heightAnchor constraintEqualToConstant:16],
        ]];
    }
    return btn;
}

#pragma mark - 筛选 UI 更新

- (void)updateStatusFilterTitle {
    NSString *label = NSLocalizedString(@"filter_status_label", @"状态:");
    NSString *value;
    switch (self.statusFilter) {
        case EZStatusFilterOnline:  value = NSLocalizedString(@"filter_online", @"在线"); break;
        case EZStatusFilterOffline: value = NSLocalizedString(@"filter_offline", @"离线"); break;
        default:                    value = NSLocalizedString(@"filter_all", @"全部"); break;
    }
    [self setFilterButton:self.statusFilterBtn label:label value:value];
}

- (void)updateChannelFilterTitle {
    NSString *label = NSLocalizedString(@"filter_channel_label", @"通道:");
    NSString *value;
    switch (self.channelFilter) {
        case EZChannelFilterSingle: value = NSLocalizedString(@"filter_single_channel", @"单通道"); break;
        case EZChannelFilterMulti:  value = NSLocalizedString(@"filter_multi_channel", @"多通道"); break;
        default:                    value = NSLocalizedString(@"filter_all", @"全部"); break;
    }
    [self setFilterButton:self.channelFilterBtn label:label value:value];
}

- (void)setFilterButton:(UIButton *)btn label:(NSString *)label value:(NSString *)value {
    NSString *full = [NSString stringWithFormat:@"%@%@", label, value];
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:full];
    [attr addAttribute:NSForegroundColorAttributeName
                 value:[UIColor colorWithWhite:0 alpha:0.5]
                 range:NSMakeRange(0, label.length)];
    [attr addAttribute:NSForegroundColorAttributeName
                 value:[UIColor colorWithWhite:0 alpha:0.88]
                 range:NSMakeRange(label.length, value.length)];
    [btn setAttributedTitle:attr forState:UIControlStateNormal];
}

#pragma mark - 筛选事件

- (void)searchTextChanged:(UITextField *)textField {
    self.searchKeyword = textField.text ?: @"";
    [self notifyDelegate];
}

- (void)onStatusFilterTap:(UIButton *)sender {
    NSArray *titles = @[
        NSLocalizedString(@"filter_all", @"全部"),
        NSLocalizedString(@"filter_online", @"在线"),
        NSLocalizedString(@"filter_offline", @"离线")
    ];
    [self showFilterActionSheetFromButton:sender titles:titles completion:^(NSInteger index) {
        self.statusFilter = (EZStatusFilter)index;
        [self updateStatusFilterTitle];
        [self notifyDelegate];
    }];
}

- (void)onChannelFilterTap:(UIButton *)sender {
    NSArray *titles = @[
        NSLocalizedString(@"filter_all", @"全部"),
        NSLocalizedString(@"filter_single_channel", @"单通道"),
        NSLocalizedString(@"filter_multi_channel", @"多通道")
    ];
    [self showFilterActionSheetFromButton:sender titles:titles completion:^(NSInteger index) {
        self.channelFilter = (EZChannelFilter)index;
        [self updateChannelFilterTitle];
        [self notifyDelegate];
    }];
}

- (void)showFilterActionSheetFromButton:(UIButton *)anchor titles:(NSArray *)titles completion:(void(^)(NSInteger index))completion {
    // 找到最近的 ViewController 来 present
    UIViewController *vc = nil;
    UIResponder *responder = self.nextResponder;
    while (responder) {
        if ([responder isKindOfClass:[UIViewController class]]) {
            vc = (UIViewController *)responder;
            break;
        }
        responder = responder.nextResponder;
    }
    if (!vc) return;

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    for (NSInteger i = 0; i < titles.count; i++) {
        NSInteger idx = i;
        [alert addAction:[UIAlertAction actionWithTitle:titles[i] style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            if (completion) completion(idx);
        }]];
    }
    [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", @"取消") style:UIAlertActionStyleCancel handler:nil]];
    if (alert.popoverPresentationController) {
        alert.popoverPresentationController.sourceView = anchor;
        alert.popoverPresentationController.sourceRect = anchor.bounds;
    }
    [vc presentViewController:alert animated:YES completion:nil];
}

- (void)onResetTap {
    [self resetAll];
}

#pragma mark - 公开方法

- (void)resignSearchFocus {
    [self.searchTextField resignFirstResponder];
}

- (void)resetAll {
    [self.searchTextField resignFirstResponder];
    self.searchTextField.text = @"";
    self.searchKeyword = @"";
    self.statusFilter = EZStatusFilterAll;
    self.channelFilter = EZChannelFilterAll;
    [self updateStatusFilterTitle];
    [self updateChannelFilterTitle];
    [self notifyDelegate];
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - 内部方法

- (void)notifyDelegate {
    if ([self.delegate respondsToSelector:@selector(searchFilterView:didChangeWithKeyword:statusFilter:channelFilter:)]) {
        [self.delegate searchFilterView:self
                    didChangeWithKeyword:self.searchKeyword
                          statusFilter:self.statusFilter
                         channelFilter:self.channelFilter];
    }
}

@end
