//  HistoryDetailsViewController.mm
#import "HistoryDetailsViewController.h"

@interface HistoryDetailsViewController ()

@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIButton *backButton;
@property (nonatomic, strong) UILabel *titleLabel;

@end

@implementation HistoryDetailsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.systemBackgroundColor;
  
    NSLog(@"📦 Received History Data: %@", self.itemData);
    NSString *plainText = [NSString stringWithFormat:@"%@", self.itemData];
    NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    NSString *filePath = [docsPath stringByAppendingPathComponent:@"pendingDetail.txt"];
    [plainText writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"📁 history details saved to %@", filePath);
    
    [self setupHeader];
    [self setupDetailContent];
}

#pragma mark - Header Setup
- (void)setupHeader {
  self.headerView = [[UIView alloc] init];
  self.headerView.backgroundColor = [UIColor colorWithRed:0.0 green:0.5 blue:0.6 alpha:1.0];
  self.headerView.translatesAutoresizingMaskIntoConstraints = NO;
  [self.view addSubview:self.headerView];
  
  self.backButton = [UIButton buttonWithType:UIButtonTypeCustom];
  [self.backButton setImage:[UIImage systemImageNamed:@"chevron.backward"]
                   forState:UIControlStateNormal];
  self.backButton.tintColor = UIColor.whiteColor;
  [self.backButton addTarget:self
                      action:@selector(onBack)
            forControlEvents:UIControlEventTouchUpInside];
  self.backButton.translatesAutoresizingMaskIntoConstraints = NO;
  [self.headerView addSubview:self.backButton];
  
  self.titleLabel = [[UILabel alloc] init];
  self.titleLabel.text = @"History";
  self.titleLabel.textColor = UIColor.whiteColor;
  self.titleLabel.font = [UIFont boldSystemFontOfSize:18];
  self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
  [self.headerView addSubview:self.titleLabel];
  
  [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:48],
    
    [self.backButton.leadingAnchor constraintEqualToAnchor:self.headerView.leadingAnchor constant:8],
    [self.backButton.centerYAnchor constraintEqualToAnchor:self.headerView.centerYAnchor],
    [self.backButton.widthAnchor constraintEqualToConstant:32],
    [self.backButton.heightAnchor constraintEqualToConstant:32],
    
    [self.titleLabel.centerXAnchor constraintEqualToAnchor:self.headerView.centerXAnchor],
    [self.titleLabel.centerYAnchor constraintEqualToAnchor:self.headerView.centerYAnchor],
  ]];
}

