// IssueDetailsViewController.mm

#import "IssueDetailViewController.h"
#import "HistoryViewController.h"
#import "PlanViewController.h"
#import "WithdrawSingleIssueViewController.h"
#import "ImageCacheHelper.h"

@interface IssueDetailViewController () <UIScrollViewDelegate>

@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UIImageView *issueImageView;
@property (nonatomic, strong) UILabel *refLabel;
@property (nonatomic, strong) UILabel *statusLabel;

@property (nonatomic, strong) UIView *detailsCard;
@property (nonatomic, strong) UIButton *editButton;
@property (nonatomic, strong) UIButton *deleteButton;
@property (nonatomic, strong) UIImageView *floorPlanThumbnail;

@end

@implementation IssueDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"Issue Details";

    NSLog(@"📦 navigated to issueDetailViewController with:\n self.projectName=%@\n self.projectCode=%@",
          self.projectCode, self.projectName);
  
    [self setupHeader];
    [self setupScrollView];
    [self setupHeaderImage];
    [self setupDetailsCard];
    [self setupButtons];
    [self populateData];
}

#pragma mark - Header Setup
- (void)setupHeader {
    self.headerView = [[UIView alloc] init];
    self.headerView.translatesAutoresizingMaskIntoConstraints = NO;
    self.headerView.backgroundColor = [UIColor colorWithRed:0/255.0
                                                      green:109/255.0
                                                       blue:141/255.0
                                                      alpha:1.0];
    [self.view addSubview:self.headerView];

    [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.bottomAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor constant:44],
    ]];


    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    backButton.translatesAutoresizingMaskIntoConstraints = NO;
    [backButton setImage:[UIImage systemImageNamed:@"chevron.left"] forState:UIControlStateNormal];
    backButton.tintColor = UIColor.whiteColor;
    [backButton addTarget:self action:@selector(handleBackTap) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:backButton];
    
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    titleLabel.text = @"Issue Details";
    titleLabel.textColor = UIColor.whiteColor;
    titleLabel.font = [UIFont boldSystemFontOfSize:15];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.headerView addSubview:titleLabel];
    
    UIButton *historyButton = [UIButton buttonWithType:UIButtonTypeSystem];
    historyButton.translatesAutoresizingMaskIntoConstraints = NO;
    [historyButton setImage:[UIImage systemImageNamed:@"clock"] forState:UIControlStateNormal];
    historyButton.tintColor = UIColor.whiteColor;
    [historyButton addTarget:self action:@selector(handleHistoryTap) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:historyButton];

    [NSLayoutConstraint activateConstraints:@[
        // Back button
        [backButton.leadingAnchor constraintEqualToAnchor:self.headerView.leadingAnchor constant:16],
        [backButton.centerYAnchor constraintEqualToAnchor:self.headerView.centerYAnchor],
        [backButton.widthAnchor constraintEqualToConstant:20],
        [backButton.heightAnchor constraintEqualToConstant:20],

        // Title
        [titleLabel.centerXAnchor constraintEqualToAnchor:self.headerView.centerXAnchor],
        [titleLabel.centerYAnchor constraintEqualToAnchor:self.headerView.centerYAnchor],

        // Right button
        [historyButton.trailingAnchor constraintEqualToAnchor:self.headerView.trailingAnchor constant:-16],
        [historyButton.centerYAnchor constraintEqualToAnchor:self.headerView.centerYAnchor],
        [historyButton.widthAnchor constraintEqualToConstant:20],
        [historyButton.heightAnchor constraintEqualToConstant:20],
    ]];
}

#pragma mark - UI Setup

