//  ThirdTutorialViewController.mm

#import "ThirdTutorialViewController.h"

@interface ThirdPartyTutorialViewController () <UIScrollViewDelegate>
@property (nonatomic, strong) UIView *headerBar;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *backButton;
@property (nonatomic, strong) UIButton *helpButton;
@property (nonatomic, strong) UIButton *skipButton;

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIPageControl *pageControl;
@property (nonatomic, strong) UIButton *nextButton;
@property (nonatomic, strong) NSArray<NSDictionary *> *slides;
@property (nonatomic, assign) NSInteger currentIndex;

@end


@implementation ThirdPartyTutorialViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;
    [self setupHeader];
  
    self.slides = @[
        @{
            @"title": @"Need someone to handle ongoing defects on your behalf?",
            @"subtitle": @"3rd Party Link is your go-to feature for assigning and allowing authorised person to help submit your defects.",
            @"image": @"img_tutorial_tpl01"  // just the string
        },
        @{
            @"title": @"Create temporary access via weblink for your representatives",
            @"subtitle": @"The link created and shared by you will allow your authorised person to view the submitted issues.",
            @"image": @"img_tutorial_tpl02"
        },
        @{
            @"title": @"Change link access at your convenience",
            @"subtitle": @"Toggle to switch link access when you no longer need the authorised person’s assistance.",
            @"image": @"img_tutorial_tpl03"
        }
    ];

    self.currentIndex = 0;

    [self setupScrollView];
    [self setupPageControl];
    [self setupNextButton];

}