#pragma mark - Detail Content
- (void)setupDetailContent {
    UIScrollView *scroll = [[UIScrollView alloc] init];
    scroll.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:scroll];
    
    UIView *container = [[UIView alloc] init];
    container.translatesAutoresizingMaskIntoConstraints = NO;
    [scroll addSubview:container];
    
    [NSLayoutConstraint activateConstraints:@[
        [scroll.topAnchor constraintEqualToAnchor:self.headerView.bottomAnchor],
        [scroll.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [scroll.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [scroll.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor],
        
        [container.topAnchor constraintEqualToAnchor:scroll.topAnchor],
        [container.leadingAnchor constraintEqualToAnchor:scroll.leadingAnchor],
        [container.trailingAnchor constraintEqualToAnchor:scroll.trailingAnchor],
        [container.bottomAnchor constraintEqualToAnchor:scroll.bottomAnchor],
        [container.widthAnchor constraintEqualToAnchor:scroll.widthAnchor],
    ]];
    
    UIStackView *stack = [[UIStackView alloc] init];
    stack.axis = UILayoutConstraintAxisVertical;
    stack.spacing = 12;
    stack.translatesAutoresizingMaskIntoConstraints = NO;
    [container addSubview:stack];
    
    [NSLayoutConstraint activateConstraints:@[
        [stack.topAnchor constraintEqualToAnchor:container.topAnchor constant:16],
        [stack.leadingAnchor constraintEqualToAnchor:container.leadingAnchor constant:16],
        [stack.trailingAnchor constraintEqualToAnchor:container.trailingAnchor constant:-16],
        [stack.bottomAnchor constraintLessThanOrEqualToAnchor:container.bottomAnchor constant:-16],
    ]];
  
    UILabel *unitLabel = [[UILabel alloc] init];
    unitLabel.text = self.itemData[@"unitName"];
    unitLabel.font = [UIFont boldSystemFontOfSize:22];
    unitLabel.textColor = UIColor.labelColor;
    unitLabel.numberOfLines = 0;
    
    [stack addArrangedSubview:unitLabel];
    
    // spacing
    UIView *spacer = [[UIView alloc] init];
    [spacer.heightAnchor constraintEqualToConstant:12].active = YES;
    [stack addArrangedSubview:spacer];
  
    NSString *status = self.itemData[@"status"];
    UIColor *statusColor = [self colorForStatus:status];
    
    // Add rows
    [stack addArrangedSubview:[self makeRow:@"Created Date" value:self.itemData[@"createdOn"] color:nil]];
    [stack addArrangedSubview:[self makeRow:@"Created By" value:self.itemData[@"createdBy"] color:nil]];
    [stack addArrangedSubview:[self makeRow:@"Uploaded On" value:self.itemData[@"raw"][@"syncedAt"] color:statusColor]];
    [stack addArrangedSubview:[self makeRow:@"Action Made" value:self.itemData[@"type"] color:nil]];
    [stack addArrangedSubview:[self makeRow:@"Location" value:self.itemData[@"raw"][@"fieldNames"][@"locationName"] ?: @"-" color:nil]];
    [stack addArrangedSubview:[self makeRow:@"Category" value:self.itemData[@"raw"][@"category"][@"categoryName"] ?: @"-" color:nil]];
    [stack addArrangedSubview:[self makeRow:@"Type" value:self.itemData[@"raw"][@"type"][@"typeName"] color:nil]];
    [stack addArrangedSubview:[self makeRow:@"Issue" value:self.itemData[@"raw"][@"issueDisplay"][@"issueName"] ?: @"-" color:nil]];
    [stack addArrangedSubview:[self makeRow:@"Comment" value:self.itemData[@"raw"][@"remarks"] ?: @"-" color:nil]];
}


- (UIView *)makeRow:(NSString *)title
              value:(NSString *)value
              color:(UIColor *)color {

    UIView *row = [[UIView alloc] init];
    row.translatesAutoresizingMaskIntoConstraints = NO;

    UILabel *left = [[UILabel alloc] init];
    left.text = [NSString stringWithFormat:@"%@ :", title];
    left.font = [UIFont systemFontOfSize:15];
    left.textColor = UIColor.secondaryLabelColor;
    left.translatesAutoresizingMaskIntoConstraints = NO;

    UILabel *right = [[UILabel alloc] init];
    right.text = value ?: @"-";
    right.font = [UIFont systemFontOfSize:15 weight:UIFontWeightMedium];
    right.textColor = color ?: UIColor.labelColor;
    right.numberOfLines = 0;
    right.translatesAutoresizingMaskIntoConstraints = NO;

    [row addSubview:left];
    [row addSubview:right];

    [NSLayoutConstraint activateConstraints:@[
        [left.leadingAnchor constraintEqualToAnchor:row.leadingAnchor],
        [left.topAnchor constraintEqualToAnchor:row.topAnchor],
        [left.widthAnchor constraintEqualToConstant:120],

        [right.leadingAnchor constraintEqualToAnchor:left.trailingAnchor constant:8],
        [right.trailingAnchor constraintEqualToAnchor:row.trailingAnchor],
        [right.topAnchor constraintEqualToAnchor:row.topAnchor],
        [right.bottomAnchor constraintEqualToAnchor:row.bottomAnchor],
    ]];

    return row;
}

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

- (UIColor *)colorForStatus:(NSString *)status {
    if (!status) return UIColor.labelColor;

    if ([status isEqualToString:@"FAILED"]) {
        return [UIColor systemRedColor];
    }

    if ([status isEqualToString:@"SUCCESS"] ||
        [status isEqualToString:@"SYNCED"] ||
        [status isEqualToString:@"COMPLETED"]) {
        return [UIColor systemGreenColor];
    }

    return UIColor.labelColor;
}

@end
