//
//  OLAlertViewController.m
//  OneLoginExample
//
//  Created by Niko Xu on 2025/8/21.
//  Copyright © 2025 geetest. All rights reserved.
//

#import "OLAlertViewController.h"

@interface OLAlertViewController () <UITextViewDelegate>

@property (nonatomic, strong) UIView *alertContainer;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UITextView *contentTextView;
@property (nonatomic, strong) UIButton *confirmButton;
@property (nonatomic, strong) UIButton *cancelButton;

@property (nonatomic, copy) OLAlertAction confirmAction;
@property (nonatomic, copy) OLAlertAction cancelAction;

@property (nonatomic, strong) NSString *titleText;
@property (nonatomic, strong) NSAttributedString *contentAttr;
@property (nonatomic, strong) NSString *confirmText;
@property (nonatomic, strong) NSString *cancelText;

@end

@implementation OLAlertViewController

+ (instancetype)alertWithTitle:(NSString *)title
                       content:(NSAttributedString *)content
             confirmButtonText:(NSString *)confirmText
              cancelButtonText:(NSString *)cancelText
                confirmHandler:(OLAlertAction)confirmHandler
                 cancelHandler:(OLAlertAction)cancelHandler {
    OLAlertViewController *alert = [[OLAlertViewController alloc] initWithTitle:title content:content confirmButtonText:confirmText cancelButtonText:cancelText confirmHandler:confirmHandler cancelHandler:cancelHandler];
    
    return alert;
}

- (instancetype)initWithTitle:(NSString *)title
                      content:(NSAttributedString *)content
            confirmButtonText:(NSString *)confirmText
             cancelButtonText:(NSString *)cancelText
              confirmHandler:(OLAlertAction)confirmHandler
               cancelHandler:(OLAlertAction)cancelHandler {
    self = [super init];
    if (self) {
        _titleText    = title ?: @"";
        _contentAttr  = content ?: [[NSAttributedString alloc] init];
        _confirmText  = confirmText ?: @"确认";
        _cancelText   = cancelText  ?: @"取消";
        _confirmAction = confirmHandler;
        _cancelAction  = cancelHandler;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self showWithAnimation];
}

