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

#pragma mark - custom cell structure
@interface WithdrawIssueCell : UITableViewCell

@property (nonatomic, strong) UIImageView *thumbView;
@property (nonatomic, strong) UILabel *referenceLabel;
@property (nonatomic, strong) UILabel *statusLabel;
@property (nonatomic, strong) UILabel *locationLabel;
@property (nonatomic, strong) UILabel *createdLabel;
@property (nonatomic, strong) UILabel *detailsLabel;
@property (nonatomic, strong) UIImageView *checkmarkView;
@end

@implementation WithdrawIssueCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.backgroundColor = UIColor.whiteColor;
        self.selectionStyle = UITableViewCellSelectionStyleNone;

        UIView *card = [[UIView alloc] init];
        card.layer.borderWidth = 1.0;
        card.layer.borderColor = [UIColor colorWithWhite:0.85 alpha:1.0].CGColor;
        card.layer.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.2].CGColor;
        card.layer.shadowOpacity = 0.25;
        card.layer.shadowRadius = 4;
        card.layer.shadowOffset = CGSizeMake(0, 2);
        card.layer.masksToBounds = NO;
        card.layer.cornerRadius = 12.0;
        card.translatesAutoresizingMaskIntoConstraints = NO;
        [self.contentView addSubview:card];
        
        // Tick/checkmark icon
        self.checkmarkView = [[UIImageView alloc] initWithImage:[UIImage systemImageNamed:@"circle"]];
        self.checkmarkView.tintColor = [UIColor lightGrayColor];
        self.checkmarkView.translatesAutoresizingMaskIntoConstraints = NO;
        self.checkmarkView.translatesAutoresizingMaskIntoConstraints = NO;
        [self.contentView addSubview:self.checkmarkView];

        // Thumbnail
        self.thumbView = [[UIImageView alloc] init];
        self.thumbView.layer.cornerRadius = 22;
        self.thumbView.clipsToBounds = YES;
        self.thumbView.translatesAutoresizingMaskIntoConstraints = NO;
        self.thumbView.contentMode = UIViewContentModeScaleAspectFill;
        [card addSubview:self.thumbView];
        
        // Labels
        self.referenceLabel = [[UILabel alloc] init];
        self.referenceLabel.font = [UIFont boldSystemFontOfSize:15];
        self.referenceLabel.textColor = [UIColor colorWithRed:0.0 green:0.45 blue:0.55 alpha:1];
        self.referenceLabel.translatesAutoresizingMaskIntoConstraints = NO;
        [card addSubview:self.referenceLabel];
        
        self.statusLabel = [[UILabel alloc] init];
        self.statusLabel.font = [UIFont systemFontOfSize:13 weight:UIFontWeightSemibold];
        self.statusLabel.textColor = UIColor.whiteColor;
        self.statusLabel.textAlignment = NSTextAlignmentCenter;
        self.statusLabel.backgroundColor = [UIColor systemBlueColor];
        self.statusLabel.layer.cornerRadius = 12;
        self.statusLabel.clipsToBounds = YES;
        self.statusLabel.translatesAutoresizingMaskIntoConstraints = NO;
        [card addSubview:self.statusLabel];
        
        self.locationLabel = [[UILabel alloc] init];
        self.locationLabel.font = [UIFont boldSystemFontOfSize:16];
        self.locationLabel.textColor = UIColor.labelColor;
        self.locationLabel.translatesAutoresizingMaskIntoConstraints = NO;
        [card addSubview:self.locationLabel];
        
        self.createdLabel = [[UILabel alloc] init];
        self.createdLabel.font = [UIFont systemFontOfSize:13];
        self.createdLabel.textColor = [UIColor colorWithWhite:0.45 alpha:1];
        self.createdLabel.translatesAutoresizingMaskIntoConstraints = NO;
        [card addSubview:self.createdLabel];
        
        self.detailsLabel = [[UILabel alloc] init];
        self.detailsLabel.font = [UIFont systemFontOfSize:14];
        self.detailsLabel.textColor = UIColor.darkGrayColor;
        self.detailsLabel.numberOfLines = 2;
        self.detailsLabel.translatesAutoresizingMaskIntoConstraints = NO;
        [card addSubview:self.detailsLabel];
      
        // Layout
        [NSLayoutConstraint activateConstraints:@[
            // Checkmark
            [self.checkmarkView.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:10],
            [self.checkmarkView.centerYAnchor constraintEqualToAnchor:self.contentView.centerYAnchor],
            [self.checkmarkView.widthAnchor constraintEqualToConstant:28],
            [self.checkmarkView.heightAnchor constraintEqualToConstant:28],

            // Card itself
            [card.leadingAnchor constraintEqualToAnchor:_checkmarkView.trailingAnchor constant:6],
            [card.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-8],
            [card.topAnchor constraintEqualToAnchor:self.contentView.topAnchor constant:4],
            [card.bottomAnchor constraintEqualToAnchor:self.contentView.bottomAnchor constant:-4],

            [self.thumbView.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:12],
            [self.thumbView.topAnchor constraintEqualToAnchor:card.topAnchor constant:12],
            [self.thumbView.widthAnchor constraintEqualToConstant:44],
            [self.thumbView.heightAnchor constraintEqualToConstant:44],
            
            [self.statusLabel.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-12],
            [self.statusLabel.topAnchor constraintEqualToAnchor:card.topAnchor constant:12],
            [self.statusLabel.widthAnchor constraintEqualToConstant:70],
            [self.statusLabel.heightAnchor constraintEqualToConstant:24],
            
            [self.locationLabel.leadingAnchor constraintEqualToAnchor:self.thumbView.trailingAnchor constant:12],
            [self.locationLabel.topAnchor constraintEqualToAnchor:card.topAnchor constant:12],
            
            [self.createdLabel.leadingAnchor constraintEqualToAnchor:self.thumbView.trailingAnchor constant:12],
            [self.createdLabel.topAnchor constraintEqualToAnchor:self.locationLabel.bottomAnchor constant:4],
            
            [self.referenceLabel.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:12],
            [self.referenceLabel.topAnchor constraintEqualToAnchor:self.thumbView.bottomAnchor constant:8],
            
            [self.detailsLabel.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:12],
            [self.detailsLabel.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-12],
            [self.detailsLabel.topAnchor constraintEqualToAnchor:self.referenceLabel.bottomAnchor constant:4],
            [self.detailsLabel.bottomAnchor constraintEqualToAnchor:card.bottomAnchor constant:-12],
        ]];
    }
    return self;
}

