// PlanViewController.mm
#import "PlanViewController.h"
#import "DetailsViewController.h"
#import "AddIssueAPIClient.h"
#import <AVFoundation/AVFoundation.h>

@interface PlanViewController ()

@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *backButton;
@property (nonatomic, strong) UIButton *helpButton;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIImageView *planImageView;
@property (nonatomic, strong) NSString *selectedLocation;
@property (nonatomic, strong) NSDictionary *unitPlanData;
@property (nonatomic, strong) NSArray *locations;
@property (nonatomic, strong) NSString *planImageURL;
@property (nonatomic, assign) CGFloat planWidth;
@property (nonatomic, assign) CGFloat planHeight;
@property (nonatomic, strong) UIView *markerView;
@property (nonatomic, strong) UIView *footerView;
@property (nonatomic, strong) UILabel *selectedLabel;
@property (nonatomic, strong) UIButton *footerBackButton;
@property (nonatomic, strong) UIButton *footerNextButton;
@property (nonatomic, strong) CAShapeLayer *selectedOverlay;
@property (nonatomic, strong) NSMutableArray<CAShapeLayer *> *overlayLayers;
@property (nonatomic, assign) BOOL selectionLocked;
@property (nonatomic, strong) NSString *planID;
@property (nonatomic, strong) NSString *locationID;
@property (nonatomic, strong) NSDictionary *locationData;
@property (nonatomic, strong) NSString *defectMatrix;
@property (nonatomic, strong) NSDictionary *unitPlanResponse;
@property (nonatomic, strong) NSArray *unitPlanLocations;
@property (nonatomic, assign) CGFloat tappedPlanX;
@property (nonatomic, assign) CGFloat tappedPlanY;

@end

@implementation PlanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;
    NSLog(@"PlanViewController loaded");
    NSLog(@"🧭 Navigated to PlanScreen with:\n type=%@\n unitID=%@\n unitName=%@\n location= %@ & %@\n issue_id=%@\n action=%@",
        self.type, self.unitID, self.unitName, self.locationName, self.locationId, self.issueContent[@"issue_id"], self.action);
    // Create UI elements (but don’t assign final frames yet)
    [self createHeader];
    [self createScrollView];
  
    self.overlayLayers = [NSMutableArray array];
  
    [self handleGetUnitPlan];
    [self.view bringSubviewToFront:self.headerView];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    [self.view bringSubviewToFront:self.headerView];
  
    static BOOL hasRenderedLocations = NO;
    if (!hasRenderedLocations && self.planImageView.image && self.locations.count > 0) {
        hasRenderedLocations = YES;
        [self renderAllLocations:self.locations];
    }
}

