//  AppointmentTutorialViewController.mm
#import "AppointmentTutorialViewController.h"
#import "TutorialBubbleView.h"
#import "TutorialStep.h"

@interface AppointmentTutorialViewController ()

@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIButton *backButton;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *skipButton;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UIImageView *tutorialImageView;
@property (nonatomic, strong) NSArray<UIImage *> *tutorialImages;
@property (nonatomic, strong) NSArray<TutorialStep *> *steps;
@property (nonatomic, strong) TutorialBubbleView *bubbleView;
@property (nonatomic, assign) BOOL didLayoutInitialPage;

@end

@implementation AppointmentTutorialViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  self.view.backgroundColor = UIColor.systemBackgroundColor;
  self.didLayoutInitialPage = NO;
  
  [self setupHeader];
  [self setupContent];
  [self setupTutorialData];
  [self setupBubble];
  [self.view bringSubviewToFront:self.headerView];

}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    if (!self.didLayoutInitialPage) {
        self.didLayoutInitialPage = YES;
        // showPage now that layout is ready
        [self showPage:self.currentPage];
    } else {
        // update bubble position for rotation / layout changes
        [self updateBubblePosition];
    }
}

#pragma mark - Header Setup
- (void)setupHeader {
  self.headerView = [[UIView alloc] init];
  self.headerView.backgroundColor = [UIColor colorWithRed:0.0 green:0.5 blue:0.6 alpha:1.0];
  self.headerView.translatesAutoresizingMaskIntoConstraints = NO;
  [self.view addSubview:self.headerView];
  
  self.backButton = [UIButton buttonWithType:UIButtonTypeCustom];
  [self.backButton setImage:[UIImage systemImageNamed:@"chevron.backward"]
                   forState:UIControlStateNormal];
  self.backButton.tintColor = UIColor.whiteColor;
  [self.backButton addTarget:self
                      action:@selector(onBack)
            forControlEvents:UIControlEventTouchUpInside];
  self.backButton.translatesAutoresizingMaskIntoConstraints = NO;
  [self.headerView addSubview:self.backButton];
  
  self.titleLabel = [[UILabel alloc] init];
  self.titleLabel.text = @"Add Appintment Tutorial";
  self.titleLabel.textColor = UIColor.whiteColor;
  self.titleLabel.font = [UIFont boldSystemFontOfSize:18];
  self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
  [self.headerView addSubview:self.titleLabel];
  
  self.skipButton = [UIButton buttonWithType:UIButtonTypeSystem];
  [self.skipButton setTitle:@"Skip" forState:UIControlStateNormal];
  self.skipButton.tintColor = UIColor.whiteColor;
  self.skipButton.layer.borderColor = UIColor.whiteColor.CGColor;
  self.skipButton.layer.borderWidth = 0.5;
  self.skipButton.layer.cornerRadius = 14;
  self.skipButton.titleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
  [self.skipButton addTarget:self
                      action:@selector(onSkip)
            forControlEvents:UIControlEventTouchUpInside];
  self.skipButton.translatesAutoresizingMaskIntoConstraints = NO;
  [self.headerView addSubview:self.skipButton];

  // Initially visible on first screen
  self.skipButton.hidden = NO;

  [NSLayoutConstraint activateConstraints:@[
    [self.headerView.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor],
    [self.headerView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
    [self.headerView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
    [self.headerView.heightAnchor constraintEqualToConstant:44],
    
    [self.backButton.leadingAnchor constraintEqualToAnchor:self.headerView.leadingAnchor constant:16],
    [self.backButton.centerYAnchor constraintEqualToAnchor:self.headerView.centerYAnchor],
    [self.backButton.widthAnchor constraintEqualToConstant:24],
    [self.backButton.heightAnchor constraintEqualToConstant:24],
    
    [self.skipButton.trailingAnchor constraintEqualToAnchor:self.headerView.trailingAnchor constant:-16],
    [self.skipButton.centerYAnchor constraintEqualToAnchor:self.headerView.centerYAnchor],
    
    [self.titleLabel.centerXAnchor constraintEqualToAnchor:self.headerView.centerXAnchor],
    [self.titleLabel.centerYAnchor constraintEqualToAnchor:self.headerView.centerYAnchor],
  ]];
}

#pragma mark - Content
- (void)setupContent {
    self.contentView = [[UIView alloc] init];
    self.contentView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.contentView];

    self.tutorialImageView = [[UIImageView alloc] init];
    self.tutorialImageView.translatesAutoresizingMaskIntoConstraints = NO;
    self.tutorialImageView.contentMode = UIViewContentModeScaleAspectFill;
    self.tutorialImageView.clipsToBounds = YES;
    [self.contentView addSubview:self.tutorialImageView];

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

        [self.tutorialImageView.topAnchor constraintEqualToAnchor:self.contentView.topAnchor],
        [self.tutorialImageView.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor],
        [self.tutorialImageView.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor],
        [self.tutorialImageView.bottomAnchor constraintEqualToAnchor:self.contentView.bottomAnchor],
    ]];
}