#pragma mark - UI
- (void)setupUI {
    self.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    self.modalTransitionStyle   = UIModalTransitionStyleCrossDissolve;
    self.view.backgroundColor   = [UIColor clearColor];
    
    // 毛玻璃背景
    UIBlurEffect *blurEffect = nil;
    if (@available(iOS 13.0, *)) {
        blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleSystemMaterial];
    }
    else {
        blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    }
    UIVisualEffectView *blurView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    blurView.translatesAutoresizingMaskIntoConstraints = NO;
    
    // 容器
    self.alertContainer = [[UIView alloc] init];
    if (@available(iOS 13.0, *)) {
        self.alertContainer.backgroundColor = [UIColor systemBackgroundColor];
    }
    else {
        self.alertContainer.backgroundColor = [UIColor whiteColor];
    }
    self.alertContainer.layer.cornerRadius = 14;
    self.alertContainer.layer.masksToBounds = YES;
    self.alertContainer.layer.borderWidth = 0.5;
    self.alertContainer.layer.borderColor = [[[UIColor lightGrayColor] colorWithAlphaComponent:0.4] CGColor];
    self.alertContainer.translatesAutoresizingMaskIntoConstraints = NO;
    
    UIView *topSpacer = [[UIView alloc] init];
    topSpacer.translatesAutoresizingMaskIntoConstraints = NO;
    [topSpacer.heightAnchor constraintEqualToConstant:1].active = YES; // 8pt 头部间距
    
    // Title
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.text          = self.titleText;
    self.titleLabel.font          = [UIFont boldSystemFontOfSize:18];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.numberOfLines = 0;
    self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    
    // Content TextView
    self.contentTextView = [[UITextView alloc] init];
    self.contentTextView.attributedText = self.contentAttr;
    self.contentTextView.editable   = NO;
    self.contentTextView.scrollEnabled = NO;
    self.contentTextView.textContainerInset = UIEdgeInsetsZero;
    self.contentTextView.textContainer.lineFragmentPadding = 0;
    self.contentTextView.backgroundColor = [UIColor clearColor];
    self.contentTextView.delegate = self;
    self.contentTextView.translatesAutoresizingMaskIntoConstraints = NO;
    
    UIView *wrapper = [[UIView alloc] init];
    [wrapper addSubview:self.contentTextView];
    [NSLayoutConstraint activateConstraints:@[
        [self.contentTextView.centerXAnchor constraintEqualToAnchor:wrapper.centerXAnchor],
        [self.contentTextView.centerYAnchor constraintEqualToAnchor:wrapper.centerYAnchor],
        [self.contentTextView.widthAnchor constraintEqualToAnchor:wrapper.widthAnchor
                                                       multiplier:0.90],
        [wrapper.heightAnchor constraintEqualToAnchor:self.contentTextView.heightAnchor]
    ]];
    
    // Buttons
    self.confirmButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.confirmButton setTitle:self.confirmText forState:UIControlStateNormal];
    [self.confirmButton.titleLabel setFont:[UIFont boldSystemFontOfSize:17]];
    [self.confirmButton setTitleColor:[UIColor systemBlueColor] forState:UIControlStateNormal];
    self.confirmButton.backgroundColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.1];
    [self.confirmButton addTarget:self action:@selector(confirmTapped) forControlEvents:UIControlEventTouchUpInside];
    
    self.cancelButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.cancelButton setTitle:self.cancelText forState:UIControlStateNormal];
    [self.cancelButton setTitleColor:[UIColor systemBlueColor] forState:UIControlStateNormal];
    self.cancelButton.backgroundColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.1];
    [self.cancelButton addTarget:self action:@selector(cancelTapped) forControlEvents:UIControlEventTouchUpInside];
    
    // Stack for buttons
    UIStackView *buttonStack = [[UIStackView alloc] initWithArrangedSubviews:@[self.cancelButton, self.confirmButton]];
    buttonStack.distribution = UIStackViewDistributionFillEqually;
    buttonStack.translatesAutoresizingMaskIntoConstraints = NO;
    
    // 组装
    UIStackView *mainStack = [[UIStackView alloc] initWithArrangedSubviews:@[topSpacer, self.titleLabel, wrapper, buttonStack]];
    mainStack.axis = UILayoutConstraintAxisVertical;
    mainStack.spacing = 12;
    mainStack.layoutMargins = UIEdgeInsetsMake(20, 24, 16, 24);
    mainStack.translatesAutoresizingMaskIntoConstraints = NO;
    
    [self.view addSubview:blurView];
    [self.view addSubview:self.alertContainer];
    [self.alertContainer addSubview:mainStack];
    
    // Auto Layout
    [NSLayoutConstraint activateConstraints:@[
        [blurView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [blurView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [blurView.topAnchor constraintEqualToAnchor:self.view.topAnchor],
        [blurView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor],
        
        [self.alertContainer.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor],
        [self.alertContainer.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor],
        [self.alertContainer.widthAnchor constraintEqualToConstant:280],
        
        [mainStack.leadingAnchor constraintEqualToAnchor:self.alertContainer.leadingAnchor],
        [mainStack.trailingAnchor constraintEqualToAnchor:self.alertContainer.trailingAnchor],
        [mainStack.topAnchor constraintEqualToAnchor:self.alertContainer.topAnchor],
        [mainStack.bottomAnchor constraintEqualToAnchor:self.alertContainer.bottomAnchor]
    ]];
}

#pragma mark - Actions & Animation
- (void)showWithAnimation {
    self.alertContainer.transform = CGAffineTransformMakeScale(0.8, 0.8);
    [UIView animateWithDuration:0.25 animations:^{
        self.alertContainer.transform = CGAffineTransformIdentity;
    }];
}

- (void)dismissWithAnimation {
    [UIView animateWithDuration:0.15 animations:^{
        self.alertContainer.transform = CGAffineTransformMakeScale(0.8, 0.8);
        self.view.alpha = 0;
    } completion:^(BOOL finished) {
        [self dismissViewControllerAnimated:NO completion:nil];
    }];
}

- (void)confirmTapped {
    [self dismissWithAnimation];
    if (self.confirmAction) self.confirmAction();
}

- (void)cancelTapped {
    [self dismissWithAnimation];
    if (self.cancelAction) self.cancelAction();
}

#pragma mark - UITextViewDelegate (点击 URL)
- (BOOL)textView:(UITextView *)textView
    shouldInteractWithURL:(NSURL *)URL
                  inRange:(NSRange)characterRange {
    if (@available(iOS 10.0, *)) {
        if ([[UIApplication sharedApplication] canOpenURL:URL]) {
            [[UIApplication sharedApplication] openURL:URL options:@{} completionHandler:^(BOOL finish){
                
            }];
        }
    }
    else {
        if ([[UIApplication sharedApplication] canOpenURL:URL]) {
            [[UIApplication sharedApplication] openURL:URL];
        }
    }
    return NO;  // 返回 NO 表示已自行处理
}

@end