- (void)handleGetUnitPlan {
    NSLog(@"🌐 Fetching Unit Plan data...");

    [AddIssueAPIClient fetchGetUnitPlan:^(NSDictionary *data, NSError *error) {
        if (error) {
            NSLog(@"❌ Unit Plan fetch failed: %@", error.localizedDescription);
            return;
        }

        NSLog(@"✅ Raw Unit Plan response received");

        // Save response to Documents for debugging
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:NSJSONWritingPrettyPrinted error:nil];
        NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
        NSString *filePath = [docsPath stringByAppendingPathComponent:@"getUnitPlan.txt"];
        [jsonData writeToFile:filePath atomically:YES];
        NSLog(@"📁 UnitPlan saved to %@", filePath);
      
        // 🔹 Save the full API response
        self.unitPlanResponse = data;

        // 🔍 Parse JSON
        NSDictionary *appData = data[@"AppData"];
        if (![appData[@"status"] isEqualToString:@"success"]) {
            NSLog(@"⚠️ Server returned non-success status: %@", appData[@"message"]);
            return;
        }

        NSArray *mainData = data[@"Data"];
        if (mainData.count == 0) {
            NSLog(@"⚠️ No unit plan data found");
            return;
        }
        self.unitPlanLocations = mainData.firstObject[@"location"];
        self.unitPlanData = mainData.firstObject;
        self.locations = self.unitPlanData[@"location"];

        if (self.locations.count == 0) {
            NSLog(@"⚠️ No locations found in plan");
            return;
        }

        // ✅ Extract plan info from the first location’s first issue
        NSDictionary *firstLocation = self.locations.firstObject;
        NSArray *issues = firstLocation[@"issue"];
        if (issues.count == 0) {
            NSLog(@"⚠️ No issues found under first location");
            return;
        }

        NSDictionary *firstIssue = issues.firstObject;
        NSString *widthStr = [NSString stringWithFormat:@"%@", firstIssue[@"plan_width"]];
        NSString *heightStr = [NSString stringWithFormat:@"%@", firstIssue[@"plan_height"]];
        self.planID = [NSString stringWithFormat:@"%@", firstIssue[@"plan_id"] ?: @"0"];

        self.planWidth = [widthStr floatValue];
        self.planHeight = [heightStr floatValue];
        self.planImageURL = firstIssue[@"plan_image"];

        NSLog(@"📐 Plan dimensions: width = %f, height = %f", self.planWidth, self.planHeight);
        NSLog(@"🗺 Found %lu locations", (unsigned long)self.locations.count);
        NSLog(@"🖼 Plan image URL: %@", self.planImageURL);
        NSLog(@"🧭 plan_id = %@ ", self.planID);

        // Update UI on main thread
        dispatch_async(dispatch_get_main_queue(), ^{
            [self displayPlanImage];
            [self debugPrintAllIssues];

            // 🧭 Auto-lock logic for edit mode
            if ([self.action isEqualToString:@"edit_issue"]) {
                NSLog(@"✏️ Edit mode detected — will auto-select issue location after image loads");

                NSString *posX = [NSString stringWithFormat:@"%@", self.issueContent[@"pos_x"] ?: @""];
                NSString *posY = [NSString stringWithFormat:@"%@", self.issueContent[@"pos_y"] ?: @""];
                self.tappedPlanX = [posX floatValue];
                self.tappedPlanY = [posY floatValue];

                NSString *locationName = self.locationName;
                self.selectedLocation = locationName;

                // Wait until planImageView has a valid image
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    if (self.planImageView.image) {
                        [self highlightExistingIssueAtCoordinates:self.tappedPlanX Y:self.tappedPlanY];
                        [self showAddIssuePopup];
                    } else {
                        NSLog(@"⚠️ Plan image not ready, retrying highlight...");
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            [self highlightExistingIssueAtCoordinates:self.tappedPlanX Y:self.tappedPlanY];
                            [self showAddIssuePopup];
                        });
                    }
                });
            }
        });
    }];
}


- (void)highlightExistingIssueAtCoordinates:(CGFloat)x Y:(CGFloat)y {
    NSLog(@"📍 Highlighting existing issue at (%.2f, %.2f)", x, y);

    if (!self.planImageView.image) {
        NSLog(@"⚠️ Plan image not ready yet");
        return;
    }

    CGRect imageRect = [self imageRectInImageView:self.planImageView];
    CGFloat displayedWidth = imageRect.size.width;
    CGFloat displayedHeight = imageRect.size.height;
    CGFloat scaleX = displayedWidth / self.planWidth;
    CGFloat scaleY = displayedHeight / self.planHeight;

    CGFloat tapX = imageRect.origin.x + (x * scaleX);
    CGFloat tapY = imageRect.origin.y + (y * scaleY);

    // Visual marker
    [self.markerView removeFromSuperview];
    UIView *marker = [[UIView alloc] initWithFrame:CGRectMake(tapX - 6, tapY - 6, 12, 12)];
    marker.backgroundColor = [UIColor redColor];
    marker.layer.cornerRadius = 6;
    marker.layer.borderColor = UIColor.whiteColor.CGColor;
    marker.layer.borderWidth = 2.0;
    [self.planImageView addSubview:marker];
    self.markerView = marker;

    // Try to find which location it falls inside
    for (int i = 0; i < self.locations.count; i++) {
        NSDictionary *locationData = self.locations[i];
        if ([self isPoint:CGPointMake(tapX, tapY) insideLocation:locationData]) {
            NSLog(@"✅ Auto-selected location: %@", locationData[@"name"]);
            self.selectedLocation = locationData[@"name"];
            self.selectionLocked = YES;
            [self showAddIssuePopup];
            break;
        }
    }
}