#pragma mark - Tutorial Data
- (void)setupTutorialData {
    // Using black placeholder images for testing
    NSBundle *bundle = [NSBundle bundleForClass:[self class]];
    UIImage *img1 = [UIImage imageNamed:@"img_tutorial_ma01"
                               inBundle:bundle
          compatibleWithTraitCollection:nil];
    UIImage *img2 = [UIImage imageNamed:@"img_tutorial_ma02"
                               inBundle:bundle
          compatibleWithTraitCollection:nil];
    UIImage *img3 = [UIImage imageNamed:@"img_tutorial_ma03"
                               inBundle:bundle
          compatibleWithTraitCollection:nil];
  
    self.tutorialImages = @[img1, img2, img3];

    self.steps = @[
        ({
            TutorialStep *s = [TutorialStep new];
            s.text = @"Select appointment date.";
            s.anchorPoint = CGPointMake(0.63, 0.5);
            s.bubbleAbove = NO;
            s;
        }),
        ({
            TutorialStep *s = [TutorialStep new];
            s.text = @"Select appointment time slot.";
            s.anchorPoint = CGPointMake(0.4, 0.32);
            s.bubbleAbove = NO;
            s;
        }),
        ({
            TutorialStep *s = [TutorialStep new];
            s.text = @"Select \"Confirm\" button to confirm appointment details.";
            s.anchorPoint = CGPointMake(0.6, 0.86);
            s.bubbleAbove = YES;
            s;
        })
    ];

    self.currentPage = 0;
}

#pragma mark - Bubble
- (void)setupBubble {
    self.bubbleView = [[TutorialBubbleView alloc] init];
    self.bubbleView.translatesAutoresizingMaskIntoConstraints = NO;

    [self.bubbleView.prevButton addTarget:self
                                   action:@selector(backButtonTapped)
                         forControlEvents:UIControlEventTouchUpInside];

    [self.bubbleView.nextButton addTarget:self
                                   action:@selector(nextButtonTapped)
                         forControlEvents:UIControlEventTouchUpInside];

    [self.contentView addSubview:self.bubbleView];

    // Fixed width; height will auto-size
    [self.bubbleView.widthAnchor constraintEqualToConstant:260].active = YES;
}

#pragma mark - Helper
- (void)onBack {
  NSLog(@"on back triggered");
  [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)onSkip {
  [self completeTutorial];
}

-(void)completeTutorial {
  [self onBack];
}

-(void)updateHeaderButtons {
  self.skipButton.hidden = (self.currentPage == self.steps.count - 1);
}

- (void)showPage:(NSInteger)page {
    if (page < 0 || page >= self.tutorialImages.count) return;

    self.tutorialImageView.image = self.tutorialImages[page];
    [self updateHeaderButtons];
    [self updateBubbleContent];

    dispatch_async(dispatch_get_main_queue(), ^{
        [self updateBubblePosition];
    });
}

- (void)nextButtonTapped {
    if (self.currentPage < self.steps.count - 1) {
        self.currentPage++;
        [self showPage:self.currentPage];
    } else {
        [self completeTutorial];
    }
}

- (void)backButtonTapped {
    if (self.currentPage > 0) {
        self.currentPage--;
        [self showPage:self.currentPage];
    }
}

- (CGRect)imageFrameInImageView:(UIImageView *)imageView {
    if (!imageView.image) return CGRectZero;

    CGSize imageSize = imageView.image.size;
    CGSize viewSize = imageView.bounds.size;

    CGFloat imageRatio = imageSize.width / imageSize.height;
    CGFloat viewRatio = viewSize.width / viewSize.height;

    CGSize drawSize;

    if (imageRatio > viewRatio) {
        // Image is wider → height fills, width overflows
        drawSize.height = viewSize.height;
        drawSize.width = viewSize.height * imageRatio;
    } else {
        // Image is taller → width fills, height overflows
        drawSize.width = viewSize.width;
        drawSize.height = viewSize.width / imageRatio;
    }

    CGFloat x = (viewSize.width - drawSize.width) / 2.0;
    CGFloat y = (viewSize.height - drawSize.height) / 2.0;

    return CGRectMake(x, y, drawSize.width, drawSize.height);
}

- (CGPoint)screenPointForCurrentStep {
    TutorialStep *step = self.steps[self.currentPage];
    CGRect imageFrame = [self imageFrameInImageView:self.tutorialImageView];

    CGFloat x = imageFrame.origin.x + step.anchorPoint.x * imageFrame.size.width;
    CGFloat y = imageFrame.origin.y + step.anchorPoint.y * imageFrame.size.height;

    return CGPointMake(x, y);
}

- (void)updateBubblePosition {
    if (!self.bubbleView || !self.tutorialImageView.image) return;

    // Make sure bubble layout is up-to-date
    [self.bubbleView layoutIfNeeded];

    TutorialStep *step = self.steps[self.currentPage];
    CGPoint anchor = [self screenPointForCurrentStep];

    self.bubbleView.arrowDirection =
        step.bubbleAbove ? BubbleArrowDirectionDown : BubbleArrowDirectionUp;

    CGFloat bubbleHeight =
        [self.bubbleView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;

    CGFloat bubbleWidth = 260;
    CGFloat x = anchor.x - bubbleWidth / 2.0;
    CGFloat y = step.bubbleAbove
        ? anchor.y - bubbleHeight - 12
        : anchor.y + 12;

    self.bubbleView.frame = CGRectMake(x, y, bubbleWidth, bubbleHeight);
}

- (void)updateBubbleContent {
    TutorialStep *step = self.steps[self.currentPage];

    [self.bubbleView configureWithText:step.text
                                  step:self.currentPage
                                 total:self.steps.count
                               isFirst:self.currentPage == 0
                                isLast:self.currentPage == self.steps.count - 1];
    self.bubbleView.prevButton.hidden = (self.currentPage == 0);

}

@end