- (void)updateSelectionState:(BOOL)isSelected {
    self.checkmarkView.image = isSelected
        ? [UIImage systemImageNamed:@"checkmark.circle.fill"]
        : [UIImage systemImageNamed:@"circle"];
    self.checkmarkView.tintColor = isSelected
        ? [UIColor systemTealColor]
        : [UIColor lightGrayColor];
    self.contentView.alpha = isSelected ? 0.85 : 1.0;
}

@end

#pragma mark - view controller
@interface WithdrawIssuesViewController () <UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate>

@property (nonatomic, strong) UIButton *backButton;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) UILabel *searchLabel;
@property (nonatomic, strong) UIButton *filterButton;
@property (nonatomic, strong) UIButton *selectAllButton;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UILabel *counterLabel;
@property (nonatomic, strong) UIButton *proceedButton;

@property (nonatomic, strong) NSArray *issues;
@property (nonatomic, strong) NSMutableSet *selectedIssueIDs;
@property (nonatomic, strong) NSArray *filteredIssues;
@property (nonatomic, strong) NSDate *filterFromDate;
@property (nonatomic, strong) NSDate *filterToDate;
@property (nonatomic, copy) NSString *filterStatus;

@end

@implementation WithdrawIssuesViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;
    self.selectedIssueIDs = [NSMutableSet set];

    [self setupHeader];
    [self setupSearchBar];
    [self setupTableView];
    [self setupBottomBar];
    [self fetchIssues];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    static BOOL hasLoadedBefore = NO;
      if (!hasLoadedBefore) {
          hasLoadedBefore = YES;
          [self.selectedIssueIDs removeAllObjects];
          [self.tableView reloadData];
      } else if (self.isMovingToParentViewController) {
      // Coming here via push (forward navigation)
      [self.selectedIssueIDs removeAllObjects];
      [self.tableView reloadData];
    }
}