- (void)setupScrollView {
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.scrollView];

    self.contentView = [[UIView alloc] init];
    self.contentView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.scrollView addSubview:self.contentView];

    [NSLayoutConstraint activateConstraints:@[
        // ScrollView
        [self.scrollView.topAnchor constraintEqualToAnchor:self.headerView.bottomAnchor],
        [self.scrollView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.scrollView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.scrollView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor],

        // ContentView inside ScrollView
        [self.contentView.topAnchor constraintEqualToAnchor:self.scrollView.contentLayoutGuide.topAnchor],
        [self.contentView.leadingAnchor constraintEqualToAnchor:self.scrollView.contentLayoutGuide.leadingAnchor],
        [self.contentView.trailingAnchor constraintEqualToAnchor:self.scrollView.contentLayoutGuide.trailingAnchor],
        [self.contentView.bottomAnchor constraintEqualToAnchor:self.scrollView.contentLayoutGuide.bottomAnchor],

        // IMPORTANT: content width = scroll width
        [self.contentView.widthAnchor constraintEqualToAnchor:self.scrollView.frameLayoutGuide.widthAnchor],
    ]];
}

- (void)setupHeaderImage {
    UIScrollView *imageScroll = [[UIScrollView alloc] init];
    imageScroll.translatesAutoresizingMaskIntoConstraints = NO;
    imageScroll.pagingEnabled = YES;
    imageScroll.showsHorizontalScrollIndicator = NO;
    imageScroll.delegate = self;
    imageScroll.tag = 777;
    [self.contentView addSubview:imageScroll];

    UIPageControl *pageControl = [[UIPageControl alloc] init];
    pageControl.translatesAutoresizingMaskIntoConstraints = NO;
    pageControl.tag = 778;
    [self.contentView addSubview:pageControl];

    [NSLayoutConstraint activateConstraints:@[
        [imageScroll.topAnchor constraintEqualToAnchor:self.contentView.topAnchor],
        [imageScroll.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor],
        [imageScroll.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor],
        [imageScroll.heightAnchor constraintEqualToConstant:230],

        [pageControl.centerXAnchor constraintEqualToAnchor:self.contentView.centerXAnchor],
        [pageControl.bottomAnchor constraintEqualToAnchor:imageScroll.bottomAnchor constant:-8],
    ]];
}