#pragma mark - Header
- (void)setupHeader {
  UILayoutGuide *safe = self.view.safeAreaLayoutGuide;
  
  //Header
  self.headerBar = [[UIView alloc] init];
  self.headerBar.backgroundColor = [UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0]; // #006D8D
  [self.view addSubview:self.headerBar];
  self.headerBar.translatesAutoresizingMaskIntoConstraints = NO;
  
  [NSLayoutConstraint activateConstraints:@[
    [self.headerBar.topAnchor constraintEqualToAnchor:safe.topAnchor],
    [self.headerBar.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
    [self.headerBar.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
    [self.headerBar.heightAnchor constraintEqualToConstant:44],
  ]];
  
  // Title
  self.titleLabel = [[UILabel alloc] init];
  self.titleLabel.text = @"What is 3rd Party Link?";
  self.titleLabel.textColor = UIColor.whiteColor;
  self.titleLabel.font = [UIFont systemFontOfSize:18 weight:UIFontWeightMedium];
  self.titleLabel.textAlignment = NSTextAlignmentCenter;
  
  // Back button
  self.backButton = [UIButton buttonWithType:UIButtonTypeSystem];
  [self.backButton setImage:[UIImage systemImageNamed:@"chevron.backward"] forState:UIControlStateNormal];
  self.backButton.tintColor = UIColor.whiteColor;
  [self.backButton addTarget:self
                      action:@selector(onBack)
            forControlEvents:UIControlEventTouchUpInside];
  
  for (UIView *sub in @[self.titleLabel, self.backButton]) {
    sub.translatesAutoresizingMaskIntoConstraints = NO;
    [self.headerBar addSubview:sub];
  }
  
  // Skip button
  self.skipButton = [UIButton buttonWithType:UIButtonTypeSystem];
  [self.skipButton setTitle:@"Skip" forState:UIControlStateNormal];
  [self.skipButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
  self.skipButton.titleLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightRegular];
  self.skipButton.layer.cornerRadius = 20;
  self.skipButton.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5]; // semi-transparent
  [self.skipButton addTarget:self action:@selector(onSkip) forControlEvents:UIControlEventTouchUpInside];
  self.skipButton.translatesAutoresizingMaskIntoConstraints = NO;
  [self.headerBar addSubview:self.skipButton];
  
  [NSLayoutConstraint activateConstraints:@[
    [self.backButton.leadingAnchor constraintEqualToAnchor:self.headerBar.leadingAnchor constant:16],
    [self.backButton.centerYAnchor constraintEqualToAnchor:self.headerBar.centerYAnchor],
    [self.backButton.heightAnchor constraintEqualToConstant:24],
    [self.backButton.widthAnchor constraintEqualToConstant:24],
    
    [self.titleLabel.centerXAnchor constraintEqualToAnchor:self.headerBar.centerXAnchor],
    [self.titleLabel.centerYAnchor constraintEqualToAnchor:self.headerBar.centerYAnchor],
    
    [self.skipButton.trailingAnchor constraintEqualToAnchor:self.headerBar.trailingAnchor constant:-12],
    [self.skipButton.centerYAnchor constraintEqualToAnchor:self.headerBar.centerYAnchor],
    [self.skipButton.heightAnchor constraintEqualToConstant:28],
    [self.skipButton.widthAnchor constraintEqualToConstant:64],
  ]];
}

#pragma mark - Scroll View
- (void)setupScrollView {
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.pagingEnabled = YES;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.delegate = self;
    self.scrollView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.scrollView];

    UILayoutGuide *safe = self.view.safeAreaLayoutGuide;
    [NSLayoutConstraint activateConstraints:@[
        [self.scrollView.topAnchor constraintEqualToAnchor:self.headerBar.bottomAnchor],
        [self.scrollView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.scrollView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.scrollView.bottomAnchor constraintEqualToAnchor:safe.bottomAnchor constant:-100] // leave space for pageControl + button
    ]];

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

    [NSLayoutConstraint activateConstraints:@[
        [contentView.topAnchor constraintEqualToAnchor:self.scrollView.topAnchor],
        [contentView.bottomAnchor constraintEqualToAnchor:self.scrollView.bottomAnchor],
        [contentView.leadingAnchor constraintEqualToAnchor:self.scrollView.leadingAnchor],
        [contentView.trailingAnchor constraintEqualToAnchor:self.scrollView.trailingAnchor],
        [contentView.heightAnchor constraintEqualToAnchor:self.scrollView.heightAnchor]
    ]];

    UIView *previousSlide = nil;
    for (NSDictionary *slide in self.slides) {
        UIView *slideView = [self createSlideWithData:slide];
        [contentView addSubview:slideView];
        slideView.translatesAutoresizingMaskIntoConstraints = NO;

        [NSLayoutConstraint activateConstraints:@[
            [slideView.topAnchor constraintEqualToAnchor:contentView.topAnchor],
            [slideView.bottomAnchor constraintEqualToAnchor:contentView.bottomAnchor],
            [slideView.widthAnchor constraintEqualToAnchor:self.view.widthAnchor]
        ]];

        if (previousSlide) {
            [slideView.leadingAnchor constraintEqualToAnchor:previousSlide.trailingAnchor].active = YES;
        } else {
            [slideView.leadingAnchor constraintEqualToAnchor:contentView.leadingAnchor].active = YES;
        }
        previousSlide = slideView;
    }

    [previousSlide.trailingAnchor constraintEqualToAnchor:contentView.trailingAnchor].active = YES;
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    NSInteger pageIndex = round(scrollView.contentOffset.x / scrollView.frame.size.width);
    self.currentIndex = pageIndex;
    self.pageControl.currentPage = pageIndex;

    // change next button title on last page
    if (pageIndex == self.slides.count - 1) {
        [self.nextButton setTitle:@"OK" forState:UIControlStateNormal];
        self.skipButton.hidden = YES; // hide skip
    } else {
        [self.nextButton setTitle:@"Next" forState:UIControlStateNormal];
        self.skipButton.hidden = NO; // show skip
    }
}

- (void)onNextPress {
    if (self.currentIndex < self.slides.count - 1) {
        self.currentIndex++;
        [self.scrollView setContentOffset:CGPointMake(self.scrollView.frame.size.width * self.currentIndex, 0) animated:YES];
        self.pageControl.currentPage = self.currentIndex;

        // hide skip on last slide
        if (self.currentIndex == self.slides.count - 1) {
            self.skipButton.hidden = YES;
        }
    } else {
        [self finishTutorial];
    }
}

- (void)finishTutorial {
    // store flag in NSUserDefaults
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"HAS_SEEN_3RD_PARTY_TUTORIAL"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [self onBack];
}

