// PlanViewController.mm
#import "PlanViewController.h"
#import "DetailsViewController.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;

@end

@implementation PlanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;
    NSLog(@"PlanViewController loaded");

    // Create UI elements (but don’t assign final frames yet)
    [self createHeader];
    [self createScrollView];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

    CGFloat topInset = self.view.safeAreaInsets.top;
    CGFloat headerHeight = 48.0;

    // Layout header
    self.headerView.frame = CGRectMake(0, topInset, self.view.bounds.size.width, headerHeight);

    // Layout items within header
    self.backButton.frame = CGRectMake(12, 8, 32, 32);
    self.helpButton.frame = CGRectMake(self.headerView.bounds.size.width - 44, 8, 32, 32);
    self.titleLabel.frame = CGRectMake(0, 8, self.headerView.bounds.size.width, 32);

    // Layout scroll view
    CGFloat scrollY = topInset + headerHeight;
    self.scrollView.frame = CGRectMake(0, scrollY, self.view.bounds.size.width, self.view.bounds.size.height - scrollY);
    self.planImageView.frame = self.scrollView.bounds;

    [self.view bringSubviewToFront:self.headerView];
}

#pragma mark - UI Creation

- (void)createHeader {
    // 🟩 Status bar background view
    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 view
    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];

    // Title label
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.titleLabel.text = @"Plan Viewer";
    self.titleLabel.textColor = UIColor.whiteColor;
    self.titleLabel.font = [UIFont systemFontOfSize:18 weight:UIFontWeightMedium];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.headerView addSubview:self.titleLabel];

    // 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];

    // ✅ Constraints
    UILayoutGuide *safe = self.view.safeAreaLayoutGuide;
    [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 pinned below safe area
        [self.headerView.topAnchor constraintEqualToAnchor:safe.topAnchor],
        [self.headerView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.headerView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.headerView.heightAnchor constraintEqualToConstant:48],

        // Back button
        [self.backButton.leadingAnchor constraintEqualToAnchor:self.headerView.leadingAnchor constant:8],
        [self.backButton.centerYAnchor constraintEqualToAnchor:self.headerView.centerYAnchor],
        [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.headerView.centerYAnchor],
        [self.helpButton.widthAnchor constraintEqualToConstant:44],
        [self.helpButton.heightAnchor constraintEqualToConstant:44],

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

- (void)createScrollView {
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.delegate = (id<UIScrollViewDelegate>)self;
    self.scrollView.minimumZoomScale = 1.0;
    self.scrollView.maximumZoomScale = 5.0;
    [self.view addSubview:self.scrollView];
    
    self.planImageView = [[UIImageView alloc] init];
    self.planImageView.contentMode = UIViewContentModeScaleAspectFit;
    [self.scrollView addSubview:self.planImageView];

    UIImage *testImage = [UIImage imageNamed:@"image_placeholder"];
    if (!testImage) {
        NSLog(@"❌ image_placeholder not found in bundle!");
        self.planImageView.backgroundColor = [UIColor whiteColor];

        // 👉 Temporary test button
        UIButton *testButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [testButton setTitle:@"Next Screen →" forState:UIControlStateNormal];
        testButton.titleLabel.font = [UIFont boldSystemFontOfSize:18];
        [testButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        testButton.backgroundColor = [UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0];
        testButton.layer.cornerRadius = 8;
        testButton.clipsToBounds = YES;

        // Add simple frame — will center it later in viewDidLayoutSubviews
        testButton.frame = CGRectMake(0, 0, 200, 50);
        testButton.center = self.view.center;

        [testButton addTarget:self
                       action:@selector(handleNextScreen)
             forControlEvents:UIControlEventTouchUpInside];

        // Add directly on top of main view (not inside scrollView)
        [self.view addSubview:testButton];
    } else {
        self.planImageView.image = testImage;
    }
}

- (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";
    self.selectedLocation = locationLabel.text;
    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");

    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");

    // Dismiss popup first
    [self dismissAddIssuePopup];

    // Then open AddIssueDetailsViewController after a short delay
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        AddIssueDetailsViewController *nextVC = [[AddIssueDetailsViewController alloc] init];
        nextVC.selectedLocationName = self.selectedLocation; // ✅ Pass it here
        nextVC.modalPresentationStyle = UIModalPresentationFullScreen;
        [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
}

@end