- (void)setupDetailsCard {
    self.detailsCard = [[UIView alloc] init];
    self.detailsCard.translatesAutoresizingMaskIntoConstraints = NO;
    self.detailsCard.backgroundColor = UIColor.whiteColor;
    self.detailsCard.layer.cornerRadius = 20;
    self.detailsCard.layer.maskedCorners =
        kCALayerMinXMinYCorner | kCALayerMaxXMinYCorner;

    [self.contentView addSubview:self.detailsCard];

    UIScrollView *imageScroll = [self.contentView viewWithTag:777];

    [NSLayoutConstraint activateConstraints:@[
        [self.detailsCard.topAnchor constraintEqualToAnchor:imageScroll.bottomAnchor constant:12],
        [self.detailsCard.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor],
        [self.detailsCard.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor],
    ]];

    // ---- Reference Label ----
    self.refLabel = [[UILabel alloc] init];
    self.refLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.refLabel.font = [UIFont boldSystemFontOfSize:20];
    [self.detailsCard addSubview:self.refLabel];

    // ---- Floor Plan Thumbnail ----
    self.floorPlanThumbnail = [[UIImageView alloc] init];
    self.floorPlanThumbnail.translatesAutoresizingMaskIntoConstraints = NO;
    self.floorPlanThumbnail.contentMode = UIViewContentModeScaleAspectFill;
    self.floorPlanThumbnail.clipsToBounds = YES;
    [self.detailsCard addSubview:self.floorPlanThumbnail];

    // ---- Status Label ----
    self.statusLabel = [[UILabel alloc] init];
    self.statusLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.statusLabel.textAlignment = NSTextAlignmentCenter;
    self.statusLabel.layer.cornerRadius = 14;
    self.statusLabel.layer.masksToBounds = YES;
    [self.detailsCard addSubview:self.statusLabel];

    [NSLayoutConstraint activateConstraints:@[
        [self.refLabel.topAnchor constraintEqualToAnchor:self.detailsCard.topAnchor constant:20],
        [self.refLabel.leadingAnchor constraintEqualToAnchor:self.detailsCard.leadingAnchor constant:16],
        [self.refLabel.trailingAnchor constraintLessThanOrEqualToAnchor:self.floorPlanThumbnail.leadingAnchor constant:-16],

        [self.floorPlanThumbnail.topAnchor constraintEqualToAnchor:self.detailsCard.topAnchor constant:20],
        [self.floorPlanThumbnail.trailingAnchor constraintEqualToAnchor:self.detailsCard.trailingAnchor constant:-20],
        [self.floorPlanThumbnail.widthAnchor constraintEqualToConstant:64],
        [self.floorPlanThumbnail.heightAnchor constraintEqualToConstant:64],

        [self.statusLabel.topAnchor constraintEqualToAnchor:self.refLabel.bottomAnchor constant:18],
        [self.statusLabel.leadingAnchor constraintEqualToAnchor:self.detailsCard.leadingAnchor constant:16],
        [self.statusLabel.widthAnchor constraintEqualToConstant:104],
        [self.statusLabel.heightAnchor constraintEqualToConstant:28],
    ]];

    // Info rows (stacked vertically)
    UIView *previous = self.statusLabel;
    NSArray *titles = @[@"Created Date",@"Location",@"Category",@"Type",@"Issue",@"Created By",@"Comment"];

    for (int i = 0; i < titles.count; i++) {
        UILabel *title = [[UILabel alloc] init];
        title.translatesAutoresizingMaskIntoConstraints = NO;
        title.text = [NSString stringWithFormat:@"%@ :", titles[i]];
        title.textColor = UIColor.darkGrayColor;

        UILabel *value = [[UILabel alloc] init];
        value.translatesAutoresizingMaskIntoConstraints = NO;
        value.tag = 100 + i;

        [self.detailsCard addSubview:title];
        [self.detailsCard addSubview:value];

        [NSLayoutConstraint activateConstraints:@[
            [title.topAnchor constraintEqualToAnchor:previous.bottomAnchor constant:14],
            [title.leadingAnchor constraintEqualToAnchor:self.detailsCard.leadingAnchor constant:20],
            [title.widthAnchor constraintEqualToConstant:120],

            [value.centerYAnchor constraintEqualToAnchor:title.centerYAnchor],
            [value.leadingAnchor constraintEqualToAnchor:title.trailingAnchor constant:10],
            [value.trailingAnchor constraintEqualToAnchor:self.detailsCard.trailingAnchor constant:-20],
        ]];

        previous = title;
    }

    // Bottom anchor defines content height
    [self.detailsCard.bottomAnchor constraintEqualToAnchor:previous.bottomAnchor constant:20].active = YES;
}

- (void)setupButtons {
    UIView *buttonContainer = [[UIView alloc] init];
    buttonContainer.translatesAutoresizingMaskIntoConstraints = NO;
    [self.contentView addSubview:buttonContainer];

    [NSLayoutConstraint activateConstraints:@[
        [buttonContainer.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor],
        [buttonContainer.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor],
        [buttonContainer.bottomAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.bottomAnchor],
        [buttonContainer.heightAnchor constraintGreaterThanOrEqualToConstant:48],
    ]];

    NSString *status = [self.issueData[@"status_external"] lowercaseString];

    if ([status isEqualToString:@"lodged"]) {
        UIButton *editButton = [self createAnimatedButtonWithTitle:@"Edit Issue"
                                                      color:UIColor.systemTealColor];
        UIButton *deleteButton = [self createAnimatedButtonWithTitle:@"Delete Issue"
                                                        color:UIColor.systemRedColor];

        UIStackView *stack = [[UIStackView alloc] initWithArrangedSubviews:@[editButton, deleteButton]];
        stack.translatesAutoresizingMaskIntoConstraints = NO;
        stack.axis = UILayoutConstraintAxisHorizontal;
        stack.spacing = 16;
        stack.distribution = UIStackViewDistributionFillEqually;

        [buttonContainer addSubview:stack];

        [NSLayoutConstraint activateConstraints:@[
            [stack.topAnchor constraintEqualToAnchor:buttonContainer.topAnchor],
            [stack.leadingAnchor constraintEqualToAnchor:buttonContainer.leadingAnchor constant:16],
            [stack.trailingAnchor constraintEqualToAnchor:buttonContainer.trailingAnchor constant:-16],
            [stack.heightAnchor constraintEqualToConstant:48],
        ]];
    }
}


