//  AppointmentViewController.mm

#import "AppointmentViewController.h"
#import <UIKit/UIKit.h>
#import "AppointmentAPIClient.h"
#import <WebKit/WebKit.h>

@interface AppointmentViewController () <WKNavigationDelegate, WKUIDelegate, UIScrollViewDelegate>

@property (nonatomic, strong) UIView *headerBar;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *backButton;
@property (nonatomic, strong) UIButton *helpButton;

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIView *contentView;

// Terms & Conditions
@property (nonatomic, strong) UIView *termsOverlay;
@property (nonatomic, strong) UITextView *termsTextView;
@property (nonatomic, strong) UIButton *agreeButton;
@property (nonatomic, assign) BOOL hasAgreedToTerms;
@property (nonatomic, strong) UILabel *termsTitleLabel;
@property (nonatomic, strong) UIView *termsContainer;
@property (nonatomic, strong) NSDictionary *appointmentData;
@property (nonatomic, strong) WKWebView *termsWebView;

// Calendar placeholder
@property (nonatomic, strong) UIView *calendarContainer;
@property (nonatomic, strong) UIStackView *legendStack;

// Footer buttons
@property (nonatomic, strong) UIView *footerView;
@property (nonatomic, strong) UIButton *backFooterButton;
@property (nonatomic, strong) UIButton *nextFooterButton;

// Tutorial overlay
@property (nonatomic, strong) UIView *tutorialOverlay;
@property (nonatomic, strong) UIImageView *tutorialImageView;
@property (nonatomic, strong) UIButton *skipButton;

@end

@implementation AppointmentViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  self.view.backgroundColor = UIColor.whiteColor;
  [self setupUI];
  [self setupTermsOverlay];
  [self fetchAppointment];
}

#pragma mark - Setup UI

- (void)setupUI {
  [self setupHeader];
  [self setupScrollView];
  [self setupCalendarSection];
  [self setupFooter];
  [self setupTutorialOverlay];
}

#pragma mark - Navigation Bar

- (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:48],
  ]];
  
  // Title
  self.titleLabel = [[UILabel alloc] init];
  self.titleLabel.text = @"Make Appointment";
  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:@"xmark"] forState:UIControlStateNormal];
  self.backButton.tintColor = UIColor.whiteColor;
  [self.backButton addTarget:self
                      action:@selector(handleBackTapped)
            forControlEvents:UIControlEventTouchUpInside];
  
  for (UIView *sub in @[self.titleLabel, self.backButton]) {
    sub.translatesAutoresizingMaskIntoConstraints = NO;
    [self.headerBar addSubview:sub];
  }
  
  [NSLayoutConstraint activateConstraints:@[
    [self.backButton.leadingAnchor constraintEqualToAnchor:self.headerBar.leadingAnchor constant:16],
    [self.backButton.centerYAnchor constraintEqualToAnchor:self.headerBar.centerYAnchor],
    
    [self.titleLabel.centerXAnchor constraintEqualToAnchor:self.headerBar.centerXAnchor],
    [self.titleLabel.centerYAnchor constraintEqualToAnchor:self.headerBar.centerYAnchor],
  ]];
}

