//
//  XXGAlertView.m
//  XXGPlayKit
//
//  Created by apple on 2025/2/26.
//

#import "XXGAlertView.h"
#import "XXGUIDriver.h"
#import "XXGWindowManager.h"
#import "Masonry.h"

#define weakify(obj) __weak typeof(obj) weak##obj = obj;
#define strongify(obj) __strong typeof(obj) obj = weak##obj;

@interface XXGAlertView()

@property (nonatomic, strong) UIView *alertContainerView;
@property (nonatomic, copy) XXGAlertViewCompletion completion;
@property (nonatomic, strong) UIStackView *buttonsStackView;

@end

@implementation XXGAlertView

- (void)dealloc {
    NSLog(@"dealloc - %@", NSStringFromClass([self class]));
}

- (instancetype)initWithFrame:(CGRect)frame
                          title:(NSString *)title
                        message:(NSString *)message
                   buttonTitles:(NSArray<NSString *> *)buttonTitles
                     completion:(XXGAlertViewCompletion)completion {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
        self.completion = completion;
        
        // 创建内容容器
        self.alertContainerView = [[UIView alloc] init];
        self.alertContainerView.backgroundColor = [XXGUIDriver xxpk_mainColor];
        self.alertContainerView.layer.cornerRadius = 8.0;
        self.alertContainerView.clipsToBounds = YES;
        self.alertContainerView.translatesAutoresizingMaskIntoConstraints = NO;
        [self addSubview:self.alertContainerView];
        
        // 居中显示容器，并设置固定宽度
        [NSLayoutConstraint activateConstraints:@[
            [self.alertContainerView.centerXAnchor constraintEqualToAnchor:self.centerXAnchor],
            [self.alertContainerView.centerYAnchor constraintEqualToAnchor:self.centerYAnchor],
            [self.alertContainerView.widthAnchor constraintEqualToConstant:270]
        ]];
        
        // 记录上一个控件，用于确定下一个控件的顶部约束
        UIView *previousView = nil;
        CGFloat verticalPadding = 20;
        
        // 如果有标题则添加标题Label
        if (title.length > 0) {
            UILabel *titleLabel = [[UILabel alloc] init];
            titleLabel.text = title;
            titleLabel.textColor = UIColor.whiteColor;
            titleLabel.font = [UIFont boldSystemFontOfSize:18];
            titleLabel.textAlignment = NSTextAlignmentCenter;
            titleLabel.numberOfLines = 0;
            titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
            [self.alertContainerView addSubview:titleLabel];
            
            [NSLayoutConstraint activateConstraints:@[
                [titleLabel.topAnchor constraintEqualToAnchor:self.alertContainerView.topAnchor constant:verticalPadding],
                [titleLabel.leadingAnchor constraintEqualToAnchor:self.alertContainerView.leadingAnchor constant:16],
                [titleLabel.trailingAnchor constraintEqualToAnchor:self.alertContainerView.trailingAnchor constant:-16]
            ]];
            
            previousView = titleLabel;
        }
        
        // 如果有消息则添加消息Label
        if (message.length > 0) {
            UILabel *messageLabel = [[UILabel alloc] init];
            messageLabel.text = message;
            messageLabel.textColor = UIColor.whiteColor;
            messageLabel.font = [UIFont systemFontOfSize:15];
            messageLabel.textAlignment = NSTextAlignmentCenter;
            messageLabel.numberOfLines = 0;
            messageLabel.translatesAutoresizingMaskIntoConstraints = NO;
            [self.alertContainerView addSubview:messageLabel];
            
            NSLayoutYAxisAnchor *topAnchor = previousView ? previousView.bottomAnchor : self.alertContainerView.topAnchor;
            CGFloat topPadding = previousView ? 10 : verticalPadding;
            [NSLayoutConstraint activateConstraints:@[
                [messageLabel.topAnchor constraintEqualToAnchor:topAnchor constant:topPadding],
                [messageLabel.leadingAnchor constraintEqualToAnchor:self.alertContainerView.leadingAnchor constant:16],
                [messageLabel.trailingAnchor constraintEqualToAnchor:self.alertContainerView.trailingAnchor constant:-16]
            ]];
            previousView = messageLabel;
        }
        
        // 创建一个垂直排列按钮的StackView
        self.buttonsStackView = [[UIStackView alloc] init];
        self.buttonsStackView.axis = UILayoutConstraintAxisVertical;
        self.buttonsStackView.spacing = 1;  // 分割线间距，可调整
        self.buttonsStackView.distribution = UIStackViewDistributionFillEqually;
        self.buttonsStackView.translatesAutoresizingMaskIntoConstraints = NO;
        [self.alertContainerView addSubview:self.buttonsStackView];
        
        // StackView顶部与上面控件（标题或消息）之间间距20，如果都没有，则从容器顶部开始
        NSLayoutYAxisAnchor *buttonsTopAnchor = previousView ? previousView.bottomAnchor : self.alertContainerView.topAnchor;
        CGFloat buttonsTopPadding = previousView ? verticalPadding : verticalPadding;
        
        [NSLayoutConstraint activateConstraints:@[
            [self.buttonsStackView.topAnchor constraintEqualToAnchor:buttonsTopAnchor constant:buttonsTopPadding],
            [self.buttonsStackView.leadingAnchor constraintEqualToAnchor:self.alertContainerView.leadingAnchor],
            [self.buttonsStackView.trailingAnchor constraintEqualToAnchor:self.alertContainerView.trailingAnchor],
            [self.buttonsStackView.bottomAnchor constraintEqualToAnchor:self.alertContainerView.bottomAnchor]
        ]];
        
        // 4. 按钮区域
       // 判断按钮数量，如果正好2个，则水平布局；否则纵向布局
       if (buttonTitles.count == 2) {
           // 水平布局
           self.buttonsStackView = [[UIStackView alloc] init];
           self.buttonsStackView.axis = UILayoutConstraintAxisHorizontal;
           self.buttonsStackView.distribution = UIStackViewDistributionFillEqually;
           self.buttonsStackView.spacing = 1;  // 分割线宽度
           self.buttonsStackView.translatesAutoresizingMaskIntoConstraints = NO;
           [self.alertContainerView addSubview:self.buttonsStackView];
           
           NSLayoutYAxisAnchor *buttonsTopAnchor = previousView ? previousView.bottomAnchor : self.alertContainerView.topAnchor;
           [NSLayoutConstraint activateConstraints:@[
               [self.buttonsStackView.topAnchor constraintEqualToAnchor:buttonsTopAnchor constant:verticalPadding],
               [self.buttonsStackView.leadingAnchor constraintEqualToAnchor:self.alertContainerView.leadingAnchor],
               [self.buttonsStackView.trailingAnchor constraintEqualToAnchor:self.alertContainerView.trailingAnchor],
               [self.buttonsStackView.bottomAnchor constraintEqualToAnchor:self.alertContainerView.bottomAnchor]
           ]];
           
           // 添加按钮（带垂直分割线）
           for (NSInteger i = 0; i < buttonTitles.count; i++) {
               NSString *btnTitle = buttonTitles[i];
               UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
               [button setTitle:btnTitle forState:UIControlStateNormal];
               button.titleLabel.font = [UIFont systemFontOfSize:17];
               [button setTitleColor:[XXGUIDriver xxpk_mainColor] forState:UIControlStateNormal];
               [button setTitleColor:UIColor.lightGrayColor forState:UIControlStateHighlighted];
               button.backgroundColor = [UIColor whiteColor];
               button.tag = i;
               [button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
               button.translatesAutoresizingMaskIntoConstraints = NO;
               [button.heightAnchor constraintEqualToConstant:40].active = YES;
               [self.buttonsStackView addArrangedSubview:button];
           }
       } else {
           // 纵向布局（按钮数量 >= 3 或者只有1个）
           self.buttonsStackView = [[UIStackView alloc] init];
           self.buttonsStackView.axis = UILayoutConstraintAxisVertical;
           self.buttonsStackView.spacing = 1;
           self.buttonsStackView.distribution = UIStackViewDistributionFillEqually;
           self.buttonsStackView.translatesAutoresizingMaskIntoConstraints = NO;
           [self.alertContainerView addSubview:self.buttonsStackView];
           
           NSLayoutYAxisAnchor *buttonsTopAnchor = previousView ? previousView.bottomAnchor : self.alertContainerView.topAnchor;
           [NSLayoutConstraint activateConstraints:@[
               [self.buttonsStackView.topAnchor constraintEqualToAnchor:buttonsTopAnchor constant:verticalPadding],
               [self.buttonsStackView.leadingAnchor constraintEqualToAnchor:self.alertContainerView.leadingAnchor],
               [self.buttonsStackView.trailingAnchor constraintEqualToAnchor:self.alertContainerView.trailingAnchor],
               [self.buttonsStackView.bottomAnchor constraintEqualToAnchor:self.alertContainerView.bottomAnchor]
           ]];
           
           for (NSInteger i = 0; i < buttonTitles.count; i++) {
               NSString *btnTitle = buttonTitles[i];
               UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
               [button setTitle:btnTitle forState:UIControlStateNormal];
               button.titleLabel.font = [UIFont systemFontOfSize:17];
               [button setTitleColor:[XXGUIDriver xxpk_mainColor] forState:UIControlStateNormal];
               [button setTitleColor:UIColor.lightGrayColor forState:UIControlStateHighlighted];
               button.backgroundColor = [UIColor whiteColor];
               button.tag = i;
               [button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
               button.translatesAutoresizingMaskIntoConstraints = NO;
               [button.heightAnchor constraintEqualToConstant:40].active = YES;
               [self.buttonsStackView addArrangedSubview:button];
           }
       }
    }
    return self;
}

- (void)buttonTapped:(UIButton *)sender {
    // 动画隐藏alert并移除
    [UIView animateWithDuration:0.25 animations:^{
        self.alpha = 0;
    } completion:^(BOOL finished) {
        [XXGWindowManager.shared xxpk_dismissWindow];
        
        if (self.completion) {
            self.completion(sender.tag);
        }
    }];
}

+ (void)xxpk_showAlertWithTitle:(NSString *)title
                        message:(NSString *)message
                   buttonTitles:(NSArray<NSString *> *)buttonTitles
                     completion:(XXGAlertViewCompletion)completion {
    // 创建一个alert实例，frame覆盖全屏
    XXGAlertView *alert = [[XXGAlertView alloc] initWithFrame:[UIScreen mainScreen].bounds
                                                 title:title
                                               message:message
                                          buttonTitles:buttonTitles
                                            completion:completion];
    
    // 添加到主窗口上
    [XXGWindowManager.shared xxpk_showWindowWithRootView:alert];
    
    // 简单动画显示alert
    alert.alpha = 0.0;
    [UIView animateWithDuration:0.25 animations:^{
        alert.alpha = 1.0;
    }];
}

+ (void)xxpk_showAlertWithTitle:(NSString *)title message:(NSString *)message completion:(XXGAlertViewCompletion)completion {
    [self xxpk_showAlertWithTitle:title message:message buttonTitles:@[XXGUIDriver.xxpk_string_ui.xxpk_ok] completion:completion];
}

@end