#pragma mark - Data
- (void)populateData {
    if (!self.issueData) return;
    
    [self.view layoutIfNeeded];
    NSString *ref = self.issueData[@"issue_reference"] ?: self.issueData[@"reference"] ?: @"Unknown Reference";
    NSString *status = self.issueData[@"status_external"] ?: @"No Status";
    NSString *statusColor = self.issueData[@"status_ex_color"] ?: @"#999999";
    NSDictionary *createdBy = self.issueData[@"creted_by"];

    NSArray *values = @[
        self.issueData[@"created_at"] ?: @"–",
        self.issueData[@"location_name"] ?: @"–",
        self.issueData[@"category"] ?: @"–",
        self.issueData[@"type"] ?: @"–",
        self.issueData[@"issue"] ?: @"–",
        createdBy[@"name"] ?: @"–",
        self.issueData[@"remarks"] ?: @"–"
    ];

    self.refLabel.text = ref;
    self.statusLabel.text = status;
    self.statusLabel.textColor = [UIColor whiteColor];
    self.statusLabel.backgroundColor = [self colorFromHex:statusColor];

    // Fill info rows
    for (int i = 0; i < values.count; i++) {
        UILabel *label = [self.detailsCard viewWithTag:100 + i];
        if ([label isKindOfClass:[UILabel class]]) label.text = values[i];
    }

    // 🖼️ Handle multiple images
    NSArray *imageList = self.issueData[@"images"];
    if (![imageList isKindOfClass:[NSArray class]] || imageList.count == 0) {
        // ✅ Fallback to "first" array (actual source for multiple images)
        if ([self.issueData[@"first"] isKindOfClass:[NSArray class]]) {
            imageList = self.issueData[@"first"];
        } else if (self.issueData[@"image"]) {
            imageList = @[ self.issueData[@"image"] ];
        } else {
            imageList = @[];
        }
    }

    UIPageControl *pageControl = [self.scrollView viewWithTag:778];
    UIScrollView *imageScroll = [self.scrollView viewWithTag:777];
    NSLog(@"imageScroll width: %f", imageScroll.bounds.size.width);
    CGFloat width = imageScroll.bounds.size.width;
    CGFloat height = imageScroll.bounds.size.height;
    imageScroll.contentSize = CGSizeMake(width * imageList.count, height);
    pageControl.numberOfPages = imageList.count;
    pageControl.currentPage = 0;

    // ✅ Remove old subviews first
    for (UIView *sub in imageScroll.subviews) {
        [sub removeFromSuperview];
    }

    for (int i = 0; i < imageList.count; i++) {
        NSString *urlStr = nil;
        id imgItem = imageList[i];
        if ([imgItem isKindOfClass:[NSDictionary class]]) {
            urlStr = imgItem[@"image"] ?: imgItem[@"thumb_image"];
        } else if ([imgItem isKindOfClass:[NSString class]]) {
            urlStr = imgItem;
        }
        if (!urlStr || urlStr.length == 0) continue;

        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(width * i, 0, width, height)];
        imgView.contentMode = UIViewContentModeScaleAspectFill;
        imgView.clipsToBounds = YES;
        imgView.userInteractionEnabled = YES;
        imgView.backgroundColor = [UIColor colorWithWhite:0.85 alpha:1];
        imgView.tag = i;

        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleImageTap:)];
        [imgView addGestureRecognizer:tap];
        [imageScroll addSubview:imgView];

        NSURL *url = [NSURL URLWithString:urlStr];
        [ImageCacheHelper loadImageWithURL:url completion:^(UIImage *image) {
            if (image) imgView.image = image;
        }];
    }

    NSString *planThumbURL = self.issueData[@"plan_image_thumb"];
    if (planThumbURL.length > 0) {
        NSURL *url = [NSURL URLWithString:planThumbURL];
        [ImageCacheHelper loadImageWithURL:url completion:^(UIImage *image) {
            if (image) self.floorPlanThumbnail.image = image;
        }];
    }

    //thumbnail marker
    NSString *x = self.issueData[@"pos_x"];
    NSString *y = self.issueData[@"pos_y"];

    if (x && y) {
        CGFloat posX = [x floatValue];
        CGFloat posY = [y floatValue];

        // Original floor plan size (replace these with actual known values)
        CGFloat originalWidth = 1920.0;
        CGFloat originalHeight = 1953.6;

        // Scale to thumbnail
        CGFloat thumbWidth = self.floorPlanThumbnail.bounds.size.width;
        CGFloat thumbHeight = self.floorPlanThumbnail.bounds.size.height;

        CGFloat scaleX = thumbWidth / originalWidth;
        CGFloat scaleY = thumbHeight / originalHeight;

        CGFloat dotX = posX * scaleX;
        CGFloat dotY = posY * scaleY;

        UIView *marker = [[UIView alloc] initWithFrame:CGRectMake(dotX - 4, dotY - 4, 8, 8)];
        marker.backgroundColor = [UIColor systemRedColor];
        marker.layer.cornerRadius = 4;
        marker.layer.borderColor = [UIColor whiteColor].CGColor;
        marker.layer.borderWidth = 1;
        [self.floorPlanThumbnail addSubview:marker];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.tag != 777) return; // only for the image scroll view
    UIPageControl *pageControl = [self.scrollView viewWithTag:778];
    
    CGFloat pageWidth = scrollView.frame.size.width;
    NSInteger page = (NSInteger)floor((scrollView.contentOffset.x + pageWidth / 2) / pageWidth);
    pageControl.currentPage = page;
}

