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

@interface IssueDetailViewController () <UIScrollViewDelegate>

@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 systemGray6Color];
    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];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

    UIView *headerView = [self.view viewWithTag:999];
    if (!headerView) return;

    // ✅ Use updated safe area now that it’s available
    UILayoutGuide *safe = self.view.safeAreaLayoutGuide;
    CGFloat topInset = safe.layoutFrame.origin.y;
    CGFloat headerHeight = 56.0 + topInset;
    headerView.frame = CGRectMake(0, 0, self.view.bounds.size.width, headerHeight);

    // ✅ Adjust subviews within header
    UIButton *backButton = [headerView viewWithTag:1];
    UILabel *titleLabel = [headerView viewWithTag:2];
    UIButton *historyButton = [headerView viewWithTag:3];

    backButton.frame = CGRectMake(12, topInset + 8, 44, 40);
    titleLabel.frame = CGRectMake(0, topInset + 8, self.view.bounds.size.width, 40);
    historyButton.frame = CGRectMake(self.view.bounds.size.width - 56, topInset + 8, 44, 40);

    // ✅ Shift scroll view below header
    CGFloat headerBottom = CGRectGetMaxY(headerView.frame);
    self.scrollView.frame = CGRectMake(0, headerBottom, self.view.bounds.size.width, self.view.bounds.size.height - headerBottom);
}

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

    // --- Back Button ---
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    backButton.tag = 1;
    [backButton setImage:[UIImage systemImageNamed:@"chevron.left"] forState:UIControlStateNormal];
    backButton.tintColor = UIColor.whiteColor;
    [backButton addTarget:self action:@selector(handleBackTap) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:backButton];

    // --- Title ---
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.tag = 2;
    titleLabel.text = @"Issue Details";
    titleLabel.font = [UIFont boldSystemFontOfSize:18];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = UIColor.whiteColor;
    [headerView addSubview:titleLabel];

    // --- History Button ---
    UIButton *historyButton = [UIButton buttonWithType:UIButtonTypeSystem];
    historyButton.tag = 3;
    [historyButton setImage:[UIImage systemImageNamed:@"clock.arrow.circlepath"] forState:UIControlStateNormal];
    historyButton.tintColor = UIColor.whiteColor;
    [historyButton addTarget:self action:@selector(handleHistoryTap) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:historyButton];
}

#pragma mark - UI Setup

- (void)setupScrollView {
    UIView *headerView = [self.view viewWithTag:999];
    CGFloat headerBottom = CGRectGetMaxY(headerView.frame);

    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, headerBottom, self.view.bounds.size.width, self.view.bounds.size.height - headerBottom)];
    self.scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.scrollView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.scrollView];
}

- (void)setupHeaderImage {
    CGFloat height = 230;
    UIScrollView *imageScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, height)];
    imageScroll.pagingEnabled = YES;
    imageScroll.showsHorizontalScrollIndicator = NO;
    imageScroll.delegate = self;
    imageScroll.tag = 777;
    [self.scrollView addSubview:imageScroll];

    UIPageControl *pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, height - 30, self.view.bounds.size.width, 20)];
    pageControl.pageIndicatorTintColor = [UIColor colorWithWhite:1 alpha:0.5];
    pageControl.currentPageIndicatorTintColor = UIColor.whiteColor;
    pageControl.tag = 778;
    [self.scrollView addSubview:pageControl];
}