- (void)displayPlanImage {
    if (!self.planImageURL || self.planImageURL.length == 0) {
        NSLog(@"⚠️ No plan image URL found");
        return;
    }

    NSURL *url = [NSURL URLWithString:self.planImageURL];
    if (!url) {
        NSLog(@"⚠️ Invalid plan image URL: %@", self.planImageURL);
        return;
    }

    NSLog(@"⬇️ Downloading plan image from %@", self.planImageURL);
    NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url
                                                             completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error || !data) {
            NSLog(@"❌ Failed to download plan image: %@", error.localizedDescription);
            return;
        }

        UIImage *image = [UIImage imageWithData:data];
        if (!image) {
            NSLog(@"⚠️ Could not decode image data");
            return;
        }

        dispatch_async(dispatch_get_main_queue(), ^{
            self.planImageView.image = image;
            self.planImageView.userInteractionEnabled = YES;
            UITapGestureRecognizer *tapRecognizer =
                [[UITapGestureRecognizer alloc] initWithTarget:self
                                                        action:@selector(handleTapOnPlan:)];
            [self.planImageView addGestureRecognizer:tapRecognizer];
            [self.scrollView setZoomScale:1.0 animated:NO];
            [self.view setNeedsLayout];
            [self.view layoutIfNeeded];
            [self renderAllLocations:self.locations];
            NSLog(@"✅ Plan image displayed successfully");
        });
    }];
    [task resume];
}

- (void)handleTapOnPlan:(UITapGestureRecognizer *)recognizer {
    if (self.selectionLocked) return;

    CGPoint tapPoint = [recognizer locationInView:self.planImageView];
    NSLog(@"👆 User tapped on screen at: %@", NSStringFromCGPoint(tapPoint));

    // Get image display rect and scaling ratios
    CGRect imageRect = [self imageRectInImageView:self.planImageView];
    CGFloat displayedWidth = imageRect.size.width;
    CGFloat displayedHeight = imageRect.size.height;
    CGFloat scaleX = displayedWidth / self.planWidth;
    CGFloat scaleY = displayedHeight / self.planHeight;

    // 🔹 Convert back to original plan coordinates
    CGFloat planX = (tapPoint.x - imageRect.origin.x) / scaleX;
    CGFloat planY = (tapPoint.y - imageRect.origin.y) / scaleY;
    NSLog(@"🧭 Original plan coordinates: (%.2f, %.2f)", planX, planY);
  
    self.tappedPlanX = planX;
    self.tappedPlanY = planY;

    // Optional: Visual marker
    [self.markerView removeFromSuperview];
    UIView *marker = [[UIView alloc] initWithFrame:CGRectMake(tapPoint.x - 6, tapPoint.y - 6, 12, 12)];
    marker.backgroundColor = [UIColor redColor];
    marker.layer.cornerRadius = 6;
    marker.layer.borderColor = UIColor.whiteColor.CGColor;
    marker.layer.borderWidth = 2.0;
    [self.planImageView addSubview:marker];
    self.markerView = marker;

    // Continue with polygon detection
    for (int i = 0; i < self.locations.count; i++) {
        NSDictionary *locationData = self.locations[i];
        CAShapeLayer *overlay = self.overlayLayers[i];
        
        if ([self isPoint:tapPoint insideLocation:locationData]) {
            NSLog(@"✅ Tap inside location: %@", locationData[@"name"]);
            overlay.strokeColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:0.8].CGColor;
            self.selectedOverlay = overlay;
            self.selectionLocked = YES;
            self.selectedLocation = locationData[@"name"];
            [self showAddIssuePopup];
        } else {
            overlay.strokeColor = [UIColor colorWithWhite:0.6 alpha:0.5].CGColor;
            overlay.fillColor = UIColor.clearColor.CGColor;
        }
    }
}

- (BOOL)isPoint:(CGPoint)point insideLocation:(NSDictionary *)locationData {
    CGFloat planWidth = self.planWidth;
    CGFloat planHeight = self.planHeight;
    if (planWidth == 0 || planHeight == 0) return NO;

    CGRect imageRect = AVMakeRectWithAspectRatioInsideRect(
        CGSizeMake(planWidth, planHeight),
        self.planImageView.bounds
    );

    CGFloat scaleX = imageRect.size.width / planWidth;
    CGFloat scaleY = imageRect.size.height / planHeight;

    NSArray *points = locationData[@"points"];
    UIBezierPath *path = [UIBezierPath bezierPath];

    for (int i = 0; i < points.count; i++) {
        NSDictionary *p = points[i];
        CGFloat x = imageRect.origin.x + [p[@"x"] doubleValue] * scaleX;
        CGFloat y = imageRect.origin.y + [p[@"y"] doubleValue] * scaleY;

        if (i == 0) [path moveToPoint:CGPointMake(x, y)];
        else [path addLineToPoint:CGPointMake(x, y)];
    }
    [path closePath];

    return [path containsPoint:point];
}

