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

#pragma mark - Internal IssueCell
@interface IssueCell : 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;
@end

@implementation IssueCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        self.backgroundColor = UIColor.whiteColor;
        
        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];
        
        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];
        
        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];
        
        [NSLayoutConstraint activateConstraints:@[
            [card.topAnchor constraintEqualToAnchor:self.contentView.topAnchor constant:6],
            [card.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:10],
            [card.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-10],
            [card.bottomAnchor constraintEqualToAnchor:self.contentView.bottomAnchor constant:-6],
            
            [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;
}

@end


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

@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIButton *backButton;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *withdrawButton;
@property (nonatomic, strong) UIButton *filterButton;
@property (nonatomic, strong) UILabel *filterLabel;
@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *issues;
@property (nonatomic, strong) NSDictionary *issueResponse;
@property (nonatomic, strong) NSString *selectedFilter;
@property (nonatomic, strong) NSArray<NSDictionary *> *groupedIssues;
@property (nonatomic, strong) NSString *searchText;
@property (nonatomic, strong) NSArray *filteredIssues;
@property (nonatomic, strong) NSArray *filteredGroupedIssues;

@end

@implementation IssuesViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self setupHeader];
    [self setupFilterBar];
    [self setupSearchBar];
    [self setupTableView];
    self.tableView.sectionHeaderTopPadding = 0; // Optional, iOS 15+ removes top gap
    self.tableView.sectionHeaderHeight = 34;
    self.tableView.estimatedSectionHeaderHeight = 34;
    [self setupConstraints];
    [self handleGetIssue];
  
    self.selectedFilter = @"All";
}

#pragma mark - Setup UI
- (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.0 green:0.43 blue:0.55 alpha:1.0]; // THEME COLOR
    [self.view addSubview:self.headerView];
    
    // Back Button
    self.backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.backButton setImage:[UIImage systemImageNamed:@"chevron.left"] forState:UIControlStateNormal];
    self.backButton.tintColor = UIColor.whiteColor;
    self.backButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.backButton addTarget:self action:@selector(backTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:self.backButton];
    
    // Title
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.text = @"Issues";
    self.titleLabel.textColor = UIColor.whiteColor;
    self.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.headerView addSubview:self.titleLabel];
    
    // Withdraw Button
    self.withdrawButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.withdrawButton setImage:[UIImage systemImageNamed:@"checklist.checked"] forState:UIControlStateNormal];
    self.withdrawButton.tintColor = UIColor.whiteColor;
    self.withdrawButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.withdrawButton addTarget:self action:@selector(withdrawTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:self.withdrawButton];
}

