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

@interface WithdrawIssuesViewController () <UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate>

@property (nonatomic, strong) UIButton *closeButton;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UISearchBar *searchBar;
@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) UIView *searchContainer;
@property (nonatomic, strong) UIView *bottomBar;
@property (nonatomic, strong) NSArray *issues;
@property (nonatomic, strong) NSMutableSet *selectedIssueIDs;
@property (nonatomic, strong) NSArray *filteredIssues;

@end

@implementation WithdrawIssuesViewController

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

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

#pragma mark - UI Setup
- (void)setupHeader {
    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];
    
    self.closeButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.closeButton setImage:[UIImage systemImageNamed:@"xmark"] forState:UIControlStateNormal];
    self.closeButton.tintColor = UIColor.whiteColor;
    [self.closeButton addTarget:self action:@selector(closeTapped) forControlEvents:UIControlEventTouchUpInside];
    self.closeButton.translatesAutoresizingMaskIntoConstraints = NO;
    [header addSubview:self.closeButton];
    
    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.closeButton.leadingAnchor constraintEqualToAnchor:header.leadingAnchor constant:16],
        [self.closeButton.centerYAnchor constraintEqualToAnchor:header.centerYAnchor],
        
        [self.titleLabel.centerXAnchor constraintEqualToAnchor:header.centerXAnchor],
        [self.titleLabel.centerYAnchor constraintEqualToAnchor:header.centerYAnchor],
    ]];
}

- (void)setupSearchBar {
    self.searchContainer = [[UIView alloc] init]; // 👈 keep a property reference
    self.searchContainer.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.searchContainer];
    
    self.searchBar = [[UISearchBar alloc] init];
    self.searchBar.placeholder = @"Search Reference Number / Location";
    self.searchBar.delegate = self;
    self.searchBar.translatesAutoresizingMaskIntoConstraints = NO;
    [self.searchContainer addSubview:self.searchBar];
    
    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];
    [self.searchContainer addSubview:self.selectAllButton];
    
    UIView *header = self.view.subviews.firstObject;
    
    [NSLayoutConstraint activateConstraints:@[
        [self.searchContainer.topAnchor constraintEqualToAnchor:header.bottomAnchor],
        [self.searchContainer.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:8],
        [self.searchContainer.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:-8],
        [self.searchContainer.heightAnchor constraintEqualToConstant:80],
        
        [self.searchBar.leadingAnchor constraintEqualToAnchor:self.searchContainer.leadingAnchor],
        [self.searchBar.trailingAnchor constraintEqualToAnchor:self.searchContainer.trailingAnchor constant:-8],
        [self.searchBar.centerYAnchor constraintEqualToAnchor:self.searchContainer.centerYAnchor constant:-10],
        
        [self.selectAllButton.trailingAnchor constraintEqualToAnchor:self.searchContainer.trailingAnchor constant:-16],
        [self.selectAllButton.topAnchor constraintEqualToAnchor:self.searchBar.bottomAnchor constant:8],
    ]];
}

- (void)setupTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.translatesAutoresizingMaskIntoConstraints = NO;
    self.tableView.backgroundColor = [UIColor systemGroupedBackgroundColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
}