#pragma mark - UI Setup
- (void)setupHeader {
    UIView *statusBarBackground = [[UIView alloc] init];
    statusBarBackground.backgroundColor = [UIColor colorWithRed:0/255.0
                                                          green:109/255.0
                                                           blue:141/255.0
                                                          alpha:1];
    statusBarBackground.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:statusBarBackground];
  
    UIView *header = [[UIView alloc] init];
    header.backgroundColor = [UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0];
    header.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:header];
    
    // 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];
    [header addSubview:self.backButton];
    
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.text = @"Withdraw Issue";
    self.titleLabel.textColor = UIColor.whiteColor;
    self.titleLabel.font = [UIFont boldSystemFontOfSize:18];
    self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [header addSubview:self.titleLabel];
    
    [NSLayoutConstraint activateConstraints:@[
        [header.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor],
        [header.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [header.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [header.heightAnchor constraintEqualToConstant:50],
        
        [self.backButton.leadingAnchor constraintEqualToAnchor:header.leadingAnchor constant:16],
        [self.backButton.centerYAnchor constraintEqualToAnchor:header.centerYAnchor],
        
        [self.titleLabel.centerXAnchor constraintEqualToAnchor:header.centerXAnchor],
        [self.titleLabel.centerYAnchor constraintEqualToAnchor:header.centerYAnchor],
    ]];
}

- (void)setupSearchBar {
    UIView *searchContainer = [[UIView alloc] init];
    searchContainer.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:searchContainer];
    
    self.searchBar = [[UISearchBar alloc] init];
    self.searchBar.placeholder = @"Search Reference Number / Location";
    self.searchBar.delegate = self;
    self.searchBar.translatesAutoresizingMaskIntoConstraints = NO;
    self.searchBar.showsCancelButton = YES;
    self.searchBar.barTintColor = [UIColor whiteColor];
    self.searchBar.backgroundImage = [UIImage new]; // removes dark/blurred bg
    if (@available(iOS 13.0, *)) {
        self.searchBar.searchTextField.backgroundColor = [UIColor whiteColor];
        self.searchBar.searchTextField.textColor = [UIColor blackColor];
    }
    self.searchBar.opaque = YES;
    [searchContainer addSubview:self.searchBar];
    
    self.searchLabel = [[UILabel alloc] init];
    self.searchLabel.text = @"All Issues";
    self.searchLabel.font = [UIFont boldSystemFontOfSize:16];
    self.searchLabel.textColor = UIColor.labelColor;
    self.searchLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [searchContainer addSubview:self.searchLabel];
    
    self.selectAllButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.selectAllButton setTitle:@"Select All" forState:UIControlStateNormal];
    [self.selectAllButton setTitleColor:[UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0] forState:UIControlStateNormal];
    self.selectAllButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.selectAllButton addTarget:self action:@selector(selectAllTapped) forControlEvents:UIControlEventTouchUpInside];
    [searchContainer addSubview:self.selectAllButton];
  
    // Filter button (next to search bar)
    self.filterButton = [UIButton buttonWithType:UIButtonTypeSystem];
    UIImage *filterIcon = [UIImage systemImageNamed:@"line.3.horizontal.decrease.circle"];
    [self.filterButton setImage:filterIcon forState:UIControlStateNormal];
    self.filterButton.tintColor = [UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0];
    self.filterButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.filterButton addTarget:self action:@selector(filterTapped) forControlEvents:UIControlEventTouchUpInside];
    [searchContainer addSubview:self.filterButton];

    [NSLayoutConstraint activateConstraints:@[
        [searchContainer.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor constant:50],
        [searchContainer.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:8],
        [searchContainer.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:-8],
        [searchContainer.heightAnchor constraintEqualToConstant:100],
        
        [self.searchBar.leadingAnchor constraintEqualToAnchor:searchContainer.leadingAnchor],
        [self.searchBar.trailingAnchor constraintEqualToAnchor:searchContainer.trailingAnchor],
        [self.searchBar.centerYAnchor constraintEqualToAnchor:searchContainer.centerYAnchor constant:-10],
        
        [self.filterButton.trailingAnchor constraintEqualToAnchor:self.selectAllButton.leadingAnchor constant:-12],
        [self.filterButton.centerYAnchor constraintEqualToAnchor:self.selectAllButton.centerYAnchor],
        [self.filterButton.widthAnchor constraintEqualToConstant:28],
        [self.filterButton.heightAnchor constraintEqualToConstant:28],
        
        [self.searchLabel.leadingAnchor constraintEqualToAnchor:searchContainer.leadingAnchor constant:16],
        [self.searchLabel.centerYAnchor constraintEqualToAnchor:self.selectAllButton.centerYAnchor],

        [self.selectAllButton.trailingAnchor constraintEqualToAnchor:searchContainer.trailingAnchor constant:-16],
        [self.selectAllButton.topAnchor constraintEqualToAnchor:self.searchBar.bottomAnchor constant:8],
    ]];
    UITextField *textField = self.searchBar.searchTextField;

    // Make text darker and clearer
    textField.textColor = [UIColor blackColor];
    textField.font = [UIFont systemFontOfSize:16 weight:UIFontWeightRegular];

    // Darken placeholder
    textField.attributedPlaceholder = [[NSAttributedString alloc]
        initWithString:self.searchBar.placeholder
            attributes:@{NSForegroundColorAttributeName: [UIColor darkGrayColor],
                         NSFontAttributeName: [UIFont systemFontOfSize:16]}];

    // Optional: give the search field a white rounded background with shadow
    textField.backgroundColor = [UIColor whiteColor];
    textField.layer.cornerRadius = 10;
    textField.layer.masksToBounds = YES;
    textField.layer.borderColor = [UIColor colorWithWhite:0.8 alpha:1.0].CGColor; // light gray
    textField.layer.borderWidth = 1.0;
}