#pragma mark - UI Creation
- (void)createHeader {
    // 🟩 Status bar background
    UIView *statusBarBackground = [[UIView alloc] init];
    statusBarBackground.backgroundColor = [UIColor colorWithRed:0/255.0
                                                          green:109/255.0
                                                           blue:141/255.0
                                                          alpha:1];
    statusBarBackground.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:statusBarBackground];
    
    // 🟦 Header background
    self.headerView = [[UIView alloc] init];
    self.headerView.backgroundColor = statusBarBackground.backgroundColor;
    self.headerView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.headerView];

    // 🔙 Back button
    self.backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.backButton.translatesAutoresizingMaskIntoConstraints = NO;
    UIImage *backImage = [[UIImage systemImageNamed:@"chevron.left"]
                          imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    [self.backButton setImage:backImage forState:UIControlStateNormal];
    self.backButton.tintColor = UIColor.whiteColor;
    [self.backButton addTarget:self
                        action:@selector(handleBack)
              forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:self.backButton];

    // ❓ Help button
//    self.helpButton = [UIButton buttonWithType:UIButtonTypeSystem];
//    self.helpButton.translatesAutoresizingMaskIntoConstraints = NO;
//    UIImage *helpImage = [[UIImage systemImageNamed:@"questionmark.circle"]
//                           imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
//    [self.helpButton setImage:helpImage forState:UIControlStateNormal];
//    self.helpButton.tintColor = UIColor.whiteColor;
//    [self.helpButton addTarget:self
//                        action:@selector(showTutorial)
//              forControlEvents:UIControlEventTouchUpInside];
//    [self.headerView addSubview:self.helpButton];

    // 🏷 Title label (project name)
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.titleLabel.text = self.projectName ?: @"Plan Viewer";
    self.titleLabel.textColor = UIColor.whiteColor;
    self.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.headerView addSubview:self.titleLabel];

    // 🧩 Subtitle label (project code)
    UILabel *subtitleLabel = [[UILabel alloc] init];
    subtitleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    subtitleLabel.text = self.projectCode ?: @"";
    subtitleLabel.textColor = [UIColor colorWithWhite:1.0 alpha:0.8];
    subtitleLabel.font = [UIFont systemFontOfSize:15 weight:UIFontWeightRegular];
    subtitleLabel.textAlignment = NSTextAlignmentCenter;
    [self.headerView addSubview:subtitleLabel];

    // ✅ Constraints
    UILayoutGuide *safe = self.view.safeAreaLayoutGuide;
    CGFloat headerHeight = 110.0; // header height

    [NSLayoutConstraint activateConstraints:@[
        // Status bar background
        [statusBarBackground.topAnchor constraintEqualToAnchor:self.view.topAnchor],
        [statusBarBackground.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [statusBarBackground.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [statusBarBackground.bottomAnchor constraintEqualToAnchor:safe.topAnchor],

        // Header
        [self.headerView.topAnchor constraintEqualToAnchor:safe.topAnchor],
        [self.headerView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.headerView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.headerView.heightAnchor constraintEqualToConstant:headerHeight],

        // Back button
        [self.backButton.leadingAnchor constraintEqualToAnchor:self.headerView.leadingAnchor constant:8],
        [self.backButton.topAnchor constraintEqualToAnchor:self.headerView.topAnchor constant:4],
        [self.backButton.widthAnchor constraintEqualToConstant:44],
        [self.backButton.heightAnchor constraintEqualToConstant:44],

        // Help button
//        [self.helpButton.trailingAnchor constraintEqualToAnchor:self.headerView.trailingAnchor constant:-8],
//        [self.helpButton.centerYAnchor constraintEqualToAnchor:self.backButton.centerYAnchor],
//        [self.helpButton.widthAnchor constraintEqualToConstant:44],
//        [self.helpButton.heightAnchor constraintEqualToConstant:44],

        // Title label (below buttons, left-aligned)
        [self.titleLabel.topAnchor constraintEqualToAnchor:self.backButton.bottomAnchor constant:4],
        [self.titleLabel.leadingAnchor constraintEqualToAnchor:self.headerView.leadingAnchor constant:16],
//        [self.titleLabel.trailingAnchor constraintLessThanOrEqualToAnchor:self.helpButton.leadingAnchor constant:-8],

        // Subtitle (below title, left-aligned)
        [subtitleLabel.topAnchor constraintEqualToAnchor:self.titleLabel.bottomAnchor constant:2],
        [subtitleLabel.leadingAnchor constraintEqualToAnchor:self.titleLabel.leadingAnchor],
//        [subtitleLabel.trailingAnchor constraintLessThanOrEqualToAnchor:self.helpButton.leadingAnchor constant:-8],
    ]];
}

- (void)loadPlanImageFromURL:(NSString *)urlString {
    NSURL *url = [NSURL URLWithString:urlString];
    if (!url) return;

    NSURLSessionDataTask *task = [[NSURLSession sharedSession]
        dataTaskWithURL:url
      completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error) {
            NSLog(@"❌ Failed to load image: %@", error);
            return;
        }
        UIImage *image = [UIImage imageWithData:data];
        if (image) {
            dispatch_async(dispatch_get_main_queue(), ^{
                self.planImageView.image = image;
                NSLog(@"🖼 Plan image loaded successfully");
            });
        }
    }];
    [task resume];
}

