// WithdrawSingleIssueViewController.mm
#import "WithdrawSingleIssueViewController.h"
#import "APIClient.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];
  
    if (self.isMultiWithdraw){
      
    }
  
    [self setupContent];
}

#pragma mark - Header
- (void)setupHeader {
    CGFloat statusBarHeight = UIApplication.sharedApplication.statusBarFrame.size.height;
    self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, statusBarHeight + 60)];
    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];
    promptLabel.textColor = [UIColor darkGrayColor];
    [self.view addSubview:promptLabel];

    self.messageInput = [[UITextView alloc] init];
    self.messageInput.translatesAutoresizingMaskIntoConstraints = NO;
    self.messageInput.font = [UIFont systemFontOfSize:16];

    // --- Styling ---
    self.messageInput.backgroundColor = [UIColor colorWithWhite:0.97 alpha:1.0]; // soft light gray
    self.messageInput.textColor = [UIColor blackColor];
    self.messageInput.layer.borderWidth = 1.0;
    self.messageInput.layer.borderColor = [UIColor colorWithWhite:0.85 alpha:1.0].CGColor;
    self.messageInput.layer.cornerRadius = 8;
    self.messageInput.layer.masksToBounds = YES;
    [self.view addSubview:self.messageInput];

    // --- CREATE confirmButton BEFORE using it in constraints ---
    self.confirmButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.confirmButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.confirmButton setTitle:@"Submit" 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.layer.cornerRadius = 8;
    [self.confirmButton addTarget:self action:@selector(handleConfirm) forControlEvents:UIControlEventTouchUpInside];
    // don't addSubview yet if you prefer, we'll add below before constraints

    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) {
        // "Withdrawing" title
        UILabel *withdrawingLabel = [[UILabel alloc] init];
        withdrawingLabel.translatesAutoresizingMaskIntoConstraints = NO;
        withdrawingLabel.text = @"Withdrawing";
        withdrawingLabel.font = [UIFont boldSystemFontOfSize:16];
        withdrawingLabel.textColor = [UIColor blackColor]; // main title dark
        withdrawingLabel.backgroundColor = [UIColor clearColor];
        [self.view addSubview:withdrawingLabel];

        // "X Issue(s)" label
        NSString *countText = [NSString stringWithFormat:@"%lu Issue(s)", (unsigned long)self.selectedIssues.count];
        UILabel *countLabel = [[UILabel alloc] init];
        countLabel.translatesAutoresizingMaskIntoConstraints = NO;
        countLabel.text = countText;
        countLabel.font = [UIFont systemFontOfSize:14];
        countLabel.textColor = [UIColor colorWithWhite:0.4 alpha:1.0]; // subtle gray text
        [self.view addSubview:countLabel];
        
        // Table showing list of issues
        self.issuesTable = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleInsetGrouped];
        self.issuesTable.translatesAutoresizingMaskIntoConstraints = NO;
        self.issuesTable.dataSource = self;
        self.issuesTable.delegate = self;
        self.issuesTable.layer.cornerRadius = 8;
        self.issuesTable.layer.masksToBounds = YES;
        self.issuesTable.layer.borderColor = [UIColor colorWithWhite:0.9 alpha:1.0].CGColor;
        self.issuesTable.layer.borderWidth = 1.0;
        [self.issuesTable registerClass:[UITableViewCell class] forCellReuseIdentifier:@"WithdrawListCell"];
        [self.view addSubview:self.issuesTable];
        
        [constraints addObjectsFromArray:@[
            [withdrawingLabel.topAnchor constraintEqualToAnchor:separator.bottomAnchor constant:20],
            [withdrawingLabel.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:20],
            
            [countLabel.topAnchor constraintEqualToAnchor:withdrawingLabel.bottomAnchor constant:4],
            [countLabel.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:20],
            
            [self.issuesTable.topAnchor constraintEqualToAnchor:countLabel.bottomAnchor constant:8],
            [self.issuesTable.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:20],
            [self.issuesTable.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:-20],
            [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],
        ]];
    }

    // Add confirm button to view so its anchors are valid
    [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;
    }

    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) {
            // Extract only IDs (and skip nils)
            NSMutableArray *ids = [NSMutableArray array];
            for (NSDictionary *issue in self.selectedIssues ?: @[]) {
                id issueId = issue[@"id"];
                if (issueId) [ids addObject:issueId];
            }

            NSLog(@"📦 Extracted IDs for API: %@", ids);

            if (ids.count == 0) {
                [self showAlertWithTitle:@"Alert" message:@"No valid issue IDs to submit."];
                return;
            }

            [self requestVoidIssue:ids remarks:message];
        }
        else if ([self.titleText containsString:@"Delete"]) {
            if (self.issueID == nil) {
                [self showAlertWithTitle:@"Alert" message:@"No issue selected to delete."];
                return;
            }
            [self requestDeleteIssue:self.issueID remarks:message];
        }
        else {
            if (self.issueID == nil) {
                [self showAlertWithTitle:@"Alert" message:@"No issue selected to void."];
                return;
            }
            NSArray *singleIssueArray = @[ self.issueID ];
            [self requestVoidIssue:singleIssueArray 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);

    [APIClient requestDeleteIssue:issueID remarks:remarks completion:^(BOOL success, 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];
        }
    }];
}

-(void)requestVoidIssue:(NSArray *)ids remarks:(NSString *)remarks {
  NSLog(@"🚀 Sending VOID ISSUE for ID=%@, remarks=%@", self.selectedIssues, remarks);

    [APIClient requestVoidIssue:ids
                         remarks:remarks
                      completion:^(BOOL success, NSDictionary *data, NSError *error) {
    if (error) {
        NSLog(@"Error %@", error.localizedDescription);
          return;
      }

      NSDictionary *appData = data[@"AppData"];
      if ([appData[@"status"] isEqualToString:@"success"]) {
          NSLog(@"✅ Issue voided successfully!");

          UIAlertController *successAlert = [UIAlertController alertControllerWithTitle:@"Success"
                                                                                message:@"Issue voided 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:@"Void 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];
}

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

- (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];
    }
    
    if (indexPath.row < self.selectedIssues.count) {
        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];
    } else {
        cell.textLabel.text = @"(No Ref)";
        cell.detailTextLabel.text = @"";
    }
  
    cell.backgroundColor = [UIColor whiteColor];
    cell.textLabel.textColor = [UIColor blackColor];
    cell.detailTextLabel.textColor = [UIColor colorWithWhite:0.4 alpha:1.0];
    cell.contentView.backgroundColor = [UIColor colorWithWhite:0.98 alpha:1.0];
    cell.layer.cornerRadius = 8;
    cell.layer.masksToBounds = NO;
    cell.layer.shadowColor = [UIColor colorWithWhite:0 alpha:0.1].CGColor;
    cell.layer.shadowOffset = CGSizeMake(0, 2);
    cell.layer.shadowOpacity = 0.3;
    cell.layer.shadowRadius = 4;
    cell.layer.borderWidth = 0.5;
    cell.layer.borderColor = [UIColor colorWithWhite:0.9 alpha:1.0].CGColor;

    cell.textLabel.font = [UIFont boldSystemFontOfSize:15];
    cell.detailTextLabel.font = [UIFont systemFontOfSize:13];
    cell.textLabel.textColor = [UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0];
    cell.detailTextLabel.textColor = [UIColor darkGrayColor];

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

@end