#pragma mark - Image Tap Handler
- (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];

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

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

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

- (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)handleFloorPlanTap {
    NSString *planFullURL = self.issueData[@"plan_image"];
    if (planFullURL.length == 0) return; // No full image available

    UIView *overlay = [[UIView alloc] initWithFrame:self.view.bounds];
    overlay.backgroundColor = [UIColor colorWithWhite:0 alpha:0.95];
    overlay.alpha = 0;
    overlay.tag = 901;
    overlay.userInteractionEnabled = YES;
    [self.view addSubview:overlay];

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

    // Dismiss on tap
    UITapGestureRecognizer *dismissTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeFullFloorPlan)];
    [overlay addGestureRecognizer:dismissTap];

    // Animate overlay fade-in
    [UIView animateWithDuration:0.25 animations:^{
        overlay.alpha = 1;
    }];

    // Load full image asynchronously
    NSURL *url = [NSURL URLWithString:planFullURL];
    [ImageCacheHelper loadImageWithURL:url completion:^(UIImage *img) {
        if (!img) return;

        fullImageView.image = img;

        NSString *xStr = self.issueData[@"pos_x"];
        NSString *yStr = self.issueData[@"pos_y"];
        if (xStr && yStr) {
            CGFloat posX = [xStr floatValue];
            CGFloat posY = [yStr floatValue];

            // Calculate scale and offsets based on aspect-fit
            CGSize imageSize = img.size;
            CGSize viewSize = fullImageView.bounds.size;
            CGFloat scale = MIN(viewSize.width / imageSize.width, viewSize.height / imageSize.height);
            CGFloat offsetX = (viewSize.width - imageSize.width * scale) / 2.0;
            CGFloat offsetY = (viewSize.height - imageSize.height * scale) / 2.0;

            CGFloat dotX = posX * scale + offsetX;
            CGFloat dotY = posY * scale + offsetY;

            UIView *marker = [[UIView alloc] initWithFrame:CGRectMake(dotX - 5, dotY - 5, 10, 10)];
            marker.backgroundColor = [UIColor systemRedColor];
            marker.layer.cornerRadius = 5;
            marker.layer.borderColor = [UIColor whiteColor].CGColor;
            marker.layer.borderWidth = 1.5;
            [fullImageView addSubview:marker];
        }
    }];
}

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

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