- (void)setupBottomBar {
    self.bottomBar = [[UIView alloc] init]; // 👈 also store in a property
    self.bottomBar.backgroundColor = UIColor.whiteColor;
    self.bottomBar.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.bottomBar];
    
    // ... your existing counter + button setup ...
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

    // Now that everything exists, activate proper constraints for the table
    if (self.tableView.constraints.count == 0) {
        [NSLayoutConstraint activateConstraints:@[
            [self.tableView.topAnchor constraintEqualToAnchor:self.searchContainer.bottomAnchor constant:8],
            [self.tableView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
            [self.tableView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
            [self.tableView.bottomAnchor constraintEqualToAnchor:self.bottomBar.topAnchor]
        ]];
    }
}

#pragma mark - Data
- (void)fetchIssues {
    [IssueAPIClient fetchIssues:^(NSDictionary *data, NSError *error) {
        if (error) return;

        NSArray *allIssues = data[@"Data"] ?: @[];

        // ✅ Filter W.I.P. only
        NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(NSDictionary *issue, NSDictionary *bindings) {
            NSString *status = [issue[@"status_external"] lowercaseString];
            return [status isEqualToString:@"w.i.p"] || [status isEqualToString:@"wip"];
        }];

        self.issues = [allIssues filteredArrayUsingPredicate:predicate];
        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)closeTapped {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)selectAllTapped {
    if (self.selectedIssueIDs.count == self.issues.count) {
        [self.selectedIssueIDs removeAllObjects];
    } else {
        for (NSDictionary *issue in self.issues) {
            [self.selectedIssueIDs addObject:issue[@"id"]];
        }
    }
    [self.tableView reloadData];
    [self updateCounter];
}

- (void)proceedTapped {
    if (self.selectedIssueIDs.count == 0) {
        [self showAlert:@"Please select at least one issue to proceed."];
        return;
    }
    WithdrawSingleIssueViewController *vc = [[WithdrawSingleIssueViewController alloc] init];
    vc.selectedIssues = [self.issues filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"id IN %@", self.selectedIssueIDs]];
    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];
}

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellId = @"WithdrawCardCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        cell.backgroundColor = UIColor.clearColor;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        // --- Card container ---
        UIView *card = [[UIView alloc] initWithFrame:CGRectZero];
        card.tag = 100;
        card.backgroundColor = UIColor.whiteColor;
        card.layer.cornerRadius = 12;
        card.layer.shadowColor = [UIColor blackColor].CGColor;
        card.layer.shadowOpacity = 0.1;
        card.layer.shadowRadius = 4;
        card.layer.shadowOffset = CGSizeMake(0, 2);
        [cell.contentView addSubview:card];
        card.translatesAutoresizingMaskIntoConstraints = NO;
        
        // --- Checkmark overlay ---
        UIImageView *checkIcon = [[UIImageView alloc] initWithImage:[UIImage systemImageNamed:@"checkmark.circle.fill"]];
        checkIcon.tag = 202;
        checkIcon.tintColor = [UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0];
        checkIcon.translatesAutoresizingMaskIntoConstraints = NO;
        [cell.contentView addSubview:checkIcon];
        
        // --- Title ---
        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.tag = 200;
        titleLabel.font = [UIFont boldSystemFontOfSize:16];
        [card addSubview:titleLabel];
        titleLabel.translatesAutoresizingMaskIntoConstraints = NO;

        // --- Subtitle ---
        UILabel *subtitleLabel = [[UILabel alloc] init];
        subtitleLabel.tag = 201;
        subtitleLabel.font = [UIFont systemFontOfSize:14];
        subtitleLabel.textColor = UIColor.darkGrayColor;
        [card addSubview:subtitleLabel];
        subtitleLabel.translatesAutoresizingMaskIntoConstraints = NO;

        // --- Layout ---
        [NSLayoutConstraint activateConstraints:@[
            [card.leadingAnchor constraintEqualToAnchor:cell.contentView.leadingAnchor constant:16],
            [card.trailingAnchor constraintEqualToAnchor:cell.contentView.trailingAnchor constant:-32], // leave space on the right for the checkmark
            [card.topAnchor constraintEqualToAnchor:cell.contentView.topAnchor],
            [card.bottomAnchor constraintEqualToAnchor:cell.contentView.bottomAnchor constant:-4],
            
            [checkIcon.centerYAnchor constraintEqualToAnchor:card.centerYAnchor],
            [checkIcon.leadingAnchor constraintEqualToAnchor:card.trailingAnchor constant:4], // positioned outside the card
            [checkIcon.widthAnchor constraintEqualToConstant:28],
            [checkIcon.heightAnchor constraintEqualToConstant:28],
            
            [titleLabel.topAnchor constraintEqualToAnchor:card.topAnchor constant:12],
            [titleLabel.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:12],
            [titleLabel.trailingAnchor constraintLessThanOrEqualToAnchor:card.trailingAnchor constant:-12],
            
            [subtitleLabel.topAnchor constraintEqualToAnchor:titleLabel.bottomAnchor constant:4],
            [subtitleLabel.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:12],
            [subtitleLabel.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-12],
            [subtitleLabel.bottomAnchor constraintEqualToAnchor:card.bottomAnchor constant:-12]
        ]];
    }

    // --- Configure cell ---
    NSDictionary *issue = self.filteredIssues[indexPath.row];
    UILabel *titleLabel = [cell.contentView viewWithTag:200];
    UILabel *subtitleLabel = [cell.contentView viewWithTag:201];
    UIImageView *checkIcon = [cell.contentView viewWithTag:202];
    
    titleLabel.text = issue[@"location_name"];
    subtitleLabel.text = [NSString stringWithFormat:@"%@ → %@", issue[@"category"], issue[@"issue"]];
    
    BOOL isSelected = [self.selectedIssueIDs containsObject:issue[@"id"]];
    checkIcon.hidden = !isSelected;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *issue = self.filteredIssues[indexPath.row];
    NSString *issueID = issue[@"id"];
    
    if ([self.selectedIssueIDs containsObject:issueID]) {
        [self.selectedIssueIDs removeObject:issueID];
    } else {
        [self.selectedIssueIDs addObject:issueID];
    }
    [self updateCounter];
    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100; // adjust to your card height
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10; // spacing between cells
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *spacer = [[UIView alloc] init];
    spacer.backgroundColor = UIColor.clearColor;
    return spacer;
}

@end