- (void)setupTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.translatesAutoresizingMaskIntoConstraints = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundView = nil;
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.opaque = YES;
    [self.tableView registerClass:[WithdrawIssueCell class] forCellReuseIdentifier:@"WithdrawIssueCell"];
    [self.view addSubview:self.tableView];
    
    [NSLayoutConstraint activateConstraints:@[
        [self.tableView.topAnchor constraintEqualToAnchor:self.searchBar.superview.bottomAnchor constant:4],
        [self.tableView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:8],
        [self.tableView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:-8],
        [self.tableView.bottomAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.bottomAnchor constant:-60]
    ]];
}

- (void)setupBottomBar {
    UIView *bottomBar = [[UIView alloc] init];
    bottomBar.backgroundColor = UIColor.whiteColor;
    bottomBar.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:bottomBar];
    
    self.counterLabel = [[UILabel alloc] init];
    self.counterLabel.text = @"0 / 0";
    self.counterLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightMedium];
    self.counterLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.counterLabel.textColor = UIColor.blackColor;
    [bottomBar addSubview:self.counterLabel];
    
    self.proceedButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.proceedButton setTitle:@"Proceed" forState:UIControlStateNormal];
    self.proceedButton.backgroundColor = [UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0];
    [self.proceedButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    self.proceedButton.layer.cornerRadius = 8;
    self.proceedButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.proceedButton addTarget:self action:@selector(proceedTapped) forControlEvents:UIControlEventTouchUpInside];
    [bottomBar addSubview:self.proceedButton];
    
    [NSLayoutConstraint activateConstraints:@[
        [bottomBar.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [bottomBar.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [bottomBar.bottomAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.bottomAnchor],
        [bottomBar.heightAnchor constraintEqualToConstant:60],
        
        [self.counterLabel.leadingAnchor constraintEqualToAnchor:bottomBar.leadingAnchor constant:16],
        [self.counterLabel.centerYAnchor constraintEqualToAnchor:bottomBar.centerYAnchor],
        
        [self.proceedButton.trailingAnchor constraintEqualToAnchor:bottomBar.trailingAnchor constant:-16],
        [self.proceedButton.centerYAnchor constraintEqualToAnchor:bottomBar.centerYAnchor],
        [self.proceedButton.widthAnchor constraintEqualToConstant:120],
        [self.proceedButton.heightAnchor constraintEqualToConstant:40]
    ]];
}

#pragma mark - Data
- (void)fetchIssues {
    [IssueAPIClient fetchIssues:^(NSDictionary *data, NSError *error) {
        if (error) return;
        
        NSArray *allIssues = data[@"Data"] ?: @[];
        
        // ✅ Filter to show only "W.I.P" issues
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"status_external == %@", @"W.I.P"];
        NSArray *filtered = [allIssues filteredArrayUsingPredicate:predicate];
        
        // ✅ Sort by date descending (newest first)
        NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"created_at" ascending:NO];
        NSArray *sorted = [filtered sortedArrayUsingDescriptors:@[sortDescriptor]];
        
        self.issues = sorted;
        self.filteredIssues = self.issues;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.counterLabel.text = [NSString stringWithFormat:@"0 / %lu", (unsigned long)self.issues.count];
            [self.tableView reloadData];
        });
    }];
}

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