- (void)setupDetailsCard {
    CGFloat topOffset = 220;
    CGFloat padding = 20;

    self.detailsCard = [[UIView alloc] initWithFrame:CGRectMake(0, topOffset, self.view.bounds.size.width, 420)];
    self.detailsCard.backgroundColor = UIColor.whiteColor;
    self.detailsCard.layer.cornerRadius = 20;
    self.detailsCard.layer.maskedCorners = kCALayerMinXMinYCorner | kCALayerMaxXMinYCorner;
    [self.scrollView addSubview:self.detailsCard];

    CGFloat y = 20;

    // --- Reference ID ---
    CGFloat thumbWidth = 40;
    CGFloat gap = 12;
    self.refLabel = [[UILabel alloc] initWithFrame:CGRectMake(padding, y, self.view.bounds.size.width - 2*padding - thumbWidth - gap, 24)];
    self.refLabel.font = [UIFont boldSystemFontOfSize:20];
    self.refLabel.textColor = UIColor.blackColor; // make sure it’s visible
    self.refLabel.numberOfLines = 1;
    self.refLabel.adjustsFontSizeToFitWidth = YES;

    [self.detailsCard addSubview:self.refLabel];
    y += 36;
  
    // --- Floor Plan Thumbnail ---
    CGFloat thumbSize = 100; // new size
    self.floorPlanThumbnail = [[UIImageView alloc] initWithFrame:
        CGRectMake(self.view.bounds.size.width - padding - thumbSize, 20, thumbSize, thumbSize)];
    self.floorPlanThumbnail.contentMode = UIViewContentModeScaleAspectFill;
    self.floorPlanThumbnail.clipsToBounds = YES;
    self.floorPlanThumbnail.layer.cornerRadius = 4;
    self.floorPlanThumbnail.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];
    self.floorPlanThumbnail.layer.borderColor = [UIColor systemGray3Color].CGColor;
    self.floorPlanThumbnail.layer.borderWidth = 1.0;
    self.floorPlanThumbnail.userInteractionEnabled = YES;

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleFloorPlanTap)];
    [self.floorPlanThumbnail addGestureRecognizer:tap];
    [self.detailsCard addSubview:self.floorPlanThumbnail];

    // --- Status Capsule ---
    self.statusLabel = [[UILabel alloc] initWithFrame:CGRectMake(padding, y, 90, 28)];
    self.statusLabel.font = [UIFont boldSystemFontOfSize:14];
    self.statusLabel.textColor = UIColor.whiteColor;
    self.statusLabel.textAlignment = NSTextAlignmentCenter;
    self.statusLabel.layer.cornerRadius = 14;
    self.statusLabel.layer.masksToBounds = YES;
    [self.detailsCard addSubview:self.statusLabel];
    y += 50;

    // --- Info Labels ---
    NSArray *titles = @[@"Created Date", @"Location", @"Category", @"Type", @"Issue", @"Created By", @"Comment"];
    for (NSString *title in titles) {
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(padding, y, 120, 22)];
        titleLabel.text = [NSString stringWithFormat:@"%@ :", title];
        titleLabel.textColor = UIColor.darkGrayColor;
        titleLabel.font = [UIFont systemFontOfSize:15];
        [self.detailsCard addSubview:titleLabel];

        UILabel *valueLabel = [[UILabel alloc] initWithFrame:CGRectMake(padding + 130, y, self.view.bounds.size.width - 150, 22)];
        valueLabel.tag = [titles indexOfObject:title] + 100; // tag for later update
        valueLabel.textColor = UIColor.blackColor;
        valueLabel.font = [UIFont systemFontOfSize:15 weight:UIFontWeightMedium];
        [self.detailsCard addSubview:valueLabel];
        y += 28;
    }
}