- (void)showAlertWithTitle:(NSString *)title message:(NSString *)message {
    dispatch_async(dispatch_get_main_queue(), ^{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:title
                                                                       message:message
                                                                preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alert animated:YES completion:nil];
    });
}


- (void)createScrollView {
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.delegate = (id<UIScrollViewDelegate>)self;
    self.scrollView.minimumZoomScale = 1.0;
    self.scrollView.maximumZoomScale = 5.0;
    self.scrollView.bouncesZoom = YES;
    self.scrollView.alwaysBounceVertical = YES;
    self.scrollView.alwaysBounceHorizontal = YES;
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.scrollView];

    self.planImageView = [[UIImageView alloc] init];
    self.planImageView.contentMode = UIViewContentModeScaleAspectFit;
    self.planImageView.backgroundColor = [UIColor whiteColor];
    self.planImageView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.scrollView addSubview:self.planImageView];

    // ✅ Scroll view constraints (below header)
    [NSLayoutConstraint activateConstraints:@[
        [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],
    ]];

    // ✅ Image view constraints (fills scroll view)
    [NSLayoutConstraint activateConstraints:@[
        [self.planImageView.topAnchor constraintEqualToAnchor:self.scrollView.topAnchor],
        [self.planImageView.leadingAnchor constraintEqualToAnchor:self.scrollView.leadingAnchor],
        [self.planImageView.trailingAnchor constraintEqualToAnchor:self.scrollView.trailingAnchor],
        [self.planImageView.bottomAnchor constraintEqualToAnchor:self.scrollView.bottomAnchor],
        [self.planImageView.widthAnchor constraintEqualToAnchor:self.scrollView.widthAnchor],
        [self.planImageView.heightAnchor constraintEqualToAnchor:self.scrollView.heightAnchor],
    ]];
}