- (void)selectAllTapped {
    if (self.selectedIssueIDs.count == self.filteredIssues.count) {
        // All visible issues are selected, so deselect all
        [self.selectedIssueIDs removeAllObjects];
    } else {
        // Select all currently visible issues
        for (NSDictionary *issue in self.filteredIssues) {
            [self.selectedIssueIDs addObject:issue[@"id"]];
        }
    }
  
    // Update button title dynamically
    if (self.selectedIssueIDs.count == self.filteredIssues.count) {
        [self.selectAllButton setTitle:@"Deselect All" forState:UIControlStateNormal];
    } else {
        [self.selectAllButton setTitle:@"Select All" forState:UIControlStateNormal];
    }
  
    [self.tableView reloadData];
    [self updateCounter];
}


- (void)proceedTapped {
    if (self.selectedIssueIDs.count == 0) {
        [self showAlert:@"Please select at least one issue to proceed."];
        return;
    }

    NSPredicate *selectedPredicate = [NSPredicate predicateWithFormat:@"id IN %@", self.selectedIssueIDs];
    NSArray *filteredIssues = [self.issues filteredArrayUsingPredicate:selectedPredicate];

    NSLog(@"✅ Selected issue IDs: %@", self.selectedIssueIDs);
    NSLog(@"✅ Total issues available: %lu", (unsigned long)self.issues.count);
    NSLog(@"✅ Filtered selected issues: %@", filteredIssues);

    // Create a clean array with only the reference (and other desired fields)
    NSMutableArray *formattedIssues = [NSMutableArray array];
    for (NSDictionary *issue in filteredIssues) {
        NSString *ref = issue[@"reference"] ?: @"";
        NSString *issueId = issue[@"id"] ?: @"";
        [formattedIssues addObject:@{
            @"id": issueId,
            @"reference": ref
        }];
    }
    NSLog(@"✅ Final selectedIssues to send: %@", formattedIssues);

    WithdrawSingleIssueViewController *vc = [[WithdrawSingleIssueViewController alloc] init];
    vc.selectedIssues = formattedIssues;  // Clean, predictable structure
    vc.isMultiWithdraw = YES;
    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:vc animated:YES completion:nil];
}

- (void)updateCounter {
    self.counterLabel.text = [NSString stringWithFormat:@"%lu / %lu", (unsigned long)self.selectedIssueIDs.count, (unsigned long)self.issues.count];
}

- (void)showAlert:(NSString *)message {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Alert" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)setNoImagePlaceholder:(UIImageView *)thumbView {
    // Clear any previous content
    thumbView.image = nil;
    thumbView.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1.0];
    
    for (UIView *subview in thumbView.subviews) {
        [subview removeFromSuperview];
    }

    UILabel *noImageLabel = [[UILabel alloc] init];
    noImageLabel.text = @"No image";
    noImageLabel.textAlignment = NSTextAlignmentCenter;
    noImageLabel.font = [UIFont systemFontOfSize:10];
    noImageLabel.textColor = [UIColor grayColor];
    noImageLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [thumbView addSubview:noImageLabel];

    [NSLayoutConstraint activateConstraints:@[
        [noImageLabel.centerXAnchor constraintEqualToAnchor:thumbView.centerXAnchor],
        [noImageLabel.centerYAnchor constraintEqualToAnchor:thumbView.centerYAnchor]
    ]];
}

