//  PendingDetailsViewController.mm
#import "PendingDetailsViewController.h"
#import <objc/runtime.h>
#import "OfflineSyncManager.h"
#import "SyncPendingShareHelper.h"

static const char kZoomViewKey = 0;

@interface PendingDetailsViewController () <UIScrollViewDelegate>

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

@end

@implementation PendingDetailsViewController

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

    NSLog(@"📦 Received Pending 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(@"📁 pending 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 = @"Pending Items";
  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 {
    UIScrollView *scroll = [[UIScrollView alloc] init];
    scroll.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:scroll];
    
    UIView *container = [[UIView alloc] init];
    container.translatesAutoresizingMaskIntoConstraints = NO;
    [scroll addSubview:container];
    
    // Scroll & container constraints
    [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],
    ]];
    
    // 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];
    
    // Spacer
    UIView *spacer = [[UIView alloc] init];
    [spacer.heightAnchor constraintEqualToConstant:12].active = YES;
    [stack addArrangedSubview:spacer];
    
    // Add all info rows
    [stack addArrangedSubview:[self makeRow:@"Created Date" value:self.itemData[@"createdAt"]]];
    [stack addArrangedSubview:[self makeRow:@"Created By" value:self.itemData[@"createdBy"]]];
    [stack addArrangedSubview:[self makeRow:@"Action Made" value:self.itemData[@"issueDisplay"]]];
    [stack addArrangedSubview:[self makeRow:@"Location" value:self.itemData[@"fieldNames"][@"locationName"] ?: @"-"]];
    [stack addArrangedSubview:[self makeRow:@"Category" value:self.itemData[@"fieldNames"][@"categoryName"] ?: @"-"]];
    [stack addArrangedSubview:[self makeRow:@"Type" value:self.itemData[@"fieldNames"][@"typeName"] ?: @"-"]];
    [stack addArrangedSubview:[self makeRow:@"Issue" value:self.itemData[@"fieldNames"][@"issueName"] ?: @"-"]];
    [stack addArrangedSubview:[self makeRow:@"Comment" value:self.itemData[@"payload"][@"comment"] ?: @"-"]];
    [stack addArrangedSubview:[self makeRow:@"Timestamp" value:self.itemData[@"timestamp"] ?: @"-"]];
    
    // Image + delete button
    NSArray *imagePaths = self.itemData[@"imagePaths"];
    if ([imagePaths isKindOfClass:[NSArray class]] && imagePaths.count > 0) {
        NSString *path = imagePaths.firstObject;

        NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
        NSString *fileName = [path lastPathComponent];
        NSString *fullPath = [docsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"offline_files/%@", fileName]];

        NSLog(@"📁 Loading image from %@", fullPath);

        if ([[NSFileManager defaultManager] fileExistsAtPath:fullPath]) {
            UIImage *image = [UIImage imageWithContentsOfFile:fullPath];
            if (image) {
                UIButton *viewImageButton = [UIButton buttonWithType:UIButtonTypeSystem];
                [viewImageButton setTitle:@"View Image" forState:UIControlStateNormal];
                viewImageButton.titleLabel.font = [UIFont boldSystemFontOfSize:16];
                viewImageButton.tintColor = [UIColor colorWithRed:0.0 green:0.5 blue:0.6 alpha:1.0]; // same as delete
                viewImageButton.layer.borderWidth = 0.5;
                viewImageButton.layer.cornerRadius = 8;
                viewImageButton.layer.borderColor = [UIColor colorWithRed:0.0 green:0.5 blue:0.6 alpha:1.0].CGColor;
                viewImageButton.translatesAutoresizingMaskIntoConstraints = NO;
                [viewImageButton.heightAnchor constraintEqualToConstant:44].active = YES; // match delete height

                // store image path for tap handler
                viewImageButton.accessibilityLabel = fullPath;
                [viewImageButton addTarget:self action:@selector(onViewImageButtonTapped:) forControlEvents:UIControlEventTouchUpInside];

                [stack addArrangedSubview:viewImageButton];
            } else {
                NSLog(@"❌ Failed to load UIImage from path");
            }
        } else {
            NSLog(@"❌ File does not exist at path");
        }
    }

    // Delete button
    UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [deleteButton setTitle:@"Delete Item" forState:UIControlStateNormal];
    deleteButton.tintColor = [UIColor colorWithRed:0.0 green:0.5 blue:0.6 alpha:1.0];
    deleteButton.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    deleteButton.layer.borderWidth = 0.5;
    deleteButton.layer.cornerRadius = 8;
    deleteButton.layer.borderColor = [UIColor colorWithRed:0.0 green:0.5 blue:0.6 alpha:1.0].CGColor;
    [deleteButton addTarget:self action:@selector(onDeleteItem) forControlEvents:UIControlEventTouchUpInside];
    [stack addArrangedSubview:deleteButton];
}

