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

static const char kZoomViewKey = 0;

@interface PendingDetailsViewController () <UIScrollViewDelegate>

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

@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];
  
  [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];
    
    // 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) {
                UIImageView *thumb = [[UIImageView alloc] initWithImage:image];
                thumb.contentMode = UIViewContentModeScaleAspectFill;
                thumb.clipsToBounds = YES;
                thumb.layer.cornerRadius = 8;
                thumb.userInteractionEnabled = YES;
                thumb.translatesAutoresizingMaskIntoConstraints = NO;
                [thumb.heightAnchor constraintEqualToConstant:120].active = YES;
                UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleImageTap:)];
                [thumb addGestureRecognizer:tap];
                thumb.accessibilityLabel = fullPath;
                [stack addArrangedSubview:thumb];
            } 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.systemRedColor;
    deleteButton.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    [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)handleImageTap:(UITapGestureRecognizer *)sender {
    UIImageView *tappedImageView = (UIImageView *)sender.view;
    if (!tappedImageView.image) return;

    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 = tappedImageView.image;
    fullImageView.contentMode = UIViewContentModeScaleAspectFit;
    fullImageView.userInteractionEnabled = YES;
    [scroll addSubview:fullImageView];

    // ✅ store reference for zooming
    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;
    }];
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return (UIImageView *)objc_getAssociatedObject(scrollView, &kZoomViewKey);
}

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

@end