- (void)setupFilterBar {
    self.filterButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.filterButton.translatesAutoresizingMaskIntoConstraints = NO;
    self.filterButton.layer.cornerRadius = 20;
    self.filterButton.layer.borderWidth = 0.5;
    self.filterButton.layer.borderColor = [UIColor lightGrayColor].CGColor;
    [self.filterButton setTitle:@"Filter: All" forState:UIControlStateNormal];
    [self.filterButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.filterButton.tintColor = UIColor.labelColor;
    self.filterButton.backgroundColor = UIColor.whiteColor;
    self.filterButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.filterButton addTarget:self action:@selector(filterTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.filterButton];
}

- (void)setupSearchBar {
    self.searchBar = [[UISearchBar alloc] init];
    self.searchBar.placeholder = @"Search by reference...";
    self.searchBar.translatesAutoresizingMaskIntoConstraints = NO;
    self.searchBar.delegate = self;
    self.searchBar.autocapitalizationType = UITextAutocapitalizationTypeNone;
    self.searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
    self.searchBar.returnKeyType = UIReturnKeyDone;
    self.searchBar.showsCancelButton = YES;
    self.searchBar.barTintColor = [UIColor whiteColor];
    self.searchBar.backgroundImage = [UIImage new];
    self.searchBar.opaque = YES;
    
    // ✅ Customize the internal text field
    UITextField *textField = [self.searchBar valueForKey:@"searchField"];
    if (textField) {
        textField.textColor = [UIColor blackColor];
        textField.tintColor = [UIColor darkGrayColor];
        textField.backgroundColor = [UIColor whiteColor];
        
        textField.layer.borderColor = [UIColor lightGrayColor].CGColor;
        textField.layer.borderWidth = 1.0;
        textField.layer.cornerRadius = 8.0;
        textField.clipsToBounds = YES;
        
        textField.attributedPlaceholder = [[NSAttributedString alloc]
            initWithString:self.searchBar.placeholder
                attributes:@{NSForegroundColorAttributeName: [UIColor grayColor]}];
    }
  
    UIButton *cancelButton = [self.searchBar valueForKey:@"cancelButton"];
    if (cancelButton) {
        [cancelButton setTitleColor:[UIColor systemBlueColor] forState:UIControlStateNormal];
        [cancelButton setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
        cancelButton.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    }

    [self.view addSubview:self.searchBar];
}

- (void)setupTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleInsetGrouped];
    self.tableView.translatesAutoresizingMaskIntoConstraints = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundView = nil;
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.opaque = YES;
    [self.tableView registerClass:[IssueCell class] forCellReuseIdentifier:@"IssueCell"];
    
    // 🔹 Section header behavior
    if (@available(iOS 15.0, *)) {
        self.tableView.sectionHeaderTopPadding = 0;
    }
    self.tableView.sectionHeaderHeight = 34;
    self.tableView.estimatedSectionHeaderHeight = 34;

    [self.view addSubview:self.tableView];
}

- (void)setupConstraints {
    UILayoutGuide *guide = self.view.safeAreaLayoutGuide;
    
    [NSLayoutConstraint activateConstraints:@[
        // Header
        [self.headerView.topAnchor constraintEqualToAnchor:guide.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:12],
        [self.backButton.centerYAnchor constraintEqualToAnchor:self.headerView.centerYAnchor],
        [self.titleLabel.centerXAnchor constraintEqualToAnchor:self.headerView.centerXAnchor],
        [self.titleLabel.centerYAnchor constraintEqualToAnchor:self.headerView.centerYAnchor],
        [self.withdrawButton.trailingAnchor constraintEqualToAnchor:self.headerView.trailingAnchor constant:-12],
        [self.withdrawButton.centerYAnchor constraintEqualToAnchor:self.headerView.centerYAnchor],
        
        // Filter
        [self.filterButton.topAnchor constraintEqualToAnchor:self.headerView.bottomAnchor constant:12],
        [self.filterButton.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:16],
        [self.filterButton.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:-16],
        [self.filterButton.heightAnchor constraintEqualToConstant:40],
        
        // Search
        [self.searchBar.topAnchor constraintEqualToAnchor:self.filterButton.bottomAnchor constant:8],
        [self.searchBar.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.searchBar.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        
        // Table
        [self.tableView.topAnchor constraintEqualToAnchor:self.searchBar.bottomAnchor constant:8],
        [self.tableView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.tableView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.tableView.bottomAnchor constraintEqualToAnchor:guide.bottomAnchor],
    ]];
}

#pragma mark - Networking
- (void)handleGetIssue {
    NSLog(@"🌐 Fetching Issue data...");

    [IssueAPIClient fetchIssues:^(NSDictionary *data, NSError *error) {
        if (error) {
            NSLog(@"❌ Issue fetch failed: %@", error.localizedDescription);
            return;
        }

        NSLog(@"✅ Raw Issue response received");

        // Save response to Documents for inspection
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:NSJSONWritingPrettyPrinted error:nil];
        NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
        NSString *filePath = [docsPath stringByAppendingPathComponent:@"getIssue.txt"];
        [jsonData writeToFile:filePath atomically:YES];
        NSLog(@"📁 Issue saved to %@", filePath);
      
        // 🔹 Save the full API response
        self.issueResponse = data;

        // 🔍 Parse JSON
        NSDictionary *appData = data[@"AppData"];
        if (![appData[@"status"] isEqualToString:@"success"]) {
            NSLog(@"⚠️ Server returned non-success status: %@", appData[@"message"]);
            return;
        }

        NSArray *mainData = data[@"Data"];
        if (mainData.count == 0) {
            NSLog(@"⚠️ No unit plan data found");
            return;
        }
      
        // 🔹 Sort by date (latest first)
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"dd/MM/yyyy";
        NSArray *sorted = [mainData sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *a, NSDictionary *b) {
             NSDate *dA = [formatter dateFromString:a[@"created_at"] ?: @""];
             NSDate *dB = [formatter dateFromString:b[@"created_at"] ?: @""];
             return [dB compare:dA]; // newest → oldest
           }];

         self.issues = sorted;

         // ✅ Reload UI on main thread
         dispatch_async(dispatch_get_main_queue(), ^{
             [self.tableView reloadData];
         });

         NSLog(@"✅ Issues loaded: %lu", (unsigned long)self.issues.count);
     }];
}