- (UIColor *)colorFromHexString:(NSString *)hex {
    unsigned int rgbValue = 0;
    NSScanner *scanner = [NSScanner scannerWithString:hex];
    if ([hex hasPrefix:@"#"]) [scanner setScanLocation:1];
    [scanner scanHexInt:&rgbValue];
    return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16) / 255.0
                           green:((rgbValue & 0xFF00) >> 8) / 255.0
                            blue:(rgbValue & 0xFF) / 255.0
                           alpha:1.0];
}

- (void)filterTapped {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Filter Issues"
                                                                   message:nil
                                                            preferredStyle:UIAlertControllerStyleAlert];

    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"From Date (YYYY-MM-DD)";
    }];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"To Date (YYYY-MM-DD)";
    }];
  
    UIAlertAction *allStatus = [UIAlertAction actionWithTitle:@"All" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self applyFilterWithStatus:@"All"];
    }];
    UIAlertAction *lodged = [UIAlertAction actionWithTitle:@"Lodged" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self applyFilterWithStatus:@"Lodged"];
    }];
    UIAlertAction *pending = [UIAlertAction actionWithTitle:@"Pending Access" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
          [self applyFilterWithStatus:@"Pending Access"];
      }];
    UIAlertAction *wip = [UIAlertAction actionWithTitle:@"W.I.P" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self applyFilterWithStatus:@"W.I.P"];
    }];

    [alert addAction:allStatus];
    [alert addAction:lodged];
    [alert addAction:pending];
    [alert addAction:wip];

    [alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil]];

    [self presentViewController:alert animated:YES completion:nil];
}

- (void)applyFilterWithStatus:(NSString *)status {
    NSLog(@"Filter applied: %@", status);

    if ([status isEqualToString:@"All"]) {
        self.filteredIssues = self.issues;
    } else {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"status_external == %@", status];
        self.filteredIssues = [self.issues filteredArrayUsingPredicate:predicate];
    }

    [self.tableView reloadData];
}

- (void)applyFilter {
    NSMutableArray *filtered = [NSMutableArray array];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd"; // match your issue[@"created_at"] format
    
    for (NSDictionary *issue in self.issues) {
        NSString *status = issue[@"status_external"] ?: @"";
        NSString *dateStr = issue[@"created_at"] ?: @"";
        NSDate *createdDate = [formatter dateFromString:dateStr];
        
        BOOL matchDate = YES;
        if (self.filterFromDate && createdDate && [createdDate compare:self.filterFromDate] == NSOrderedAscending) {
            matchDate = NO;
        }
        if (self.filterToDate && createdDate && [createdDate compare:self.filterToDate] == NSOrderedDescending) {
            matchDate = NO;
        }
        
        BOOL matchStatus = YES;
        if (self.filterStatus && ![self.filterStatus isEqualToString:@"All"]) {
            matchStatus = [status isEqualToString:self.filterStatus];
        }
        
        if (matchDate && matchStatus) {
            [filtered addObject:issue];
        }
    }
    
    self.filteredIssues = filtered;
    [self.tableView reloadData];
}