#pragma mark - Helper
- (UIColor *)colorFromHex:(NSString *)hexString {
    if (!hexString || hexString.length < 6) return [UIColor grayColor];
    unsigned int rgbValue = 0;
    NSScanner *scanner = [NSScanner scannerWithString:hexString];
    if ([hexString 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 - Button Actions
- (void)handleBackTap {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)handleHistoryTap {
  NSLog(@"🕓 Navigating to History");
  
  HistoryViewController *nextVC = [[HistoryViewController alloc] init];
  nextVC.modalPresentationStyle = UIModalPresentationFullScreen;
  
  nextVC.issueID = [NSString stringWithFormat:@"%@", self.issueData[@"issue_reference_id"] ?: self.issueData[@"id"] ?: @""];
  nextVC.planID = self.issueData[@"plan_id"];
  nextVC.status = self.issueData[@"status_external"];
  nextVC.unitName = self.issueData[@"plan_unit"];
  nextVC.reference = self.issueData[@"reference"] ?: self.issueData[@"issue_reference"];
  nextVC.projectCode = self.projectCode;
  nextVC.projectName = self.projectName;
  
  NSLog(@"📦 Data being sent to History:\n issueID: %@\n planID: %@\n status: %@\n unitName: %@\n reference: %@",
        nextVC.projectCode,
        nextVC.projectName,
        nextVC.status,
        nextVC.unitName,
        nextVC.reference);
  [self presentViewController:nextVC animated:YES completion:nil];
}

- (void)editIssueTapped {
    NSLog(@"✏️ Edit Issue tapped");

    NSDictionary *data = self.issueData;
    if (!data || ![data isKindOfClass:[NSDictionary class]]) {
        NSLog(@"⚠️ No issue data available for editing");
        return;
    }

    // --- Prepare base values ---
    NSString *issueType = @"internal";
    NSString *planType = data[@"plan_type"];
    if ([planType isEqualToString:@"commonarea"]) {
        issueType = @"commonarea";
    }

    NSString *strTempUnitID = data[@"plan_id"] ? [NSString stringWithFormat:@"%@", data[@"plan_id"]] : @"";
    NSString *strTempUnitName = data[@"issue_reference"] ?: @"";
    NSString *strLocationName = data[@"location_name"] ?: @"";
    NSString *strLocationID = data[@"location_id"] ? [NSString stringWithFormat:@"%@", data[@"location_id"]] : @"";

    // --- Build issue_content dictionary ---
    NSMutableDictionary *issueContent = [@{
        @"id": @"temp",
        @"join_id": @"",
        @"pos_x": @"",
        @"pos_y": @"",
        @"issue_id": @""
    } mutableCopy];

    if (data[@"id"] && ![data[@"id"] isKindOfClass:[NSNull class]]) {
        issueContent[@"issue_id"] = [NSString stringWithFormat:@"%@", data[@"issue_reference_id"]];
    }
    if (data[@"pos_x"] && ![data[@"pos_x"] isKindOfClass:[NSNull class]]) {
        issueContent[@"pos_x"] = [NSString stringWithFormat:@"%@", data[@"pos_x"]];
    }
    if (data[@"pos_y"] && ![data[@"pos_y"] isKindOfClass:[NSNull class]]) {
        issueContent[@"pos_y"] = [NSString stringWithFormat:@"%@", data[@"pos_y"]];
    }

    // --- Navigate to Plan Screen ---
    PlanViewController *planVC = [[PlanViewController alloc] init];
    planVC.modalPresentationStyle = UIModalPresentationFullScreen;

    // Assign properties directly
    planVC.type = issueType;
    planVC.unitID = strTempUnitID;
    planVC.unitName = strTempUnitName;
    planVC.action = @"edit_issue";
    planVC.offline = NO;
    planVC.locationName = strLocationName;
    planVC.locationId = strLocationID;
    planVC.issueContent = issueContent;
    planVC.issueFullData = data;
    planVC.projectCode = self.projectCode;
    planVC.projectName = self.projectName;

    NSLog(@"🧭 Navigating to PlanScreen with:\n projectCode=%@\n projectName=%@\n unitName=%@\n location= %@ & %@\n  issue_id=%@\n",
          planVC.projectCode, planVC.projectName, planVC.unitName, planVC.locationName, planVC.locationId, planVC.issueContent[@"issue_id"]);

    [self presentViewController:planVC animated:YES completion:nil];
}

- (void)deleteIssueTapped {
    NSLog(@"🗑 Delete / Withdraw Issue tapped");

    NSDictionary *data = self.issueData;
    if (!data) {
        NSLog(@"⚠️ No issueData available");
        return;
    }

    // Extract values safely
    NSString *issueID = [NSString stringWithFormat:@"%@", data[@"issue_reference_id"] ?: data[@"id"] ?: @""];
    NSString *planID = [NSString stringWithFormat:@"%@", data[@"plan_id"] ?: @""];
    NSString *status = data[@"status_external"] ?: data[@"status_internal"] ?: @"";
    NSString *unitName = data[@"plan_unit"] ?: @"";
    NSString *reference = data[@"issue_reference"] ?: data[@"reference"] ?: @"";

    // Choose title based on context
    NSString *strTitle = [status.lowercaseString containsString:@"void"]
        ? @"Void Issue"
        : @"Delete Issue";

    // ✅ Create the new VC
    WithdrawSingleIssueViewController *withdrawVC = [[WithdrawSingleIssueViewController alloc] init];
    withdrawVC.modalPresentationStyle = UIModalPresentationFullScreen;

    // Pass data individually
    withdrawVC.issueID = issueID;
    withdrawVC.planID = planID;
    withdrawVC.status = status;
    withdrawVC.unitName = unitName;
    withdrawVC.reference = reference;
    withdrawVC.titleText = strTitle;
    withdrawVC.isMultiWithdraw = NO;

    NSLog(@"📦 Navigating to WithdrawSingleIssueViewController with:\n issueID=%@\n planID=%@\n status=%@\n unitName=%@\n reference=%@\n title=%@",
          issueID, planID, status, unitName, reference, strTitle);

    [self presentViewController:withdrawVC animated:YES completion:nil];
}


- (UIButton *)createAnimatedButtonWithTitle:(NSString *)title color:(UIColor *)color {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    button.backgroundColor = color;
    button.layer.cornerRadius = 20;
    button.titleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightRegular];
    
    // Add tap animation
    [button addTarget:self action:@selector(animateButtonTouchDown:) forControlEvents:UIControlEventTouchDown];
    [button addTarget:self action:@selector(animateButtonTouchUp:) forControlEvents:UIControlEventTouchUpInside];
    [button addTarget:self action:@selector(animateButtonTouchUp:) forControlEvents:UIControlEventTouchUpOutside];
    return button;
}

- (void)animateButtonTouchDown:(UIButton *)button {
    [UIView animateWithDuration:0.1 animations:^{
        button.transform = CGAffineTransformMakeScale(0.95, 0.95);
        button.alpha = 0.8;
    }];
}

- (void)animateButtonTouchUp:(UIButton *)button {
    [UIView animateWithDuration:0.15 animations:^{
        button.transform = CGAffineTransformIdentity;
        button.alpha = 1.0;
    }];
}

@end