#pragma mark - search bar
- (void)applySearch:(NSString *)searchValue {
    if (searchValue.length == 0) {
        self.filteredIssues = nil;
        self.filteredGroupedIssues = nil;
        [self.tableView reloadData];
        return;
    }

    NSString *search = [searchValue uppercaseString];
    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];
        }
    }

    // 🧩 If user is filtering by Status/Location/Date → regroup
    if (![self.selectedFilter isEqualToString:@"All"]) {
        NSMutableDictionary<NSString *, NSMutableArray *> *map = [NSMutableDictionary dictionary];
        for (NSDictionary *issue in matches) {
            NSString *key = @"";
            if ([self.selectedFilter isEqualToString:@"Status"]) {
                key = issue[@"status_external"] ?: @"(No Status)";
            } else if ([self.selectedFilter isEqualToString:@"Location"]) {
                key = issue[@"location_name"] ?: @"(No Location)";
            } else if ([self.selectedFilter isEqualToString:@"Date"]) {
                key = issue[@"created_at"] ?: @"(No Date)";
            }
            if (!map[key]) map[key] = [NSMutableArray array];
            [map[key] addObject:issue];
        }

        NSArray *sortedKeys;
        if ([self.selectedFilter isEqualToString:@"Date"]) {
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"dd/MM/yyyy";
            sortedKeys = [[map allKeys] sortedArrayUsingComparator:^NSComparisonResult(NSString *a, NSString *b) {
                NSDate *dA = [formatter dateFromString:a];
                NSDate *dB = [formatter dateFromString:b];
                return [dB compare:dA]; // newest first
            }];
        } else {
            sortedKeys = [[map allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
        }

        NSMutableArray *grouped = [NSMutableArray array];
        for (NSString *key in sortedKeys) {
            [grouped addObject:@{ @"title": key, @"data": map[key] }];
        }

        self.filteredGroupedIssues = grouped;
        self.filteredIssues = nil;
    } else {
        self.filteredIssues = matches;
        self.filteredGroupedIssues = nil;
    }

    [self.tableView reloadData];
}

#pragma mark - Actions

- (void)backTapped {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)withdrawTapped {
    NSLog(@"Withdraw button tapped");
  
    WithdrawIssuesViewController *withdrawVC = [[WithdrawIssuesViewController alloc] init];
    withdrawVC.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:withdrawVC animated:YES completion:nil];
}