#pragma mark - TableView
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *issue = self.filteredIssues[indexPath.section];
    NSString *issueID = issue[@"id"];

    if ([self.selectedIssueIDs containsObject:issueID]) {
        [self.selectedIssueIDs removeObject:issueID];
    } else {
        [self.selectedIssueIDs addObject:issueID];
    }

    [self updateCounter];

    WithdrawIssueCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    BOOL isSelected = [self.selectedIssueIDs containsObject:issueID];
    [cell updateSelectionState:isSelected];
}

 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.filteredIssues.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WithdrawIssueCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WithdrawIssueCell" forIndexPath:indexPath];

    // Reset reused state
    cell.thumbView.image = nil;
    for (UIView *subview in cell.thumbView.subviews) {
        [subview removeFromSuperview];
    }

    NSDictionary *issue = self.filteredIssues[indexPath.section];
    NSString *thumbURL = issue[@"thumb_image"] ?: @"";

    // Thumbnail rendering (copied from IssueViewController)
    if (thumbURL.length > 0) {
        NSURL *url = [NSURL URLWithString:thumbURL];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSData *data = [NSData dataWithContentsOfURL:url];
            dispatch_async(dispatch_get_main_queue(), ^{
                WithdrawIssueCell *updateCell = [tableView cellForRowAtIndexPath:indexPath];
                if (!updateCell) return;

                // Clear any "No image" placeholder labels
                for (UIView *subview in updateCell.thumbView.subviews) {
                    [subview removeFromSuperview];
                }

                if (data) {
                    UIImage *img = [UIImage imageWithData:data];
                    if (img) {
                        updateCell.thumbView.image = img;
                        updateCell.thumbView.backgroundColor = UIColor.clearColor;
                    } else {
                        [self setNoImagePlaceholder:updateCell.thumbView];
                    }
                } else {
                    [self setNoImagePlaceholder:updateCell.thumbView];
                }
            });
        });
    } else {
        [self setNoImagePlaceholder:cell.thumbView];
    }
    
    // Text fields
    cell.referenceLabel.text = issue[@"reference"] ?: @"";
    cell.statusLabel.text = issue[@"status_external"] ?: @"";
    cell.statusLabel.backgroundColor = [self colorFromHexString:issue[@"status_ex_color"] ?: @""];
    cell.locationLabel.text = issue[@"location_name"] ?: @"";
    cell.createdLabel.text = [NSString stringWithFormat:@"Created on %@", issue[@"created_at"] ?: @""];
    NSString *category = issue[@"category"] ?: @"";
    NSString *type = issue[@"type"] ?: @"";
    NSString *issueText = issue[@"issue"] ?: @"";

    cell.detailsLabel.text = [NSString stringWithFormat:@"%@ → %@ → %@",
                              category, type, issueText];
    cell.backgroundColor = UIColor.clearColor;
    cell.contentView.backgroundColor = UIColor.whiteColor;
    // Highlight selected ones
    BOOL isSelected = [self.selectedIssueIDs containsObject:issue[@"id"]];
    [cell updateSelectionState:isSelected];
    
    return cell;
}

// ✅ Add spacing between cells using header/footer height
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 2; // top spacing
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 2; // bottom spacing
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    return 140;
}

// Remove empty header/footer lines at end
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [UIView new];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}

#pragma mark - Search Handling
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    NSString *search = [searchText uppercaseString];
    
    if (search.length == 0) {
        self.filteredIssues = self.issues;
    } else {
        NSMutableArray *matches = [NSMutableArray array];
        for (NSDictionary *issue in self.issues) {
            NSString *reference = [issue[@"reference"] ?: @"" uppercaseString];
            NSString *location = [issue[@"location_name"] ?: @"" uppercaseString];
            NSString *remarks  = [issue[@"remarks"] ?: @"" uppercaseString];
            NSString *createdAt = [issue[@"created_at"] ?: @"" uppercaseString];
            NSString *category = [issue[@"category"] ?: @"" uppercaseString];
            NSString *type = [issue[@"type"] ?: @"" uppercaseString];
            NSString *issueText = [issue[@"issue"] ?: @"" uppercaseString];
            NSString *status = [issue[@"status_external"] ?: @"" uppercaseString];

            if ([reference containsString:search] ||
                [location containsString:search] ||
                [remarks containsString:search] ||
                [createdAt containsString:search] ||
                [category containsString:search] ||
                [type containsString:search] ||
                [issueText containsString:search] ||
                [status containsString:search]) {
                [matches addObject:issue];
            }
        }
        self.filteredIssues = matches;
    }

    [self.tableView reloadData];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [searchBar resignFirstResponder];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    // Clear search text
    searchBar.text = @"";
    
    // Reset filtered issues
    self.filteredIssues = self.issues;
    [self.tableView reloadData];
    
    // Dismiss keyboard
    [searchBar resignFirstResponder];
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    [searchBar setShowsCancelButton:YES animated:YES];
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
    [searchBar setShowsCancelButton:NO animated:YES];
}

@end
