// WithdrawSingleIssueViewController.mm
#import "WithdrawSingleIssueViewController.h"
#import "IssueAPIClient.h"

@interface WithdrawSingleIssueViewController ()

@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIButton *backButton;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UITextView *messageInput;
@property (nonatomic, strong) UIButton *confirmButton;

@end

@implementation WithdrawSingleIssueViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;
  
    NSLog(@"📦 Navigated to WithdrawSingleIssueViewController with:\n issueID=%@\n planID=%@\n status=%@\n unitName=%@\n reference=%@\n title=%@",
        self.issueID, self.planID, self.status, self.unitName, self.reference, self.titleText);

    [self setupHeader];
    [self setupContent];
}

#pragma mark - Header
- (void)setupHeader {
    self.headerView = [[UIView alloc] init];
    self.headerView.translatesAutoresizingMaskIntoConstraints = NO;
    self.headerView.backgroundColor = [UIColor colorWithRed:0/255.0 green:109/255.0 blue:141/255.0 alpha:1];
    [self.view addSubview:self.headerView];

    // Back button
    self.backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.backButton.translatesAutoresizingMaskIntoConstraints = NO;
    UIImage *backImage = [[UIImage systemImageNamed:@"chevron.left"]
                          imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    [self.backButton setImage:backImage forState:UIControlStateNormal];
    self.backButton.tintColor = UIColor.whiteColor;
    [self.backButton addTarget:self
                        action:@selector(handleBack)
              forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:self.backButton];

    // Title label
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.titleLabel.text = self.titleText ?: @"Delete Issue";
    self.titleLabel.textColor = UIColor.whiteColor;
    self.titleLabel.font = [UIFont boldSystemFontOfSize:18];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.headerView addSubview:self.titleLabel];

    // Layout constraints
    UILayoutGuide *safe = self.view.safeAreaLayoutGuide;
    [NSLayoutConstraint activateConstraints:@[
        [self.headerView.topAnchor constraintEqualToAnchor:safe.topAnchor],
        [self.headerView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.headerView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.headerView.heightAnchor constraintEqualToConstant:56],

        [self.backButton.leadingAnchor constraintEqualToAnchor:self.headerView.leadingAnchor constant:8],
        [self.backButton.centerYAnchor constraintEqualToAnchor:self.headerView.centerYAnchor],
        [self.backButton.widthAnchor constraintEqualToConstant:44],
        [self.backButton.heightAnchor constraintEqualToConstant:44],

        [self.titleLabel.centerXAnchor constraintEqualToAnchor:self.headerView.centerXAnchor],
        [self.titleLabel.centerYAnchor constraintEqualToAnchor:self.headerView.centerYAnchor]
    ]];
}

