//  HistoryViewController.mm

#import "HistoryViewController.h"
#import "HistoryAPIClient.h"

@interface HistoryViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIButton *backButton;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *addInfoButton;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *historyItems;
@property (nonatomic, strong) NSArray *sortedDates;
@property (nonatomic, strong) NSDictionary *groupedHistory;

@end

@implementation HistoryViewController

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

    [self setupHeader];
    [self setupTableView];
    [self handleIssues];
  
    NSLog(@"📦 Data received by History:\n issueID: %@\n planID: %@\n status: %@\n unitName: %@\n reference: %@",
        self.issueID,
        self.planID,
        self.status,
        self.unitName,
        self.reference);
}

#pragma mark - Header
- (void)setupHeader {
    self.headerView = [[UIView alloc] init];
    self.headerView.backgroundColor = [UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0];
    self.headerView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.headerView];

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

    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.text = @"Issue History";
    self.titleLabel.font = [UIFont boldSystemFontOfSize:18];
    self.titleLabel.textColor = UIColor.whiteColor;
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.headerView addSubview:self.titleLabel];

    self.addInfoButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.addInfoButton setImage:[UIImage systemImageNamed:@"plus"] forState:UIControlStateNormal];
    self.addInfoButton.tintColor = UIColor.whiteColor;
    self.addInfoButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.addInfoButton addTarget:self action:@selector(addInfoTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:self.addInfoButton];

    [NSLayoutConstraint activateConstraints:@[
        [self.headerView.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.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.addInfoButton.trailingAnchor constraintEqualToAnchor:self.headerView.trailingAnchor constant:-12],
        [self.addInfoButton.centerYAnchor constraintEqualToAnchor:self.headerView.centerYAnchor],

        [self.titleLabel.centerXAnchor constraintEqualToAnchor:self.headerView.centerXAnchor],
        [self.titleLabel.centerYAnchor constraintEqualToAnchor:self.headerView.centerYAnchor],
    ]];
}

#pragma mark - TableView
- (void)setupTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleInsetGrouped];
    self.tableView.translatesAutoresizingMaskIntoConstraints = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];

    [NSLayoutConstraint activateConstraints:@[
        [self.tableView.topAnchor constraintEqualToAnchor:self.headerView.bottomAnchor],
        [self.tableView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.tableView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.tableView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor],
    ]];
}

#pragma mark - API request/response
- (void)handleIssues {
    [HistoryAPIClient fetchHistory:self.issueID
                                    completion:^(NSDictionary *data, NSError *error) {
        if (error) {
            NSLog(@"❌ Error fetching history: %@", error);
            return;
        }

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

         // 🔸 Save raw JSON for debugging
         NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:NSJSONWritingPrettyPrinted error:nil];
         NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
         NSString *filePath = [docsPath stringByAppendingPathComponent:@"getHistory.txt"];
         [jsonData writeToFile:filePath atomically:YES];
         NSLog(@"📁 History saved to %@", filePath);

         NSDictionary *appData = data[@"AppData"];
         NSArray *mainData = data[@"Data"];

         // 1️⃣ Handle server error codes
         if (appData[@"error_code"] && [appData[@"error_code"] integerValue] == 503) {
             NSLog(@"⚠️ Maintenance mode");
             return;
         }

         // 2️⃣ Handle non-success responses
         NSString *status = appData[@"status"];
         if (![status isEqualToString:@"success"]) {
             NSString *msg = appData[@"message"] ?: @"Unknown server error.";
             NSLog(@"⚠️ Server error: %@", msg);
             return;
         }

         // 3️⃣ Success → process data
         if (mainData && [mainData isKindOfClass:[NSArray class]] && mainData.count > 0) {
             NSLog(@"✅ History data found (%lu items)", (unsigned long)mainData.count);

             NSMutableDictionary *grouped = [NSMutableDictionary dictionary];
             NSArray *reversed = [[mainData reverseObjectEnumerator] allObjects];
           
             for (NSDictionary *item in reversed) {
                 NSString *datePost = item[@"date_post"] ?: @"";
                 // Extract only date part ("02 Jul 2025")
                 NSArray *parts = [datePost componentsSeparatedByString:@","];
                 NSString *dateOnly = parts.count > 0 ? [parts.firstObject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] : @"Unknown Date";
                 
                 if (!grouped[dateOnly]) grouped[dateOnly] = [NSMutableArray array];
                 [grouped[dateOnly] addObject:item];
             }

             self.groupedHistory = grouped;
             self.sortedDates = [[grouped allKeys] sortedArrayUsingComparator:^NSComparisonResult(NSString *a, NSString *b) {
                 return [b compare:a options:NSNumericSearch]; // newest first
             }];

             dispatch_async(dispatch_get_main_queue(), ^{
                 [self.tableView reloadData];
             });
         } else {
             NSLog(@"⚠️ No history records found");
             dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"No Data, No history records found for this issue");
             });
         }
     }];
  }