- (void)setupButtons {
    NSString *status = [self.issueData[@"status_external"] lowercaseString];
    CGFloat y = CGRectGetMaxY(self.detailsCard.frame) + 16;
    CGFloat buttonWidth = (self.view.bounds.size.width - 60) / 2;
    
    UIView *buttonContainer = [[UIView alloc] initWithFrame:CGRectMake(0, y, self.view.bounds.size.width, 60)];
    buttonContainer.backgroundColor = UIColor.clearColor;
    [self.scrollView addSubview:buttonContainer];

    // ---- Lodged ----
    if ([status isEqualToString:@"lodged"]) {
        // Edit Issue button
        self.editButton = [UIButton buttonWithType:UIButtonTypeSystem];
        self.editButton.frame = CGRectMake(20, 0, buttonWidth, 44);
        [self.editButton setTitle:@"Edit Issue" forState:UIControlStateNormal];
        [self.editButton setTitleColor:[UIColor colorWithRed:0/255.0 green:115/255.0 blue:130/255.0 alpha:1] forState:UIControlStateNormal];
        self.editButton.layer.cornerRadius = 8;
        self.editButton.layer.borderWidth = 1;
        self.editButton.layer.borderColor = [UIColor colorWithRed:0/255.0 green:115/255.0 blue:130/255.0 alpha:1].CGColor;
        [self.editButton addTarget:self action:@selector(editIssueTapped) forControlEvents:UIControlEventTouchUpInside];
        [buttonContainer addSubview:self.editButton];

        // Delete Issue button
        self.deleteButton = [UIButton buttonWithType:UIButtonTypeSystem];
        self.deleteButton.frame = CGRectMake(CGRectGetMaxX(self.editButton.frame) + 20, 0, buttonWidth, 44);
        [self.deleteButton setTitle:@"Delete Issue" forState:UIControlStateNormal];
        [self.deleteButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        self.deleteButton.backgroundColor = [UIColor systemRedColor];
        self.deleteButton.layer.cornerRadius = 8;
        [self.deleteButton addTarget:self action:@selector(deleteIssueTapped) forControlEvents:UIControlEventTouchUpInside];
        [buttonContainer addSubview:self.deleteButton];
    }

    // ---- Pending Access / W.I.P ----
    else if ([status isEqualToString:@"pending access"] || [status isEqualToString:@"w.i.p"] || [status isEqualToString:@"wip"]) {
        UIButton *withdrawButton = [UIButton buttonWithType:UIButtonTypeSystem];
        withdrawButton.frame = CGRectMake(20, 0, self.view.bounds.size.width - 40, 44);
        [withdrawButton setTitle:@"Withdraw Issue" forState:UIControlStateNormal];
        [withdrawButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        withdrawButton.backgroundColor = [UIColor colorWithRed:232/255.0 green:76/255.0 blue:79/255.0 alpha:1.0];
        withdrawButton.layer.cornerRadius = 20;
        [withdrawButton addTarget:self action:@selector(deleteIssueTapped) forControlEvents:UIControlEventTouchUpInside]; // same flow for now
        [buttonContainer addSubview:withdrawButton];
    }

    // ---- Pending Owner Acceptance (POA) ----
    else if ([status isEqualToString:@"pending owner acceptance"]) {
        CGFloat halfWidth = (self.view.bounds.size.width - 52) / 2;

        UIButton *rejectButton = [self createAnimatedButtonWithTitle:@"Reject"
                                                              color:[UIColor colorWithRed:255/255.0 green:19/255.0 blue:6/255.0 alpha:1.0]];
        rejectButton.frame = CGRectMake(20, 0, halfWidth, 44);
        [buttonContainer addSubview:rejectButton];

        UIButton *acceptButton = [self createAnimatedButtonWithTitle:@"Accept"
                                                              color:[UIColor colorWithRed:0/255.0 green:144/255.0 blue:14/255.0 alpha:1.0]];
        acceptButton.frame = CGRectMake(CGRectGetMaxX(rejectButton.frame) + 12, 0, halfWidth, 44);
        [buttonContainer addSubview:acceptButton];
    }

    // ---- Others ----
    else {
        NSLog(@"ℹ️ No action buttons for status: %@", status);
    }

    CGFloat totalHeight = CGRectGetMaxY(buttonContainer.frame) + 30;
    self.scrollView.contentSize = CGSizeMake(self.view.bounds.size.width, totalHeight);
}

#pragma mark - Data
- (void)populateData {
    if (!self.issueData) return;

    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.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 = @[];
        }
    }

    UIScrollView *imageScroll = [self.scrollView viewWithTag:777];
    UIPageControl *pageControl = [self.scrollView viewWithTag:778];

    CGFloat width = self.view.bounds.size.width;
    CGFloat height = 230;
    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];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSData *data = [NSData dataWithContentsOfURL:url];
            if (data) {
                UIImage *img = [UIImage imageWithData:data];
                dispatch_async(dispatch_get_main_queue(), ^{
                    imgView.image = img;
                });
            }
        });
    }
  
    NSString *planThumbURL = self.issueData[@"plan_image_thumb"];
    if (planThumbURL.length > 0) {
        NSURL *url = [NSURL URLWithString:planThumbURL];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSData *data = [NSData dataWithContentsOfURL:url];
            if (data) {
                UIImage *img = [UIImage imageWithData:data];
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.floorPlanThumbnail.image = img;
                });
            }
        });
    }
  
    //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];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSData *data = [NSData dataWithContentsOfURL:url];
        if (!data) return;

        UIImage *img = [UIImage imageWithData:data];
        if (!img) return;

        dispatch_async(dispatch_get_main_queue(), ^{
            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