- (void)renderLocation:(NSDictionary *)locationData onImageView:(UIImageView *)planImageView {
    if (!planImageView.image) return;

    CGRect imageRect = [self imageRectInImageView:planImageView];
    CGFloat displayedWidth = imageRect.size.width;
    CGFloat displayedHeight = imageRect.size.height;

    NSArray *issues = locationData[@"issue"];
    NSLog(@"Total issues: %lu", (unsigned long)issues.count);

    NSLog(@"planWidth: %f, planHeight: %f", self.planWidth, self.planHeight);

    CGFloat scaleX = displayedWidth / self.planWidth;
    CGFloat scaleY = displayedHeight / self.planHeight;

    NSArray *points = locationData[@"points"];
    if (!points || points.count == 0) {
        NSLog(@"⚠️ No points found for location %@", locationData[@"id"]);
        return;
    }

    UIBezierPath *path = [UIBezierPath bezierPath];

    for (int i = 0; i < points.count; i++) {
        NSDictionary *point = points[i];
        CGFloat x = imageRect.origin.x + [point[@"x"] doubleValue] * scaleX;
        CGFloat y = imageRect.origin.y + [point[@"y"] doubleValue] * scaleY;

        if (i == 0) [path moveToPoint:CGPointMake(x, y)];
        else [path addLineToPoint:CGPointMake(x, y)];

        NSLog(@"📍 Point %d -> x=%f, y=%f", i, x, y);

        if (x < imageRect.origin.x || y < imageRect.origin.y ||
            x > imageRect.origin.x + imageRect.size.width ||
            y > imageRect.origin.y + imageRect.size.height) {
            NSLog(@"⚠️ Point %d is out of bounds!", i);
        }
    }

    [path closePath];

    CAShapeLayer *polygonLayer = [CAShapeLayer layer];
    polygonLayer.path = path.CGPath;
    polygonLayer.fillColor = UIColor.clearColor.CGColor;
    polygonLayer.strokeColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:0.3].CGColor;
    polygonLayer.lineWidth = 1.0;

    [self.overlayLayers addObject:polygonLayer];
    [planImageView.layer addSublayer:polygonLayer];
}

- (CGRect)imageRectInImageView:(UIImageView *)imageView {
    CGSize imageSize = imageView.image.size;
    CGSize viewSize = imageView.bounds.size;
    CGFloat scale = MIN(viewSize.width / imageSize.width, viewSize.height / imageSize.height);
    CGFloat width = imageSize.width * scale;
    CGFloat height = imageSize.height * scale;
    CGFloat x = (viewSize.width - width) / 2.0;
    CGFloat y = (viewSize.height - height) / 2.0;
    return CGRectMake(x, y, width, height);
}

- (void)renderAllLocations:(NSArray *)locations {
    for (NSDictionary *locationData in locations) {
        [self renderLocation:locationData onImageView:self.planImageView];
    }
}

- (UIColor *)colorFromHex:(NSString *)hexString {
    unsigned int rgbValue = 0;
    NSScanner *scanner = [NSScanner scannerWithString:[hexString stringByReplacingOccurrencesOfString:@"#" withString:@""]];
    [scanner scanHexInt:&rgbValue];
    return [UIColor colorWithRed:((rgbValue >> 16) & 0xFF) / 255.0
                           green:((rgbValue >> 8) & 0xFF) / 255.0
                            blue:(rgbValue & 0xFF) / 255.0
                           alpha:1.0];
}


- (void)handleNextScreen {
  [self showAddIssuePopup];
}