- (UIView *)createSlideWithData:(NSDictionary *)slide {
    UIView *view = [[UIView alloc] init];

    // Title
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = slide[@"title"];
    titleLabel.font = [UIFont boldSystemFontOfSize:20];
    titleLabel.textAlignment = NSTextAlignmentLeft; // left align
    titleLabel.numberOfLines = 0;
    titleLabel.translatesAutoresizingMaskIntoConstraints = NO;

    // Subtitle
    UILabel *subtitleLabel = [[UILabel alloc] init];
    subtitleLabel.text = slide[@"subtitle"];
    subtitleLabel.font = [UIFont systemFontOfSize:16];
    subtitleLabel.textAlignment = NSTextAlignmentLeft; // left align
    subtitleLabel.numberOfLines = 0;
    subtitleLabel.translatesAutoresizingMaskIntoConstraints = NO;

    // Image
    NSBundle *bundle = [NSBundle bundleForClass:[self class]];
    UIImage *image = [UIImage imageNamed:slide[@"image"] inBundle:bundle compatibleWithTraitCollection:nil];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    imageView.translatesAutoresizingMaskIntoConstraints = NO;

    [view addSubview:titleLabel];
    [view addSubview:subtitleLabel];
    [view addSubview:imageView];

    UILayoutGuide *safe = view.safeAreaLayoutGuide;

    [NSLayoutConstraint activateConstraints:@[
        // Title at top
        [titleLabel.topAnchor constraintEqualToAnchor:safe.topAnchor constant:20],
        [titleLabel.leadingAnchor constraintEqualToAnchor:safe.leadingAnchor constant:16],
        [titleLabel.trailingAnchor constraintEqualToAnchor:safe.trailingAnchor constant:-16],

        // Subtitle under title
        [subtitleLabel.topAnchor constraintEqualToAnchor:titleLabel.bottomAnchor constant:12],
        [subtitleLabel.leadingAnchor constraintEqualToAnchor:safe.leadingAnchor constant:16],
        [subtitleLabel.trailingAnchor constraintEqualToAnchor:safe.trailingAnchor constant:-16],

        // Image under subtitle
        [imageView.topAnchor constraintEqualToAnchor:subtitleLabel.bottomAnchor constant:20],
        [imageView.leadingAnchor constraintEqualToAnchor:safe.leadingAnchor constant:16],
        [imageView.trailingAnchor constraintEqualToAnchor:safe.trailingAnchor constant:-16],
        [imageView.bottomAnchor constraintLessThanOrEqualToAnchor:safe.bottomAnchor constant:-20],
        [imageView.heightAnchor constraintLessThanOrEqualToAnchor:safe.heightAnchor multiplier:0.5] // max 50% of screen
    ]];

    return view;
}

- (void)setupPageControl {
    self.pageControl = [[UIPageControl alloc] init];
    self.pageControl.numberOfPages = self.slides.count;
    self.pageControl.currentPage = 0;
    self.pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
    self.pageControl.currentPageIndicatorTintColor = [UIColor colorWithRed:0.05 green:0.45 blue:0.57 alpha:1.0]; // #0E7392
    self.pageControl.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.pageControl];

    UILayoutGuide *safe = self.view.safeAreaLayoutGuide;
    [NSLayoutConstraint activateConstraints:@[
        [self.pageControl.bottomAnchor constraintEqualToAnchor:safe.bottomAnchor constant:-60],
        [self.pageControl.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor]
    ]];
}

- (void)setupNextButton {
    self.nextButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.nextButton setTitle:@"Next" forState:UIControlStateNormal];
    [self.nextButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    self.nextButton.backgroundColor = [UIColor colorWithRed:0.05 green:0.45 blue:0.57 alpha:1.0]; // #0E7392
    self.nextButton.layer.cornerRadius = 20;
    self.nextButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.nextButton addTarget:self action:@selector(onNextPress) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.nextButton];

    UILayoutGuide *safe = self.view.safeAreaLayoutGuide;
    [NSLayoutConstraint activateConstraints:@[
        [self.nextButton.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:-16],
        [self.nextButton.bottomAnchor constraintEqualToAnchor:safe.bottomAnchor constant:-16],
        [self.nextButton.widthAnchor constraintEqualToConstant:100],
        [self.nextButton.heightAnchor constraintEqualToConstant:44]
    ]];
}

#pragma mark - helpers
- (void)onBack {
  [self dismissViewControllerAnimated:YES completion:nil];
}

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

@end