#pragma mark = Overlay t&c
- (void)setupTermsOverlay {
    self.termsOverlay = [[UIView alloc] init];
    self.termsOverlay.backgroundColor = UIColor.whiteColor;
    self.termsOverlay.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.termsOverlay];
    
    [NSLayoutConstraint activateConstraints:@[
        [self.termsOverlay.topAnchor constraintEqualToAnchor:self.headerBar.bottomAnchor],
        [self.termsOverlay.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.termsOverlay.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.termsOverlay.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor],
    ]];
    
    self.termsTitleLabel = [[UILabel alloc] init];
    self.termsTitleLabel.text = @"Terms & Conditions";
    self.termsTitleLabel.font = [UIFont boldSystemFontOfSize:18];
    self.termsTitleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.termsOverlay addSubview:self.termsTitleLabel];
    
    self.termsContainer = [[UIView alloc] init];
    self.termsContainer.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1.0];
    self.termsContainer.layer.cornerRadius = 12.0;
    self.termsContainer.translatesAutoresizingMaskIntoConstraints = NO;
    [self.termsOverlay addSubview:self.termsContainer];
    
    // WKWebView
    self.termsWebView = [[WKWebView alloc] initWithFrame:CGRectZero];
    self.termsWebView.translatesAutoresizingMaskIntoConstraints = NO;
    self.termsWebView.scrollView.delegate = self;
    self.termsWebView.navigationDelegate = self;
    [self.termsContainer addSubview:self.termsWebView];
    
    // Agree button
    self.agreeButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.agreeButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.agreeButton setTitle:@"Agree and Continue" forState:UIControlStateNormal];
    self.agreeButton.enabled = NO;
    self.agreeButton.backgroundColor = UIColor.lightGrayColor;
    self.agreeButton.tintColor = UIColor.whiteColor;
    self.agreeButton.layer.cornerRadius = 10.0;
    [self.agreeButton addTarget:self action:@selector(handleAgreeTapped)
               forControlEvents:UIControlEventTouchUpInside];
    [self.termsOverlay addSubview:self.agreeButton];
    
    // Layout
    [NSLayoutConstraint activateConstraints:@[
        [self.termsTitleLabel.topAnchor constraintEqualToAnchor:self.termsOverlay.topAnchor constant:40],
        [self.termsTitleLabel.leadingAnchor constraintEqualToAnchor:self.termsOverlay.leadingAnchor constant:20],
        [self.termsTitleLabel.trailingAnchor constraintEqualToAnchor:self.termsOverlay.trailingAnchor constant:-20],
        
        [self.termsContainer.topAnchor constraintEqualToAnchor:self.termsTitleLabel.bottomAnchor constant:12],
        [self.termsContainer.leadingAnchor constraintEqualToAnchor:self.termsOverlay.leadingAnchor constant:20],
        [self.termsContainer.trailingAnchor constraintEqualToAnchor:self.termsOverlay.trailingAnchor constant:-20],
        [self.termsContainer.bottomAnchor constraintEqualToAnchor:self.agreeButton.topAnchor constant:-20],
        
        [self.termsWebView.topAnchor constraintEqualToAnchor:self.termsContainer.topAnchor],
        [self.termsWebView.leadingAnchor constraintEqualToAnchor:self.termsContainer.leadingAnchor],
        [self.termsWebView.trailingAnchor constraintEqualToAnchor:self.termsContainer.trailingAnchor],
        [self.termsWebView.bottomAnchor constraintEqualToAnchor:self.termsContainer.bottomAnchor],
        
        [self.agreeButton.leadingAnchor constraintEqualToAnchor:self.termsOverlay.leadingAnchor constant:40],
        [self.agreeButton.trailingAnchor constraintEqualToAnchor:self.termsOverlay.trailingAnchor constant:-40],
        [self.agreeButton.bottomAnchor constraintEqualToAnchor:self.termsOverlay.safeAreaLayoutGuide.bottomAnchor constant:-20],
        [self.agreeButton.heightAnchor constraintEqualToConstant:50],
    ]];
}


#pragma mark - Scroll View
- (void)setupScrollView {
  self.scrollView = [[UIScrollView alloc] init];
  self.scrollView.translatesAutoresizingMaskIntoConstraints = NO;
  [self.view addSubview:self.scrollView];
  
  [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:self.view.bottomAnchor constant:-100]
  ]];
  
  self.contentView = [[UIView alloc] init];
  self.contentView.translatesAutoresizingMaskIntoConstraints = NO;
  [self.scrollView addSubview:self.contentView];
  
  [NSLayoutConstraint activateConstraints:@[
    [self.contentView.widthAnchor constraintEqualToAnchor:self.scrollView.widthAnchor],
    [self.contentView.topAnchor constraintEqualToAnchor:self.scrollView.topAnchor],
    [self.contentView.bottomAnchor constraintEqualToAnchor:self.scrollView.bottomAnchor]
  ]];
}

#pragma mark - Calendar Section
- (void)setupCalendarSection {
  self.calendarContainer = [[UIView alloc] init];
  self.calendarContainer.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1.0];
  self.calendarContainer.layer.cornerRadius = 12.0;
  self.calendarContainer.translatesAutoresizingMaskIntoConstraints = NO;
  [self.contentView addSubview:self.calendarContainer];
  
  // Legend stack
  self.legendStack = [[UIStackView alloc] init];
  self.legendStack.axis = UILayoutConstraintAxisHorizontal;
  self.legendStack.spacing = 16.0;
  self.legendStack.alignment = UIStackViewAlignmentCenter;
  self.legendStack.distribution = UIStackViewDistributionEqualSpacing;
  self.legendStack.translatesAutoresizingMaskIntoConstraints = NO;
  [self.contentView addSubview:self.legendStack];
  
  NSArray *legendData = @[
    @{@"title": @"Available", @"color": UIColor.systemGreenColor},
    @{@"title": @"Limited", @"color": UIColor.systemOrangeColor},
    @{@"title": @"Unavailable", @"color": UIColor.systemRedColor}
  ];
  
  for (NSDictionary *item in legendData) {
    UIView *dot = [[UIView alloc] init];
    dot.backgroundColor = item[@"color"];
    dot.layer.cornerRadius = 6;
    dot.translatesAutoresizingMaskIntoConstraints = NO;
    [dot.heightAnchor constraintEqualToConstant:12].active = YES;
    [dot.widthAnchor constraintEqualToConstant:12].active = YES;
    
    UILabel *label = [[UILabel alloc] init];
    label.text = item[@"title"];
    label.font = [UIFont systemFontOfSize:13];
    
    UIStackView *pair = [[UIStackView alloc] initWithArrangedSubviews:@[dot, label]];
    pair.axis = UILayoutConstraintAxisHorizontal;
    pair.spacing = 4.0;
    
    [self.legendStack addArrangedSubview:pair];
  }
  
  [NSLayoutConstraint activateConstraints:@[
    [self.calendarContainer.topAnchor constraintEqualToAnchor:self.contentView.topAnchor constant:20],
    [self.calendarContainer.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],
    [self.calendarContainer.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-16],
    [self.calendarContainer.heightAnchor constraintEqualToConstant:320],
    
    [self.legendStack.topAnchor constraintEqualToAnchor:self.calendarContainer.bottomAnchor constant:16],
    [self.legendStack.centerXAnchor constraintEqualToAnchor:self.contentView.centerXAnchor]
  ]];
}