- (void)showAddIssuePopup {
    NSLog(@"🟢 Showing Add Issue popup");

    // Background dim view
    UIView *overlay = [[UIView alloc] initWithFrame:self.view.bounds];
    overlay.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.4];
    overlay.alpha = 0.0;
    overlay.tag = 999; // so we can find and remove it later
    [self.view addSubview:overlay];

    // Popup container
    CGFloat safeBottom = self.view.safeAreaInsets.bottom;
    CGFloat popupHeight = 180 + safeBottom;
    UIView *popup = [[UIView alloc] initWithFrame:CGRectMake(0,
                                                             self.view.bounds.size.height,
                                                             self.view.bounds.size.width,
                                                             popupHeight)];
    popup.backgroundColor = UIColor.whiteColor;
    popup.layer.cornerRadius = 16;
    popup.layer.maskedCorners = kCALayerMinXMinYCorner | kCALayerMaxXMinYCorner;
    popup.clipsToBounds = YES;
    popup.tag = 1000;
    [self.view addSubview:popup];

    // Label — “You have selected”
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, popup.bounds.size.width - 40, 20)];
    label.text = @"You have selected:";
    label.textColor = [UIColor blackColor];
    label.font = [UIFont systemFontOfSize:15 weight:UIFontWeightRegular];
    [popup addSubview:label];

    // Mock location name
    UILabel *locationLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 50, popup.bounds.size.width - 40, 24)];
    locationLabel.text = @"Building A - 2nd Floor";
    locationLabel.text = self.selectedLocation;
    NSLog(@"self.selectedLocation %@", self.selectedLocation);
    locationLabel.textColor = [UIColor blackColor];
    locationLabel.font = [UIFont boldSystemFontOfSize:17];
    [popup addSubview:locationLabel];

    // Buttons row
    CGFloat buttonWidth = (self.view.bounds.size.width - 48) / 2;
    CGFloat buttonY = popupHeight - 60 - safeBottom; // ✅ push up above safe area

    UIButton *reselectButton = [UIButton buttonWithType:UIButtonTypeSystem];
    reselectButton.frame = CGRectMake(16, buttonY, buttonWidth, 44);
    [reselectButton setTitle:@"Reselect" forState:UIControlStateNormal];
    [reselectButton setTitleColor:[UIColor colorWithRed:0/255.0 green:109/255.0 blue:141/255.0 alpha:1]
                         forState:UIControlStateNormal];
    reselectButton.layer.borderWidth = 1.0;
    reselectButton.layer.borderColor = [UIColor colorWithRed:0/255.0 green:109/255.0 blue:141/255.0 alpha:1].CGColor;
    reselectButton.layer.cornerRadius = 8;
    [reselectButton addTarget:self action:@selector(dismissAddIssuePopup)
             forControlEvents:UIControlEventTouchUpInside];
    [popup addSubview:reselectButton];

    UIButton *nextButton = [UIButton buttonWithType:UIButtonTypeSystem];
    nextButton.frame = CGRectMake(32 + buttonWidth, buttonY, buttonWidth, 44);
    [nextButton setTitle:@"Next" forState:UIControlStateNormal];
    [nextButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    nextButton.backgroundColor = [UIColor colorWithRed:0/255.0 green:109/255.0 blue:141/255.0 alpha:1];
    nextButton.layer.cornerRadius = 8;
    [nextButton addTarget:self action:@selector(handleConfirmAddIssue)
         forControlEvents:UIControlEventTouchUpInside];
    [popup addSubview:nextButton];
  
    // Animate in
    [UIView animateWithDuration:0.3 animations:^{
        overlay.alpha = 1.0;
        popup.frame = CGRectMake(0,
                                 self.view.bounds.size.height - popupHeight,
                                 self.view.bounds.size.width,
                                 popupHeight);
    }];
}

- (void)dismissAddIssuePopup {
    NSLog(@"❌ Dismissing Add Issue popup");
    self.selectionLocked = NO;

    UIView *overlay = [self.view viewWithTag:999];
    UIView *popup = [self.view viewWithTag:1000];

    [UIView animateWithDuration:0.25 animations:^{
        overlay.alpha = 0.0;
        popup.frame = CGRectMake(0,
                                 self.view.bounds.size.height,
                                 popup.bounds.size.width,
                                 popup.bounds.size.height);
    } completion:^(BOOL finished) {
        [overlay removeFromSuperview];
        [popup removeFromSuperview];
    }];
}

- (void)handleConfirmAddIssue {
    NSLog(@"✅ Confirm Add Issue pressed");
    
    self.selectionLocked = NO;
    [self dismissAddIssuePopup];
  
    
    // === 1️⃣ Find the matching location ID ===
    NSString *selectedName = self.selectedLocation;
  
    NSLog(@"self.unitPlanLocation: %@, self.selectedLocation: %@", self.unitPlanLocations, self.selectedLocation);

    for (NSDictionary *loc in self.unitPlanLocations) {
        NSString *locName = loc[@"location_name"] ?: loc[@"name"];
        NSString *locID   = [NSString stringWithFormat:@"%@", loc[@"location_id"] ?: loc[@"id"]];
        
        if ([locName isEqualToString:self.selectedLocation]) {
            self.locationID = locID;
            NSLog(@"✅ Matched location: %@ → ID %@", locName, locID);
            break;
        }
    }

    if (self.locationID) {
        NSLog(@"📡 Fetching settings for location %@ and plan %@", self.locationID, self.planID);
        [self handleSettingsByLocation:self.locationID planID:self.planID];
    } else {
        NSLog(@"⚠️ No match found for %@", self.selectedLocation);
    }
}