# pragma mark - Filter
- (void)filterTapped {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Filter By"
                                                                   message:nil
                                                            preferredStyle:UIAlertControllerStyleActionSheet];
    
    NSArray *filters = @[@"All", @"Status", @"Location", @"Date"];
    for (NSString *filter in filters) {
        UIAlertAction *action = [UIAlertAction actionWithTitle:filter
                                                         style:UIAlertActionStyleDefault
                                                       handler:^(UIAlertAction * _Nonnull action) {
            [self applyFilter:filter];
        }];
        [alert addAction:action];
    }

    [alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)applyFilter:(NSString *)filter {
    self.selectedFilter = filter;

    if ([filter isEqualToString:@"All"]) {
        self.groupedIssues = @[]; // Flat mode
    } else {
        NSMutableArray *groups = [NSMutableArray array];
        NSMutableDictionary<NSString *, NSMutableArray *> *map = [NSMutableDictionary dictionary];

        for (NSDictionary *issue in self.issues) {
            NSString *key = @"";
            if ([filter isEqualToString:@"Status"]) {
                key = issue[@"status_external"] ?: @"(No Status)";
            } else if ([filter isEqualToString:@"Location"]) {
                key = issue[@"location_name"] ?: @"(No Location)";
            } else if ([filter isEqualToString:@"Date"]) {
                key = issue[@"created_at"] ?: @"(No Date)";
            }

            if (!map[key]) {
                map[key] = [NSMutableArray array];
            }
            [map[key] addObject:issue];
        }

        NSArray *sortedKeys;

        if ([filter isEqualToString:@"Date"]) {
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"dd/MM/yyyy";
            sortedKeys = [[map allKeys] sortedArrayUsingComparator:^NSComparisonResult(NSString *a, NSString *b) {
                NSDate *dA = [formatter dateFromString:a];
                NSDate *dB = [formatter dateFromString:b];
                return [dB compare:dA]; // newest → oldest
            }];
        } else if ([filter isEqualToString:@"Status"] || [filter isEqualToString:@"Location"]) {
            sortedKeys = [[map allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
        } else {
            sortedKeys = [map allKeys];
        }

        for (NSString *key in sortedKeys) {
            [groups addObject:@{
                @"title": key,
                @"data": map[key]
            }];
        }

        self.groupedIssues = groups;
    }

    // 🔹 Update the filter button title dynamically
    NSString *buttonTitle = [NSString stringWithFormat:@"Filter: %@", filter];
    [self.filterButton setTitle:buttonTitle forState:UIControlStateNormal];

    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
    });
}


- (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];
}

#pragma mark - TableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // If user is searching:
    if (self.filteredIssues || self.filteredGroupedIssues) {
        if (self.filteredGroupedIssues) return self.filteredGroupedIssues.count;
        return 1;
    }
    // Otherwise, normal mode
    if ([self.selectedFilter isEqualToString:@"All"]) return 1;
    return self.groupedIssues.count;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    // Hide default iOS header text (we use a custom header view below)
    return nil;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.filteredIssues) return self.filteredIssues.count;
    if (self.filteredGroupedIssues) {
        NSArray *rows = self.filteredGroupedIssues[section][@"data"];
        return rows.count;
    }

    if ([self.selectedFilter isEqualToString:@"All"]) return self.issues.count;
    NSArray *rows = self.groupedIssues[section][@"data"];
    return rows.count;
}