#pragma mark - Table Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.sortedDates.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSString *dateKey = self.sortedDates[section];
    return [self.groupedHistory[dateKey] count];
}

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

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

        UIView *card = [[UIView alloc] init];
        card.tag = 100;
        card.layer.cornerRadius = 12;
        card.backgroundColor = UIColor.whiteColor;
        card.layer.shadowColor = [UIColor blackColor].CGColor;
        card.layer.shadowOpacity = 0.1;
        card.layer.shadowOffset = CGSizeMake(0, 1);
        card.layer.shadowRadius = 2;
        card.translatesAutoresizingMaskIntoConstraints = NO;
        [cell.contentView addSubview:card];

        UILabel *userLabel = [[UILabel alloc] init];
        userLabel.tag = 101;
        userLabel.font = [UIFont boldSystemFontOfSize:16];
        userLabel.translatesAutoresizingMaskIntoConstraints = NO;
        [card addSubview:userLabel];

        UILabel *remarkLabel = [[UILabel alloc] init];
        remarkLabel.tag = 102;
        remarkLabel.numberOfLines = 0;
        remarkLabel.font = [UIFont systemFontOfSize:14];
        remarkLabel.textColor = UIColor.darkGrayColor;
        remarkLabel.translatesAutoresizingMaskIntoConstraints = NO;
        [card addSubview:remarkLabel];

        UILabel *dateLabel = [[UILabel alloc] init];
        dateLabel.tag = 104;
        dateLabel.font = [UIFont italicSystemFontOfSize:12];
        dateLabel.textColor = [UIColor grayColor];
        dateLabel.translatesAutoresizingMaskIntoConstraints = NO;
        [card addSubview:dateLabel];

        UILabel *statusLabel = [[UILabel alloc] init];
        statusLabel.tag = 103;
        statusLabel.font = [UIFont systemFontOfSize:13 weight:UIFontWeightSemibold];
        statusLabel.textAlignment = NSTextAlignmentCenter;
        statusLabel.textColor = UIColor.whiteColor;
        statusLabel.layer.cornerRadius = 12;
        statusLabel.clipsToBounds = YES;
        statusLabel.translatesAutoresizingMaskIntoConstraints = NO;
        [card addSubview:statusLabel];

        UIScrollView *thumbScroll = [[UIScrollView alloc] init];
        thumbScroll.tag = 105;
        thumbScroll.showsHorizontalScrollIndicator = NO;
        thumbScroll.translatesAutoresizingMaskIntoConstraints = NO;
        [card addSubview:thumbScroll];
      
        UIView *timelineLine = [[UIView alloc] init];
        timelineLine.tag = 200;
        timelineLine.backgroundColor = [UIColor colorWithWhite:0.85 alpha:1];
        timelineLine.translatesAutoresizingMaskIntoConstraints = NO;
        [cell.contentView addSubview:timelineLine];

        UIView *circleNode = [[UIView alloc] init];
        circleNode.tag = 201;
        circleNode.backgroundColor = [UIColor blackColor];
        circleNode.layer.cornerRadius = 6;
        circleNode.translatesAutoresizingMaskIntoConstraints = NO;
        [cell.contentView addSubview:circleNode];

        UILabel *timeLabel = [[UILabel alloc] init];
        timeLabel.tag = 202;
        timeLabel.backgroundColor = [UIColor blackColor];
        timeLabel.textColor = [UIColor whiteColor];
        timeLabel.font = [UIFont boldSystemFontOfSize:12];
        timeLabel.textAlignment = NSTextAlignmentCenter;
        timeLabel.layer.cornerRadius = 10;
        timeLabel.clipsToBounds = YES;
        timeLabel.translatesAutoresizingMaskIntoConstraints = NO;
        [cell.contentView addSubview:timeLabel];

        [NSLayoutConstraint activateConstraints:@[
        [card.topAnchor constraintEqualToAnchor:cell.contentView.topAnchor constant:8],
        [card.leadingAnchor constraintEqualToAnchor:timelineLine.trailingAnchor constant:20],
        [card.trailingAnchor constraintEqualToAnchor:cell.contentView.trailingAnchor constant:-16],
        [card.bottomAnchor constraintEqualToAnchor:cell.contentView.bottomAnchor constant:-8],

        [userLabel.topAnchor constraintEqualToAnchor:card.topAnchor constant:12],
        [userLabel.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:12],

        [remarkLabel.topAnchor constraintEqualToAnchor:userLabel.bottomAnchor constant:6],
        [remarkLabel.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:12],
        [remarkLabel.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-12],

        [dateLabel.topAnchor constraintEqualToAnchor:remarkLabel.bottomAnchor constant:6],
        [dateLabel.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:12],

        [statusLabel.topAnchor constraintEqualToAnchor:dateLabel.bottomAnchor constant:10],
        [statusLabel.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:12],
        [statusLabel.widthAnchor constraintEqualToConstant:100],
        [statusLabel.heightAnchor constraintEqualToConstant:24],

        [thumbScroll.topAnchor constraintEqualToAnchor:statusLabel.bottomAnchor constant:10],
        [thumbScroll.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:12],
        [thumbScroll.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-12],
        [thumbScroll.heightAnchor constraintEqualToConstant:60],
        [thumbScroll.bottomAnchor constraintEqualToAnchor:card.bottomAnchor constant:-12],
        
        // Timeline line runs vertically through entire cell
        [timelineLine.widthAnchor constraintEqualToConstant:2],
        [card.leadingAnchor constraintEqualToAnchor:cell.contentView.leadingAnchor constant:80],
        [timelineLine.leadingAnchor constraintEqualToAnchor:cell.contentView.leadingAnchor constant:90],
        [timelineLine.topAnchor constraintEqualToAnchor:cell.contentView.topAnchor],
        [timelineLine.bottomAnchor constraintEqualToAnchor:cell.contentView.bottomAnchor],

        // Align the circle vertically with the card’s middle
        [circleNode.centerXAnchor constraintEqualToAnchor:timelineLine.centerXAnchor],
        [circleNode.centerYAnchor constraintEqualToAnchor:card.centerYAnchor],
        [circleNode.widthAnchor constraintEqualToConstant:12],
        [circleNode.heightAnchor constraintEqualToConstant:12],

        // Align time capsule left of circle
        [timeLabel.centerYAnchor constraintEqualToAnchor:circleNode.centerYAnchor],
        [timeLabel.trailingAnchor constraintEqualToAnchor:timelineLine.leadingAnchor constant:-8],
        [timeLabel.widthAnchor constraintEqualToConstant:70],
        [timeLabel.heightAnchor constraintEqualToConstant:22],
    ]];
  }

    NSString *dateKey = self.sortedDates[indexPath.section];
    NSArray *sectionItems = self.groupedHistory[dateKey];
    NSDictionary *item = sectionItems[indexPath.row];
    UILabel *userLabel = [cell viewWithTag:101];
    UILabel *remarkLabel = [cell viewWithTag:102];
    UILabel *statusLabel = [cell viewWithTag:103];
    UILabel *dateLabel = [cell viewWithTag:104];
    UIScrollView *thumbScroll = [cell viewWithTag:105];

    NSDictionary *user = item[@"user"];
    NSString *userName = [self safeString:user[@"name"]];
    NSString *remark = [self safeString:item[@"remarks"]];
    NSString *status = [self safeString:item[@"status_external"]];
    NSString *colorHex = [self safeString:item[@"status_ex_color"]];
    NSString *datePost = [self safeString:item[@"date_post"]];
    NSArray *images = item[@"image"];
    UILabel *timeLabel = [cell viewWithTag:202];

    // Extract the time portion after the comma
    NSString *timePart = @"";
    NSArray *parts = [datePost componentsSeparatedByString:@","];
    if (parts.count > 1) {
        timePart = [parts.lastObject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    }
    timeLabel.text = timePart.length > 0 ? timePart : @"--";

    userLabel.text = userName;
    remarkLabel.text = remark;
    dateLabel.text = datePost;
    statusLabel.text = status;
    statusLabel.backgroundColor = [self colorFromHex:colorHex ?: @"#888888"];

    // 🧹 Remove previous image views (since cells are reused)
    for (UIView *subview in thumbScroll.subviews) {
        [subview removeFromSuperview];
    }

    // 🖼️ Add thumbnails
    CGFloat x = 0;
    CGFloat imageSize = 56;
    CGFloat spacing = 8;

    for (NSDictionary *imgDict in images) {
        NSString *thumbURL = imgDict[@"thumb_image"];
        if (thumbURL.length == 0) continue;

        UIImageView *thumbView = [[UIImageView alloc] initWithFrame:CGRectMake(x, 0, imageSize, imageSize)];
        thumbView.layer.cornerRadius = 8;
        thumbView.layer.masksToBounds = YES;
        thumbView.contentMode = UIViewContentModeScaleAspectFill;
        thumbView.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];

        // Load async
        NSURL *url = [NSURL URLWithString:thumbURL];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSData *data = [NSData dataWithContentsOfURL:url];
            if (data) {
                UIImage *img = [UIImage imageWithData:data];
                dispatch_async(dispatch_get_main_queue(), ^{
                    thumbView.image = img;
                });
            }
        });

        [thumbScroll addSubview:thumbView];
        x += imageSize + spacing;
    }

    thumbScroll.contentSize = CGSizeMake(x, imageSize);

    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UILabel *label = [[UILabel alloc] init];
    label.text = self.sortedDates[section];
    label.font = [UIFont boldSystemFontOfSize:15];
    label.textColor = [UIColor darkGrayColor];
    label.backgroundColor = UIColor.clearColor;
    label.textAlignment = NSTextAlignmentLeft;
    return label;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30;
}


#pragma mark - Utils
- (UIColor *)colorFromHex:(NSString *)hex {
    unsigned int rgbValue = 0;
    NSScanner *scanner = [NSScanner scannerWithString:hex];
    if ([hex hasPrefix:@"#"]) scanner.scanLocation = 1;
    [scanner scanHexInt:&rgbValue];
    return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16)/255.0
                           green:((rgbValue & 0x00FF00) >> 8)/255.0
                            blue:(rgbValue & 0x0000FF)/255.0
                           alpha:1.0];
}

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

- (void)addInfoTapped {
    NSLog(@"➕ Add Info tapped");
}

#pragma mark - helper
- (NSString *)safeString:(id)value {
    if ([value isKindOfClass:[NSString class]]) return value;
    if ([value isKindOfClass:[NSNumber class]]) return [value stringValue];
    return @"–";
}

@end
