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

@interface HistoryDetailsViewController ()

@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIButton *backButton;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *shareButton;
@property (nonatomic, strong) NSArray<NSDictionary *> *itemsToShare; // <-- Add this

@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];
  
  self.shareButton = [UIButton buttonWithType:UIButtonTypeSystem];
  [self.shareButton setTitle:@"Share to Email" forState:UIControlStateNormal];
  [self.shareButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
  self.shareButton.layer.borderColor = UIColor.whiteColor.CGColor;
  self.shareButton.layer.borderWidth = 0.5;
  self.shareButton.layer.cornerRadius = 14;
  [self.shareButton addTarget:self
                      action:@selector(onShare)
            forControlEvents:UIControlEventTouchUpInside];
  self.shareButton.titleLabel.font = [UIFont systemFontOfSize:14];
  self.shareButton.translatesAutoresizingMaskIntoConstraints = NO;
  [self.headerView addSubview:self.shareButton];
  
  [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],
    
    [self.shareButton.trailingAnchor constraintEqualToAnchor:self.headerView.trailingAnchor constant:-16],
    [self.shareButton.centerYAnchor constraintEqualToAnchor:self.headerView.centerYAnchor],
    [self.shareButton.heightAnchor constraintEqualToConstant:28],
    [self.shareButton.widthAnchor constraintEqualToConstant:120],
  ]];
}

#pragma mark - Detail Content
- (void)setupDetailContent {
    // 1️⃣ Scroll view container
    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],
    ]];
    
    // 2️⃣ Stack view
    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],
    ]];
    
    // 3️⃣ Unit label
    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];
    
    // 4️⃣ Spacer
    UIView *spacer = [[UIView alloc] init];
    [spacer.heightAnchor constraintEqualToConstant:12].active = YES;
    [stack addArrangedSubview:spacer];
    
    // 5️⃣ Status color
    NSString *status = self.itemData[@"status"];
    UIColor *statusColor = [self colorForStatus:status];
    
    // 6️⃣ Helper block to safely get field values
    NSString *(^safeField)(NSString *) = ^NSString *(NSString *fieldName) {
        id fieldNames = self.itemData[@"raw"][@"fieldNames"];
        if ([fieldNames isKindOfClass:[NSDictionary class]]) {
            id value = fieldNames[fieldName];
            if ([value isKindOfClass:[NSString class]]) {
                return value;
            }
        }
        return @"-";
    };
    
    // 7️⃣ 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:safeField(@"locationName") color:nil]];
    [stack addArrangedSubview:[self makeRow:@"Category" value:safeField(@"categoryName") color:nil]];
    [stack addArrangedSubview:[self makeRow:@"Type" value:safeField(@"typeName") color:nil]];
    [stack addArrangedSubview:[self makeRow:@"Issue" value:safeField(@"issueName") color:nil]];
    [stack addArrangedSubview:[self makeRow:@"Comment" value:self.itemData[@"raw"][@"remarks"] ?: self.itemData[@"raw"][@"payload"][@"comment"] ?: @"-" 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;
}

- (NSArray<NSDictionary *> *)prepareItemsForSharing {
    NSMutableArray<NSDictionary *> *shareItems = [NSMutableArray array];

    // If you want to share a single item:
    if (self.itemData) {
        [shareItems addObject:self.itemData];
    }

    // Or, if you have multiple items stored in itemsToShare:
    if (self.itemsToShare.count > 0) {
        [shareItems addObjectsFromArray:self.itemsToShare];
    }

    return shareItems;
}

- (void)onShare {
    NSArray<NSDictionary *> *shareItems = [self prepareItemsForSharing];
    if (shareItems.count == 0) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"No items"
                                                                       message:@"There are no items to share."
                                                                preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:nil]];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }

    [SyncPendingShareHelper sharePendingItems:shareItems
                                fromController:self];
}

@end