- (NSDictionary *)issueAtIndexPath:(NSIndexPath *)indexPath {
    if (self.filteredIssues) return self.filteredIssues[indexPath.row];
    if (self.filteredGroupedIssues) return self.filteredGroupedIssues[indexPath.section][@"data"][indexPath.row];
    if ([self.selectedFilter isEqualToString:@"All"]) return self.issues[indexPath.row];
    return self.groupedIssues[indexPath.section][@"data"][indexPath.row];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    IssueCell *cell = [tableView dequeueReusableCellWithIdentifier:@"IssueCell" forIndexPath:indexPath];
    
    // --- Reset reused cell state ---
    cell.thumbView.image = nil;
    for (UIView *subview in cell.thumbView.subviews) {
        [subview removeFromSuperview];
    }

    NSDictionary *issue = [self issueAtIndexPath:indexPath];

    NSString *reference = issue[@"reference"] ?: @"";
    NSString *location = issue[@"location_name"] ?: @"";
    NSString *createdAt = issue[@"created_at"] ?: @"";
    NSString *category = issue[@"category"] ?: @"";
    NSString *type = issue[@"type"] ?: @"";
    NSString *issueText = issue[@"issue"] ?: @"";
    NSString *status = issue[@"status_external"] ?: @"";
    NSString *statusColor = issue[@"status_ex_color"] ?: @"#CCCCCC";
    NSString *thumbURL = issue[@"thumb_image"] ?: @"";

    cell.referenceLabel.text = reference;
    cell.locationLabel.text = location;
    cell.createdLabel.text = [NSString stringWithFormat:@"Created on %@", createdAt];
    cell.detailsLabel.text = [NSString stringWithFormat:@"%@ → %@ → %@", category, type, issueText];
    cell.statusLabel.text = status;
    cell.statusLabel.backgroundColor = [self colorFromHexString:statusColor];
    cell.backgroundColor = UIColor.clearColor;
    cell.contentView.backgroundColor = UIColor.whiteColor;

    // --- Thumbnail Handling ---
    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(), ^{
                IssueCell *updateCell = [tableView cellForRowAtIndexPath:indexPath];
                if (!updateCell) return;

                // Clear any "No image" 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];
    }

    return cell;
}

#pragma mark - Custom Section Header

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    NSArray *sourceGroups = self.filteredGroupedIssues ?: self.groupedIssues;
    if ([self.selectedFilter isEqualToString:@"All"] && !self.filteredGroupedIssues) return nil;
    if (section >= sourceGroups.count) return nil;

    NSDictionary *group = sourceGroups[section];
    NSString *title = group[@"title"] ?: @"";

    UIView *headerView = [[UIView alloc] init];
    headerView.backgroundColor = [UIColor colorWithWhite:0.94 alpha:1.0];

    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    titleLabel.font = [UIFont boldSystemFontOfSize:17];
    titleLabel.textColor = [UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0]; // theme color
    titleLabel.text = title.uppercaseString;

    UIView *underline = [[UIView alloc] init];
    underline.backgroundColor = [UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:0.6];
    underline.translatesAutoresizingMaskIntoConstraints = NO;

    [headerView addSubview:titleLabel];
    [headerView addSubview:underline];

    [NSLayoutConstraint activateConstraints:@[
        [titleLabel.leadingAnchor constraintEqualToAnchor:headerView.leadingAnchor constant:16],
        [titleLabel.bottomAnchor constraintEqualToAnchor:headerView.bottomAnchor constant:-6],
        [underline.leadingAnchor constraintEqualToAnchor:headerView.leadingAnchor constant:16],
        [underline.trailingAnchor constraintEqualToAnchor:headerView.trailingAnchor constant:-16],
        [underline.bottomAnchor constraintEqualToAnchor:headerView.bottomAnchor],
        [underline.heightAnchor constraintEqualToConstant:1],
    ]];

    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if ([self.selectedFilter isEqualToString:@"All"] && !self.filteredGroupedIssues) return 0;
    return 34;
}

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

#pragma mark - Helpers
- (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]
    ]];
}

#pragma mark - TableView Delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *issue;

    if ([self.selectedFilter isEqualToString:@"All"]) {
        issue = self.issues[indexPath.row];
    } else {
        issue = self.groupedIssues[indexPath.section][@"data"][indexPath.row];
    }

    IssueDetailViewController *detailVC = [[IssueDetailViewController alloc] init];
    detailVC.modalPresentationStyle = UIModalPresentationFullScreen;
    detailVC.issueData = issue; // Pass the selected data

    NSLog(@"🧭 Navigating to IssueDetailsViewController with issue: %@", issue);

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

#pragma mark - UISearchBarDelegate
-(void)searchbar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
  [self applySearch:searchText];
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
  [searchBar resignFirstResponder];
  [self applySearch:searchBar.text];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    // Optional: reset search when user cancels
    [searchBar resignFirstResponder];
    searchBar.text = @"";
    [self applySearch:@""];
}

@end