#pragma mark - Footer Buttons
- (void)setupFooter {
  self.footerView = [[UIView alloc] init];
  self.footerView.backgroundColor = UIColor.whiteColor;
  self.footerView.layer.shadowOpacity = 0.1;
  self.footerView.layer.shadowOffset = CGSizeMake(0, -1);
  self.footerView.translatesAutoresizingMaskIntoConstraints = NO;
  [self.view addSubview:self.footerView];
  
  [NSLayoutConstraint activateConstraints:@[
    [self.footerView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
    [self.footerView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
    [self.footerView.bottomAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.bottomAnchor],
    [self.footerView.heightAnchor constraintEqualToConstant:80]
  ]];
  
  self.backFooterButton = [UIButton buttonWithType:UIButtonTypeSystem];
  [self.backFooterButton setTitle:@"Back" forState:UIControlStateNormal];
  self.backFooterButton.layer.borderColor = [UIColor systemTealColor].CGColor;
  self.backFooterButton.layer.borderWidth = 1.0;
  self.backFooterButton.layer.cornerRadius = 20.0;
  [self.backFooterButton setTitleColor:[UIColor systemTealColor] forState:UIControlStateNormal];
  
  self.nextFooterButton = [UIButton buttonWithType:UIButtonTypeSystem];
  [self.nextFooterButton setTitle:@"Next" forState:UIControlStateNormal];
  self.nextFooterButton.backgroundColor = [UIColor systemTealColor];
  self.nextFooterButton.tintColor = UIColor.whiteColor;
  self.nextFooterButton.layer.cornerRadius = 20.0;
  
  UIStackView *stack = [[UIStackView alloc] initWithArrangedSubviews:@[self.backFooterButton, self.nextFooterButton]];
  stack.axis = UILayoutConstraintAxisHorizontal;
  stack.spacing = 12.0;
  stack.distribution = UIStackViewDistributionFillEqually;
  stack.translatesAutoresizingMaskIntoConstraints = NO;
  
  [self.footerView addSubview:stack];
  [NSLayoutConstraint activateConstraints:@[
    [stack.topAnchor constraintEqualToAnchor:self.footerView.topAnchor constant:12],
    [stack.leadingAnchor constraintEqualToAnchor:self.footerView.leadingAnchor constant:16],
    [stack.trailingAnchor constraintEqualToAnchor:self.footerView.trailingAnchor constant:-16],
    [stack.bottomAnchor constraintEqualToAnchor:self.footerView.bottomAnchor constant:-12]
  ]];
}

#pragma mark - Tutorial Overlay
- (void)setupTutorialOverlay {
  self.tutorialOverlay = [[UIView alloc] init];
  self.tutorialOverlay.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
  self.tutorialOverlay.hidden = YES;
  self.tutorialOverlay.translatesAutoresizingMaskIntoConstraints = NO;
  [self.view addSubview:self.tutorialOverlay];
  
  [NSLayoutConstraint activateConstraints:@[
    [self.tutorialOverlay.topAnchor constraintEqualToAnchor:self.view.topAnchor],
    [self.tutorialOverlay.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
    [self.tutorialOverlay.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
    [self.tutorialOverlay.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor]
  ]];
  
  self.tutorialImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"tutorial_step1"]];
  self.tutorialImageView.contentMode = UIViewContentModeScaleAspectFit;
  self.tutorialImageView.translatesAutoresizingMaskIntoConstraints = NO;
  [self.tutorialOverlay addSubview:self.tutorialImageView];
  
  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 = 1.0;
  self.skipButton.layer.cornerRadius = 6.0;
  self.skipButton.translatesAutoresizingMaskIntoConstraints = NO;
  [self.tutorialOverlay addSubview:self.skipButton];
  
  [NSLayoutConstraint activateConstraints:@[
    [self.tutorialImageView.centerXAnchor constraintEqualToAnchor:self.tutorialOverlay.centerXAnchor],
    [self.tutorialImageView.centerYAnchor constraintEqualToAnchor:self.tutorialOverlay.centerYAnchor],
    [self.tutorialImageView.widthAnchor constraintEqualToAnchor:self.tutorialOverlay.widthAnchor multiplier:0.9],
    [self.tutorialImageView.heightAnchor constraintEqualToAnchor:self.tutorialOverlay.heightAnchor multiplier:0.7],
    
    [self.skipButton.topAnchor constraintEqualToAnchor:self.tutorialOverlay.safeAreaLayoutGuide.topAnchor constant:16],
    [self.skipButton.trailingAnchor constraintEqualToAnchor:self.tutorialOverlay.trailingAnchor constant:-16],
    [self.skipButton.widthAnchor constraintEqualToConstant:70],
    [self.skipButton.heightAnchor constraintEqualToConstant:32]
  ]];
}

#pragma mark - api
- (void)fetchAppointment {
    [AppointmentAPIClient fetchAppointment:^(NSDictionary *data, NSError *error) {
        if (error) return;
      
      NSDictionary *appointData = data;
      NSString *text = [NSString stringWithFormat:@"%@", appointData];
      NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
      NSString *filePath = [docsPath stringByAppendingPathComponent:@"appointmentData.txt"];
      NSString *plainText = [NSString stringWithFormat:@"%@", appointData];
      [plainText writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
      NSLog(@"📁 appointmentData saved as plain text to: %@", filePath);
      
      self.appointmentData = appointData[@"Data"];
      
      dispatch_async(dispatch_get_main_queue(), ^{
          NSDictionary *jointInspection = self.appointmentData[@"joint_inspection"];
          NSDictionary *handover = self.appointmentData[@"handover"];
          NSString *termsHTML = jointInspection[@"terms"] ?: handover[@"terms"];
        
          if (termsHTML.length == 0) {
              NSLog(@"⚠️ termsHTML is EMPTY");
          } else {
              NSLog(@"✅ Loading terms HTML (%lu chars)", termsHTML.length);
          }
        
          NSString *styledHTML = [NSString stringWithFormat:
              @"<html>"
                "<head>"
                  "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0\">"
                  "<style>"
                    "body {"
                      "font-size: 14px;"
                      "font-family: -apple-system;"
                      "line-height: 1.5;"
                      "padding: 12px;"
                      "background-color: #F9F9F9;"
                    "}"
                    "p { margin-bottom: 12px; }"
                  "</style>"
                "</head>"
                "<body>%@</body>"
              "</html>", termsHTML];

          [self.termsWebView loadHTMLString:styledHTML baseURL:nil];
      });
  }];
}

#pragma mark - WKWebView Delegate
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    // Ensure layout is up-to-date
    [webView layoutIfNeeded];
    
    // Get content height via JS
    [webView evaluateJavaScript:@"document.body.scrollHeight;" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        if (error) return;
        
        CGFloat contentHeight = [result doubleValue];
        CGFloat frameHeight = webView.scrollView.bounds.size.height;

        // Short content: enable button immediately
        if (contentHeight <= frameHeight) {
            [self enableAgreeButton];
        } else {
            // Long content: track scrolling
            webView.scrollView.delegate = self;
        }
    }];
}

#pragma mark - Scroll View Delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView != self.termsWebView.scrollView) return;
    if (self.agreeButton.enabled) return;

    CGFloat offsetY = scrollView.contentOffset.y;
    CGFloat contentHeight = scrollView.contentSize.height;
    CGFloat frameHeight = scrollView.bounds.size.height;

    if (offsetY + frameHeight >= contentHeight - 10) {
        [self enableAgreeButton];
    }
}

#pragma mark - Helper
- (void)enableAgreeButton {
    self.agreeButton.enabled = YES;
    self.agreeButton.backgroundColor = [UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0];
}

- (void)handleAgreeTapped {
    self.calendarContainer.userInteractionEnabled = YES;
    self.footerView.userInteractionEnabled = YES;
    [UIView animateWithDuration:0.25 animations:^{
        self.termsOverlay.alpha = 0.0;
    } completion:^(BOOL finished) {
        self.termsOverlay.hidden = YES;
        self.termsOverlay.alpha = 1.0;
    }];
}

- (void)handleBackTapped {
    if (self.navigationController) {
        // If inside a navigation controller → go back
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        // Otherwise → dismiss modally
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

@end