- (UIView *)makeRow:(NSString *)title
              value:(id)value {
  
    NSString *displayValue = @"-";

    if ([value isKindOfClass:[NSString class]]) {
        displayValue = value;
    }
    else if ([value isKindOfClass:[NSNumber class]]) {
        displayValue = [value stringValue];
    }
    else if ([value isKindOfClass:[NSNull class]] || value == nil) {
        displayValue = @"-";
    }

    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 = displayValue ?: @"-";
    right.font = [UIFont systemFontOfSize:15 weight:UIFontWeightMedium];
    right.textColor = 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];
}

- (void)closeFullImage {
    UIView *overlay = [self.view viewWithTag:900];
    if (!overlay) return;

    [UIView animateWithDuration:0.25 animations:^{
        overlay.alpha = 0;
    } completion:^(BOOL finished) {
        [overlay removeFromSuperview];
    }];
}

- (void)onDeleteItem {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Delete Item"
                                                                   message:@"Are you sure you want to delete this pending item?"
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"Delete" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        [self deletePendingItem];
    }]];
    
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)deletePendingItem {
    NSString *itemID = self.itemData[@"id"];
    if (!itemID) return;

    NSMutableArray *queue = [[OfflineSyncManager shared] safeLoadQueue]; // load current queue

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"id != %@", itemID];
    NSArray *filtered = [queue filteredArrayUsingPredicate:predicate];
    [[OfflineSyncManager shared] saveQueue:[filtered mutableCopy]];

    NSLog(@"📤 Deleted pending item %@", itemID);

    // Close this screen after deletion
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)onShare {
    NSArray<NSDictionary *> *itemsToShare = [self prepareItemsForSharing];
    
    if (itemsToShare.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:itemsToShare
                                fromController:self];
}

- (NSArray<NSDictionary *> *)prepareItemsForSharing {
    if (!self.itemData) return @[];
    
    return @[
        @{
            @"unitName": self.itemData[@"unitName"] ?: @"",
            @"createdBy": self.itemData[@"createdBy"] ?: @"",
            @"createdOn": self.itemData[@"createdOn"] ?: @"",
            @"type": self.itemData[@"issueDisplay"] ?: @"",
            @"fieldNames": self.itemData[@"fieldNames"] ?: @{},
            @"payload": self.itemData[@"payload"] ?: @{},
            @"timestamp": self.itemData[@"timestamp"] ?: @"",
            @"imagePaths": self.itemData[@"imagePaths"] ?: @[]
        }
    ];
}

- (void)onViewImageButtonTapped:(UIButton *)sender {
    NSString *fullPath = sender.accessibilityLabel;
    UIImage *image = [UIImage imageWithContentsOfFile:fullPath];
    if (!image) return;

    // show full-screen overlay directly
    UIView *overlay = [[UIView alloc] initWithFrame:self.view.bounds];
    overlay.backgroundColor = [UIColor colorWithWhite:0 alpha:0.95];
    overlay.alpha = 0;
    overlay.tag = 900;
    overlay.userInteractionEnabled = YES;
    [self.view addSubview:overlay];

    UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:overlay.bounds];
    scroll.minimumZoomScale = 1.0;
    scroll.maximumZoomScale = 4.0;
    scroll.delegate = self;
    scroll.showsHorizontalScrollIndicator = NO;
    scroll.showsVerticalScrollIndicator = NO;
    [overlay addSubview:scroll];

    UIImageView *fullImageView = [[UIImageView alloc] initWithFrame:scroll.bounds];
    fullImageView.image = image;
    fullImageView.contentMode = UIViewContentModeScaleAspectFit;
    fullImageView.userInteractionEnabled = YES;
    [scroll addSubview:fullImageView];

    objc_setAssociatedObject(scroll, &kZoomViewKey, fullImageView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

    UITapGestureRecognizer *dismissTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeFullImage)];
    [overlay addGestureRecognizer:dismissTap];

    [UIView animateWithDuration:0.25 animations:^{
        overlay.alpha = 1;
    }];
}


@end