#pragma mark - Content
- (void)setupContent {
    UILabel *promptLabel = [[UILabel alloc] init];
    promptLabel.translatesAutoresizingMaskIntoConstraints = NO;
    promptLabel.text = @"Write your message:";
    promptLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
    [self.view addSubview:promptLabel];

    self.messageInput = [[UITextView alloc] init];
    self.messageInput.translatesAutoresizingMaskIntoConstraints = NO;
    self.messageInput.font = [UIFont systemFontOfSize:16];
    self.messageInput.layer.borderWidth = 1.0;
    self.messageInput.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.messageInput.layer.cornerRadius = 8;
    [self.view addSubview:self.messageInput];

    UIView *separator = [[UIView alloc] init];
    separator.translatesAutoresizingMaskIntoConstraints = NO;
    separator.backgroundColor = [UIColor colorWithWhite:0.8 alpha:1];
    [self.view addSubview:separator];

    self.confirmButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.confirmButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.confirmButton setTitle:@"Confirm" forState:UIControlStateNormal];
    self.confirmButton.backgroundColor = [UIColor colorWithRed:0/255.0 green:109/255.0 blue:141/255.0 alpha:1];
    [self.confirmButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    self.confirmButton.titleLabel.font = [UIFont boldSystemFontOfSize:17];
    self.confirmButton.layer.cornerRadius = 8;
    [self.confirmButton addTarget:self action:@selector(handleConfirm)
                 forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.confirmButton];

    UILayoutGuide *safe = self.view.safeAreaLayoutGuide;
    [NSLayoutConstraint activateConstraints:@[
        [promptLabel.topAnchor constraintEqualToAnchor:self.headerView.bottomAnchor constant:20],
        [promptLabel.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:20],
        [promptLabel.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:-20],

        [self.messageInput.topAnchor constraintEqualToAnchor:promptLabel.bottomAnchor constant:8],
        [self.messageInput.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:20],
        [self.messageInput.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:-20],
        [self.messageInput.heightAnchor constraintEqualToConstant:120],

        [separator.topAnchor constraintEqualToAnchor:self.messageInput.bottomAnchor constant:16],
        [separator.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:20],
        [separator.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:-20],
        [separator.heightAnchor constraintEqualToConstant:1],

        [self.confirmButton.topAnchor constraintEqualToAnchor:separator.bottomAnchor constant:40],
        [self.confirmButton.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:40],
        [self.confirmButton.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:-40],
        [self.confirmButton.heightAnchor constraintEqualToConstant:48]
    ]];
}

#pragma mark - Actions
- (void)handleBack {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)handleConfirm {
    NSString *message = self.messageInput.text ?: @"";
    if (message.length == 0) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Alert"
                                                                       message:@"Please enter a message before submitting."
                                                                preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"OK"
                                                  style:UIAlertActionStyleDefault
                                                handler:nil]];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }

    // Confirmation dialog before sending
    UIAlertController *confirm = [UIAlertController alertControllerWithTitle:@"Confirm"
                                                                     message:@"Are you sure you want to submit?"
                                                              preferredStyle:UIAlertControllerStyleAlert];
    [confirm addAction:[UIAlertAction actionWithTitle:@"No" style:UIAlertActionStyleCancel handler:nil]];
    [confirm addAction:[UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if ([self.titleText containsString:@"Delete"]) {
            [self requestDeleteIssue:self.issueID remarks:message];
        } else {
            [self requestVoidIssue:self.issueID remarks:message];
        }
    }]];
    [self presentViewController:confirm animated:YES completion:nil];
}

- (void)requestDeleteIssue:(NSString *)issueID remarks:(NSString *)remarks {
    NSLog(@"🚀 Sending DELETE ISSUE for ID=%@, remarks=%@", issueID, remarks);

    [IssueAPIClient fetchDeleteIssue:issueID remarks:remarks completion:^(NSDictionary *data, NSError *error) {
        if (error) {
          NSLog(@"Error %@", error.localizedDescription);
            return;
        }

        NSDictionary *appData = data[@"AppData"];
        if ([appData[@"status"] isEqualToString:@"success"]) {
          NSLog(@"Issue deleted successfully");
        } else {
          NSString *message = appData[@"message"] ?: @"Unknown error";
          NSLog(@"Error Message %@", message);
        }
    }];
}

- (void)requestVoidIssue:(NSString *)issueID remarks:(NSString *)remarks {
    NSLog(@"🚀 Sending VOID ISSUE for ID=%@, remarks=%@", issueID, remarks);

    NSArray *issueArray = @[ issueID ?: @"" ];
    [IssueAPIClient fetchVoidIssue:issueArray remarks:remarks completion:^(NSDictionary *data, NSError *error) {
        if (error) {
          NSLog(@"Error %@", error.localizedDescription);
            return;
        }

        NSDictionary *appData = data[@"AppData"];
        if ([appData[@"status"] isEqualToString:@"success"]) {
          NSLog(@"Issue withdrawn successfully");
        } else {
          NSString *message = appData[@"message"] ?: @"Unknown error";
          NSLog(@"Error Message %@", message);
        }
    }];
}

@end