- (void)handleSettingsByLocation:(NSString *)locationID planID:(NSString *)planID {
    [AddIssueAPIClient fetchSettingsByLocation:locationID
                                     projectID:@"8"
                                    completion:^(NSDictionary *data, NSError *error) {
        if (error) {
            NSLog(@"❌ Error fetching settings: %@", error);
            return;
        }

        NSDictionary *appData = data[@"AppData"];
        NSDictionary *mainData = data[@"Data"];
        NSNumber *statusCode = data[@"status_code"];

        // === 1️⃣ Basic error checks ===
        if (statusCode && statusCode.intValue != 200 && statusCode.intValue != 0) {
            NSLog(@"Error, Server returned %@", statusCode);
            return;
        }

        if ([appData[@"error_code"] integerValue] == 503) {
            NSLog(@"Maintenance Mode, Server temporarily unavailable");
            return;
        }

        // === 2️⃣ Success case ===
        if ([appData[@"status"] isEqualToString:@"success"] && mainData) {
            NSLog(@"✅ Location settings loaded successfully");

            NSString *defectMatrix = mainData ? @"YES" : @"NO";

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)),
                           dispatch_get_main_queue(), ^{
                [self navigateToAddIssueDetailsWithLocationData:mainData defectMatrix:defectMatrix];
            });
            return;
        }

        // === 3️⃣ Fallback and special message handling ===
        NSString *message = appData[@"message"] ?: @"Unknown server response.";
        if ([message isEqualToString:@"user_not_found"]) {
            NSLog(@"Session Expired, Please log in again");
        } else if ([message.lowercaseString containsString:@"defect matrix not found"] ||
                   [message.lowercaseString containsString:@"location not found"]) {
            [self navigateToAddIssueDetailsWithLocationData:nil defectMatrix:@"NO"];
        } else {
            NSLog(@"Error %@", message);
        }
    }];
}

- (void)navigateToAddIssueDetailsWithLocationData:(NSDictionary *)mainData defectMatrix:(NSString *)defectMatrix {
    AddIssueDetailsViewController *nextVC = [[AddIssueDetailsViewController alloc] init];
    nextVC.modalPresentationStyle = UIModalPresentationFullScreen;
    
    nextVC.planID = self.planID;
    nextVC.locationID = self.locationID;
    nextVC.selectedLocationName = self.selectedLocation;
    nextVC.locationData = mainData;
    nextVC.defectMatrix = defectMatrix;
    nextVC.projectCode = self.projectCode ?: @"";
    nextVC.projectName = self.unitName;
    nextVC.planX = self.tappedPlanX;
    nextVC.planY = self.tappedPlanY;
    
    //edit info
    nextVC.action = self.action;
    nextVC.issueFullData = self.issueFullData;
    nextVC.issueContent = self.issueContent;
    nextVC.locationName = self.locationName;

    NSLog(@"📦 Data being brought over:\n planID: %@\n locationID: %@\n selectedLocationName: %@\n defectMatrix: %@\n projectName: %@\n projectCode: %@\n XCoordinates: %f\n YCoordinates: %f\n locationData: %@\n action: %@\n issueFullData: %@\n issueContent: %@",
          nextVC.planID,
          nextVC.locationID,
          nextVC.selectedLocationName,
          nextVC.defectMatrix,
          nextVC.projectName,
          nextVC.projectCode,
          nextVC.planX,
          nextVC.planY,
          nextVC.locationData,
          nextVC.action,
          nextVC.issueFullData,
          nextVC.issueContent);

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

#pragma mark - Actions

- (void)handleBack {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)showTutorial {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Help"
                                                                   message:@"This would show the tutorial (e.g. step1/step2/step3)."
                                                            preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - UIScrollViewDelegate

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return self.planImageView;
}

#pragma mark - Status Bar Style
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent; // ✅ White text/icons
}

- (void)debugPrintAllIssues {
    for (NSDictionary *loc in self.locations) {
        NSString *roomName = loc[@"name"];
        NSArray *issues = loc[@"issue"];

        NSLog(@"📍 Room: %@ (%lu issues)", roomName, (unsigned long)issues.count);
        for (NSDictionary *issue in issues) {
            NSString *title = issue[@"issue"];
            NSString *status = issue[@"status_internal"];
            NSString *x = issue[@"pos_x"];
            NSString *y = issue[@"pos_y"];
            NSString *color = issue[@"status_in_color"];

            NSLog(@"   - %@ [%@] (x:%@, y:%@, color:%@)", title, status, x, y, color);
        }
    }
}

@end
