// WithdrawSingleIssueViewController.mm
#import "WithdrawSingleIssueViewController.h"
#import "IssueAPIClient.h"
#import <UIKit/UIKit.h>


@interface WithdrawSingleIssueViewController () <UITableViewDelegate, UITableViewDataSource>

@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;
@property (nonatomic, strong) UITableView *issuesTable;

@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];

    UILayoutGuide *safe = self.view.safeAreaLayoutGuide;
    NSMutableArray *constraints = [NSMutableArray arrayWithArray:@[
        [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],
    ]];

    // ✅ If multiple issues selected — show a list below comment box
    if (self.isMultiWithdraw) {
        UILabel *listLabel = [[UILabel alloc] init];
        listLabel.translatesAutoresizingMaskIntoConstraints = NO;
        listLabel.text = @"Selected Issues";
        listLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightSemibold];
        [self.view addSubview:listLabel];
        
        self.issuesTable = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleInsetGrouped];
        self.issuesTable.translatesAutoresizingMaskIntoConstraints = NO;
        self.issuesTable.dataSource = self;
        self.issuesTable.delegate = self;
        [self.view addSubview:self.issuesTable];
        
        [constraints addObjectsFromArray:@[
            [listLabel.topAnchor constraintEqualToAnchor:separator.bottomAnchor constant:20],
            [listLabel.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:20],
            [self.issuesTable.topAnchor constraintEqualToAnchor:listLabel.bottomAnchor constant:8],
            [self.issuesTable.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
            [self.issuesTable.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
            [self.issuesTable.heightAnchor constraintEqualToConstant:200],
        ]];
        
        // confirm button below table
        [constraints addObjectsFromArray:@[
            [self.confirmButton.topAnchor constraintEqualToAnchor:self.issuesTable.bottomAnchor constant:30],
        ]];
    } else {
        // confirm button directly below separator
        [constraints addObjectsFromArray:@[
            [self.confirmButton.topAnchor constraintEqualToAnchor:separator.bottomAnchor constant:40],
        ]];
    }

    [self.view addSubview:self.confirmButton];
    [constraints addObjectsFromArray:@[
        [self.confirmButton.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:40],
        [self.confirmButton.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:-40],
        [self.confirmButton.heightAnchor constraintEqualToConstant:48],
        [self.confirmButton.bottomAnchor constraintLessThanOrEqualToAnchor:safe.bottomAnchor constant:-20]
    ]];

    [NSLayoutConstraint activateConstraints:constraints];
}


#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.isMultiWithdraw) {
            // Multi-withdraw
            NSMutableArray *ids = [NSMutableArray array];
            for (NSDictionary *issue in self.selectedIssues) {
                if (issue[@"id"]) [ids addObject:issue[@"id"]];
            }

            [IssueAPIClient fetchVoidIssue:ids
                                   remarks:message
                                completion:^(NSDictionary *data, NSError *error) {
                [self handleVoidIssueResponse:data error:error];
            }];
        }
        else if ([self.titleText containsString:@"Delete"]) {
            [self requestDeleteIssue:self.issueID remarks:message];
        }
        else {
            NSArray *singleIssueArray = @[ self.issueID ?: @"" ];
            [IssueAPIClient fetchVoidIssue:singleIssueArray
                                   remarks:message
                                completion:^(NSDictionary *data, NSError *error) {
                [self handleVoidIssueResponse:data error:error];
            }];
        }
    }]];
    [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!");

            UIAlertController *successAlert = [UIAlertController alertControllerWithTitle:@"Success"
                                                                                  message:@"Issue deleted successfully."
                                                                           preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK"
                                                         style:UIAlertActionStyleDefault
                                                       handler:^(UIAlertAction * _Nonnull action) {
                // 🏠 Mimic AddIssue success dismissal logic
                UIViewController *presenter = self.presentingViewController;
                if (presenter.presentingViewController) {
                    [presenter.presentingViewController dismissViewControllerAnimated:YES completion:nil];
                } else {
                    [self dismissViewControllerAnimated:YES completion:nil];
                }
            }];
            [successAlert addAction:ok];
            [self presentViewController:successAlert animated:YES completion:nil];
        } else {
            NSString *message = appData[@"message"] ?: @"Unknown error";
            NSLog(@"⚠️ Error Message %@", message);
            [self showAlertWithTitle:@"Delete Failed" message:message];
        }
    }];
}

# pragma mark - helper
- (void)showAlertWithTitle:(NSString *)title message:(NSString *)message {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title
                                                                   message:message
                                                            preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:ok];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)handleVoidIssueResponse:(NSDictionary *)data error:(NSError *)error {
    if (error) {
        NSLog(@"❌ Void Issue Error: %@", error.localizedDescription);
        [self showAlertWithTitle:@"Error" message:error.localizedDescription];
        return;
    }

    NSDictionary *appData = data[@"AppData"];
    if ([appData[@"status"] isEqualToString:@"success"]) {
        NSLog(@"✅ Issues voided successfully!");
        UIAlertController *successAlert = [UIAlertController alertControllerWithTitle:@"Success"
                                                                              message:@"Issues withdrawn successfully."
                                                                       preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK"
                                                     style:UIAlertActionStyleDefault
                                                   handler:^(UIAlertAction * _Nonnull action) {
            // 🏠 Return to dashboard or issue list
            UIViewController *presenter = self.presentingViewController;
            if (presenter.presentingViewController) {
                [presenter.presentingViewController dismissViewControllerAnimated:YES completion:nil];
            } else {
                [self dismissViewControllerAnimated:YES completion:nil];
            }
        }];
        [successAlert addAction:ok];
        [self presentViewController:successAlert animated:YES completion:nil];
    } else {
        NSString *message = appData[@"message"] ?: @"Unknown error occurred.";
        NSLog(@"⚠️ Void Issue failed: %@", message);
        [self showAlertWithTitle:@"Failed" message:message];
    }
}

#pragma mark - UITableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.selectedIssues.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellId = @"WithdrawListCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellId];
    }
    
    NSDictionary *issue = self.selectedIssues[indexPath.row];
    cell.textLabel.text = issue[@"reference"] ?: @"(No Ref)";
    NSString *loc = issue[@"location_name"] ?: @"";
    NSString *cat = issue[@"category"] ?: @"";
    NSString *typ = issue[@"type"] ?: @"";
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ → %@ → %@", loc, cat, typ];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}


@end
