//  AppointmentConfirmationViewController.mm
#import "AppointmentConfirmationViewController.h"
#import <WebKit/WebKit.h>
#import <UIKit/UIKit.h>
#import "AppointmentAPIClient.h"

@interface AppointmentConfirmationViewController () <WKNavigationDelegate>

// Top Bar
@property (nonatomic, strong) UIView *headerBar;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *backButton;

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

// Summary Section
@property (nonatomic, strong) UILabel *unitLabel;
@property (nonatomic, strong) UILabel *unitLabelName;
@property (nonatomic, strong) UIView *stepBanner;
@property (nonatomic, strong) UIView *summaryCard;
@property (nonatomic, strong) UILabel *appointmentTitle;
@property (nonatomic, strong) UILabel *appointmentTypeLabel;
@property (nonatomic, strong) UILabel *dateLabel;
@property (nonatomic, strong) UILabel *timeLabel;
@property (nonatomic, strong) NSLayoutConstraint *htmlHeightConstraint;

// Representative Section
@property (nonatomic, strong) UIView *representativeSection;
@property (nonatomic, strong) UILabel *repTitleLabel;
@property (nonatomic, strong) UIButton *repToggleButton;
@property (nonatomic, strong) UIView *repOverlayContainer;
@property (nonatomic, strong) UIStackView *repInputsContainer;
@property (nonatomic, strong) NSString *repId;
@property (nonatomic, assign) BOOL blnTickRepresentative;
@property (nonatomic, strong) UIImageView *icPhotoView;
@property (nonatomic, strong) UIImageView *letterPhotoView;


// Optional input fields
@property (nonatomic, strong) UITextField *repNameField;
@property (nonatomic, strong) UITextField *repICField;
@property (nonatomic, strong) UITextField *repEmailField;
@property (nonatomic, strong) UITextField *repContactField;
@property (nonatomic, strong) UILabel *repNameTitle;
@property (nonatomic, strong) UILabel *repICTitle;
@property (nonatomic, strong) UILabel *repEmailTitle;
@property (nonatomic, strong) UILabel *repContactTitle;
@property (nonatomic, strong) NSString *icPhoto;
@property (nonatomic, strong) NSString *letterPhoto;

// Overlay for full-screen selection
@property (nonatomic, strong) UIView *repOverlayView;
@property (nonatomic, strong) NSLayoutConstraint *repInputsHeightConstraint;

// T&C
@property (nonatomic, strong) UILabel *tcTitleLabel;
@property (nonatomic, strong) WKWebView *htmlView;

// Bottom Buttons
@property (nonatomic, strong) UIView *bottomBar;
@property (nonatomic, strong) UIButton *editButton;
@property (nonatomic, strong) UIButton *confirmButton;

// Modal Placeholder
@property (nonatomic, strong) UIView *dimOverlay;


@end


@implementation AppointmentConfirmationViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  self.view.backgroundColor = UIColor.whiteColor;
  
  NSLog(@"📦 Data received by appointmentConfirmation:"
        "\n slotId: %@"
        "\n startDate: %@"
        "\n startTime: %@"
        "\n projectId: %@"
        "\n projectName: %@"
        "\n appointmentType: %@"
        "\n reprensetativeList: %@"
        "\n terms & condition: %@",
        self.slotId,
        self.startDate,
        self.startTime,
        self.projectId,
        self.projectName,
        self.appointmentType,
        self.representativeList,
        self.termsAndCondition);
  
  self.repInputsContainer.hidden = YES;
  
  self.icPhotoView = [[UIImageView alloc] init];
  self.icPhotoView.contentMode = UIViewContentModeScaleAspectFill;
  self.icPhotoView.clipsToBounds = YES;
  self.icPhotoView.layer.cornerRadius = 8;
  self.icPhotoView.hidden = YES; // hidden until a rep is selected
  
  self.letterPhotoView = [[UIImageView alloc] init];
  self.letterPhotoView.contentMode = UIViewContentModeScaleAspectFill;
  self.letterPhotoView.clipsToBounds = YES;
  self.letterPhotoView.layer.cornerRadius = 8;
  self.letterPhotoView.hidden = YES;
  
  [self setupHeader];
  [self setupBottomBar];
  [self setupScrollView];
  [self setupContentUI];
}

#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(cancelPressed:)
            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 - ScrollView
- (void)setupScrollView {
  self.scrollView = [[UIScrollView alloc] init];
  self.scrollView.translatesAutoresizingMaskIntoConstraints = NO;
  [self.view addSubview:self.scrollView];
  
  self.contentView = [[UIView alloc] init];
  self.contentView.translatesAutoresizingMaskIntoConstraints = NO;
  [self.scrollView addSubview:self.contentView];
  
  [NSLayoutConstraint activateConstraints:@[
    // scrollView sits between header and bottomBar
    [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.bottomBar.topAnchor], // anchor to bottomBar
    
    // contentView fills scrollView
    [self.contentView.topAnchor constraintEqualToAnchor:self.scrollView.topAnchor],
    [self.contentView.leadingAnchor constraintEqualToAnchor:self.scrollView.leadingAnchor],
    [self.contentView.trailingAnchor constraintEqualToAnchor:self.scrollView.trailingAnchor],
    [self.contentView.bottomAnchor constraintEqualToAnchor:self.scrollView.bottomAnchor],
    [self.contentView.widthAnchor constraintEqualToAnchor:self.scrollView.widthAnchor],
  ]];
}


#pragma mark - Main UI
- (void)setupContentUI {
    // --- Unit Labels ---
    self.unitLabel = [[UILabel alloc] init];
    self.unitLabel.text = @"For Unit No.:";
    self.unitLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightThin];
    self.unitLabel.textColor = [UIColor grayColor];
    self.unitLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.contentView addSubview:self.unitLabel];
    
    self.unitLabelName = [[UILabel alloc] init];
    self.unitLabelName.text = [NSString stringWithFormat:@"%@, %@", self.projectName, self.projectId];
    self.unitLabelName.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
    self.unitLabelName.textColor = [UIColor blackColor];
    self.unitLabelName.translatesAutoresizingMaskIntoConstraints = NO;
    [self.contentView addSubview:self.unitLabelName];
    
    // --- Step Banner ---
    self.stepBanner = [[UIView alloc] init];
    self.stepBanner.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1];
    self.stepBanner.layer.cornerRadius = 12;
    self.stepBanner.translatesAutoresizingMaskIntoConstraints = NO;
    [self.contentView addSubview:self.stepBanner];
    
    UILabel *stepLabel = [[UILabel alloc] init];
    stepLabel.text = @"Step 3/3: Confirm your Appointment";
    stepLabel.font = [UIFont systemFontOfSize:15];
    stepLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.stepBanner addSubview:stepLabel];
    
    // --- Summary Card ---
    self.summaryCard = [[UIView alloc] init];
    self.summaryCard.backgroundColor = [UIColor colorWithRed:0 green:0.23 blue:0.30 alpha:1];
    self.summaryCard.layer.cornerRadius = 12;
    self.summaryCard.translatesAutoresizingMaskIntoConstraints = NO;
    [self.contentView addSubview:self.summaryCard];
    
    self.appointmentTitle = [[UILabel alloc] init];
    self.appointmentTitle.text = @"Your Appointment Summary";
    self.appointmentTitle.textColor = UIColor.whiteColor;
    self.appointmentTitle.font = [UIFont boldSystemFontOfSize:20];
    self.appointmentTitle.translatesAutoresizingMaskIntoConstraints = NO;
    [self.summaryCard addSubview:self.appointmentTitle];
    
    self.appointmentTypeLabel = [[UILabel alloc] init];
    self.appointmentTypeLabel.text = [self formattedAppointmentType:self.appointmentType];
    self.appointmentTypeLabel.textColor = UIColor.whiteColor;
    self.appointmentTypeLabel.font = [UIFont boldSystemFontOfSize:28];
    self.appointmentTypeLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.summaryCard addSubview:self.appointmentTypeLabel];
    
    self.dateLabel = [[UILabel alloc] init];
    self.dateLabel.text = self.startDate;
    self.dateLabel.textColor = UIColor.whiteColor;
    self.dateLabel.font = [UIFont systemFontOfSize:18];
    self.dateLabel.translatesAutoresizingMaskIntoConstraints = NO;
    
    self.timeLabel = [[UILabel alloc] init];
    self.timeLabel.text = self.startTime;
    self.timeLabel.textColor = UIColor.whiteColor;
    self.timeLabel.font = [UIFont systemFontOfSize:18];
    self.timeLabel.translatesAutoresizingMaskIntoConstraints = NO;
    
    UIStackView *dateTimeStack = [[UIStackView alloc] initWithArrangedSubviews:@[self.dateLabel, self.timeLabel]];
    dateTimeStack.axis = UILayoutConstraintAxisHorizontal;
    dateTimeStack.spacing = 20;
    dateTimeStack.alignment = UIStackViewAlignmentLeading;
    dateTimeStack.translatesAutoresizingMaskIntoConstraints = NO;
    [self.summaryCard addSubview:dateTimeStack];
    
    // --- Representative Section ---
    [self setupRepresentativeSection]; // Uses stackview-based refactor from previous step
    
    // --- Terms & Conditions ---
    self.tcTitleLabel = [[UILabel alloc] init];
    self.tcTitleLabel.text = @"Terms & Conditions";
    self.tcTitleLabel.font = [UIFont boldSystemFontOfSize:16];
    self.tcTitleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.contentView addSubview:self.tcTitleLabel];
    
    self.htmlView = [[WKWebView alloc] init];
    self.htmlView.navigationDelegate = self;
    self.htmlView.scrollView.scrollEnabled = NO;
    self.htmlView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.contentView addSubview:self.htmlView];
    
    self.htmlHeightConstraint = [self.htmlView.heightAnchor constraintEqualToConstant:50];
    self.htmlHeightConstraint.active = YES;
    [self.htmlView loadHTMLString:self.termsAndCondition baseURL:nil];
    
    // --- Layout Constraints ---
    [NSLayoutConstraint activateConstraints:@[
        // Unit Labels
        [self.unitLabel.topAnchor constraintEqualToAnchor:self.contentView.topAnchor constant:16],
        [self.unitLabel.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],
        [self.unitLabel.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-16],
        
        [self.unitLabelName.topAnchor constraintEqualToAnchor:self.unitLabel.bottomAnchor constant:8],
        [self.unitLabelName.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],
        [self.unitLabelName.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-16],
        
        // Step Banner
        [self.stepBanner.topAnchor constraintEqualToAnchor:self.unitLabelName.bottomAnchor constant:20],
        [self.stepBanner.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],
        [self.stepBanner.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-16],
        [self.stepBanner.heightAnchor constraintEqualToConstant:50],
        
        [stepLabel.centerYAnchor constraintEqualToAnchor:self.stepBanner.centerYAnchor],
        [stepLabel.leadingAnchor constraintEqualToAnchor:self.stepBanner.leadingAnchor constant:12],
        
        // Summary Card
        [self.summaryCard.topAnchor constraintEqualToAnchor:self.stepBanner.bottomAnchor constant:20],
        [self.summaryCard.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:0],
        [self.summaryCard.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:0],
        
        [self.appointmentTitle.topAnchor constraintEqualToAnchor:self.summaryCard.topAnchor constant:20],
        [self.appointmentTitle.leadingAnchor constraintEqualToAnchor:self.summaryCard.leadingAnchor constant:20],
        
        [self.appointmentTypeLabel.topAnchor constraintEqualToAnchor:self.appointmentTitle.bottomAnchor constant:8],
        [self.appointmentTypeLabel.leadingAnchor constraintEqualToAnchor:self.summaryCard.leadingAnchor constant:20],
        
        [dateTimeStack.topAnchor constraintEqualToAnchor:self.appointmentTypeLabel.bottomAnchor constant:16],
        [dateTimeStack.leadingAnchor constraintEqualToAnchor:self.summaryCard.leadingAnchor constant:20],
        [dateTimeStack.bottomAnchor constraintEqualToAnchor:self.summaryCard.bottomAnchor constant:-20],
        
        // Terms & Conditions below representative stack
        [self.tcTitleLabel.topAnchor constraintEqualToAnchor:self.repInputsContainer.bottomAnchor constant:30],
        [self.tcTitleLabel.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],
        [self.tcTitleLabel.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-16],
        
        [self.htmlView.topAnchor constraintEqualToAnchor:self.tcTitleLabel.bottomAnchor constant:12],
        [self.htmlView.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:20],
        [self.htmlView.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-20],
        [self.htmlView.bottomAnchor constraintEqualToAnchor:self.contentView.bottomAnchor constant:-40],
    ]];
}


- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
  [webView evaluateJavaScript:@"document.body.scrollHeight;" completionHandler:^(id result, NSError *error) {
    if (!error && result) {
      CGFloat contentHeight = [result floatValue];
      
      // Update the dynamic constraint
      self.htmlHeightConstraint.constant = contentHeight;
      
      [UIView animateWithDuration:0.25 animations:^{
        [self.view layoutIfNeeded];
      }];
    }
  }];
}

#pragma mark - representative section
- (void)setupRepresentativeSection {
    // --- Representative Section Container ---
    self.representativeSection = [[UIView alloc] init];
    self.representativeSection.translatesAutoresizingMaskIntoConstraints = NO;
    [self.contentView addSubview:self.representativeSection];

    self.repTitleLabel = [[UILabel alloc] init];
    self.repTitleLabel.text = @"Representative Attending?";
    self.repTitleLabel.font = [UIFont boldSystemFontOfSize:17];
    self.repTitleLabel.translatesAutoresizingMaskIntoConstraints = NO;

    self.repToggleButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.repToggleButton.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];
    self.repToggleButton.layer.cornerRadius = 14;
    self.repToggleButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.repToggleButton addTarget:self
                             action:@selector(toggleRepresentative:)
                   forControlEvents:UIControlEventTouchUpInside];

    [self.representativeSection addSubview:self.repTitleLabel];
    [self.representativeSection addSubview:self.repToggleButton];

    // --- Representative Inputs Stack ---
    self.repNameField = [[UITextField alloc] init];
    self.repNameField.backgroundColor = [UIColor lightGrayColor];
    self.repICField = [[UITextField alloc] init];
    self.repICField.backgroundColor = [UIColor lightGrayColor];
    self.repEmailField = [[UITextField alloc] init];
    self.repEmailField.backgroundColor = [UIColor lightGrayColor];
    self.repContactField = [[UITextField alloc] init];
    self.repContactField.backgroundColor = [UIColor lightGrayColor];


    UILabel *repNameTitle = [[UILabel alloc] init];
    repNameTitle.text = @"Name"; repNameTitle.font = [UIFont systemFontOfSize:14 weight:UIFontWeightMedium];

    UILabel *repICTitle = [[UILabel alloc] init];
    repICTitle.text = @"NRIC / Passport"; repICTitle.font = [UIFont systemFontOfSize:14 weight:UIFontWeightMedium];

    UILabel *repEmailTitle = [[UILabel alloc] init];
    repEmailTitle.text = @"Email"; repEmailTitle.font = [UIFont systemFontOfSize:14 weight:UIFontWeightMedium];

    UILabel *repContactTitle = [[UILabel alloc] init];
    repContactTitle.text = @"Contact No."; repContactTitle.font = [UIFont systemFontOfSize:14 weight:UIFontWeightMedium];

    // Image row
    self.icPhotoView = [[UIImageView alloc] init];
    self.letterPhotoView = [[UIImageView alloc] init];
    self.icPhotoView.contentMode = UIViewContentModeScaleAspectFill; self.icPhotoView.clipsToBounds = YES; self.icPhotoView.layer.cornerRadius = 8;
    self.letterPhotoView.contentMode = UIViewContentModeScaleAspectFill; self.letterPhotoView.clipsToBounds = YES; self.letterPhotoView.layer.cornerRadius = 8;

    UIStackView *imageRow = [[UIStackView alloc] initWithArrangedSubviews:@[self.icPhotoView, self.letterPhotoView]];
    imageRow.axis = UILayoutConstraintAxisHorizontal;
    imageRow.distribution = UIStackViewDistributionFillEqually;
    imageRow.spacing = 12;
    imageRow.translatesAutoresizingMaskIntoConstraints = NO;

    self.repInputsContainer = [[UIStackView alloc] initWithArrangedSubviews:@[
        imageRow,
        repNameTitle, self.repNameField,
        repICTitle, self.repICField,
        repEmailTitle, self.repEmailField,
        repContactTitle, self.repContactField
    ]];
    self.repInputsContainer.axis = UILayoutConstraintAxisVertical;
    self.repInputsContainer.spacing = 8;
    self.repInputsContainer.translatesAutoresizingMaskIntoConstraints = NO;
    self.repInputsContainer.hidden = YES;   // Initially hidden
    [self.contentView addSubview:self.repInputsContainer];

    // --- Constraints ---
    [NSLayoutConstraint activateConstraints:@[
        // Representative Section
        [self.representativeSection.topAnchor constraintEqualToAnchor:self.summaryCard.bottomAnchor constant:30],
        [self.representativeSection.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:20],
        [self.representativeSection.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-20],
        [self.representativeSection.heightAnchor constraintEqualToConstant:50],

        [self.repTitleLabel.centerYAnchor constraintEqualToAnchor:self.representativeSection.centerYAnchor],
        [self.repTitleLabel.leadingAnchor constraintEqualToAnchor:self.representativeSection.leadingAnchor],

        [self.repToggleButton.centerYAnchor constraintEqualToAnchor:self.representativeSection.centerYAnchor],
        [self.repToggleButton.trailingAnchor constraintEqualToAnchor:self.representativeSection.trailingAnchor],
        [self.repToggleButton.widthAnchor constraintEqualToConstant:28],
        [self.repToggleButton.heightAnchor constraintEqualToConstant:28],

        // Rep inputs stack
        [self.repInputsContainer.topAnchor constraintEqualToAnchor:self.representativeSection.bottomAnchor constant:8],
        [self.repInputsContainer.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],
        [self.repInputsContainer.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-16],
    ]];

    // Image row height
    [self.icPhotoView.heightAnchor constraintEqualToConstant:120].active = YES;
    [self.letterPhotoView.heightAnchor constraintEqualToConstant:120].active = YES;
}

#pragma mark - Bottom Bar
- (void)setupBottomBar {
  self.bottomBar = [[UIView alloc] init];
  self.bottomBar.backgroundColor = UIColor.whiteColor;
  self.bottomBar.translatesAutoresizingMaskIntoConstraints = NO;
  [self.view addSubview:self.bottomBar];
  
  self.editButton = [UIButton buttonWithType:UIButtonTypeSystem];
  [self.editButton setTitle:@"Edit" forState:UIControlStateNormal];
  self.editButton.layer.borderColor = [UIColor colorWithRed:0 green:0.45 blue:0.55 alpha:1].CGColor;
  self.editButton.layer.borderWidth = 1;
  self.editButton.layer.cornerRadius = 20;
  self.editButton.translatesAutoresizingMaskIntoConstraints = NO;
  
  self.confirmButton = [UIButton buttonWithType:UIButtonTypeSystem];
  [self.confirmButton setTitle:@"Confirm" forState:UIControlStateNormal];
  self.confirmButton.backgroundColor = [UIColor colorWithRed:0 green:0.45 blue:0.55 alpha:1];
  [self.confirmButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
  self.confirmButton.layer.cornerRadius = 20;
  self.confirmButton.translatesAutoresizingMaskIntoConstraints = NO;
  [self.confirmButton addTarget:self
                           action:@selector(confirmPressed)
                 forControlEvents:UIControlEventTouchUpInside];
  
  [self.bottomBar addSubview:self.editButton];
  [self.bottomBar addSubview:self.confirmButton];
  
  [NSLayoutConstraint activateConstraints:@[
    [self.bottomBar.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
    [self.bottomBar.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
    [self.bottomBar.bottomAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.bottomAnchor],
    [self.bottomBar.heightAnchor constraintEqualToConstant:70],
    
    [self.editButton.leadingAnchor constraintEqualToAnchor:self.bottomBar.leadingAnchor constant:20],
    [self.editButton.centerYAnchor constraintEqualToAnchor:self.bottomBar.centerYAnchor],
    [self.editButton.widthAnchor constraintEqualToAnchor:self.bottomBar.widthAnchor multiplier:0.45],
    [self.editButton.heightAnchor constraintEqualToConstant:48],
    
    [self.confirmButton.trailingAnchor constraintEqualToAnchor:self.bottomBar.trailingAnchor constant:-20],
    [self.confirmButton.centerYAnchor constraintEqualToAnchor:self.bottomBar.centerYAnchor],
    [self.confirmButton.widthAnchor constraintEqualToAnchor:self.bottomBar.widthAnchor multiplier:0.45],
    [self.confirmButton.heightAnchor constraintEqualToConstant:48],
  ]];
}

#pragma mark - representative
- (void)toggleRepresentative:(UIButton *)sender {
    if (self.repInputsContainer.isHidden) {
        [self showRepresentativePicker];
      self.blnTickRepresentative = YES;
    } else {
        // Already showing → hide
        [self hideRepresentativeInputs];
        self.blnTickRepresentative = NO;
    }
}

- (void)showRepresentativeInputs {
    self.repInputsContainer.hidden = NO;
    self.icPhotoView.hidden = NO;
    self.letterPhotoView.hidden = NO;

    [UIView animateWithDuration:0.3 animations:^{
        [self.contentView layoutIfNeeded];
    }];
}

- (void)hideRepresentativeInputs {
    [UIView animateWithDuration:0.3 animations:^{
        self.repInputsContainer.hidden = YES;
        self.icPhotoView.hidden = YES;
        self.letterPhotoView.hidden = YES;
        [self.contentView layoutIfNeeded];
    }];

    // Optional: clear fields
    self.repNameField.text = @"";
    self.repICField.text = @"";
    self.repEmailField.text = @"";
    self.repContactField.text = @"";
}


#pragma mark - helpers
- (void)cancelPressed:(id)sender {
  UIAlertController *a = [UIAlertController alertControllerWithTitle:@"Cancel"
                                                             message:@"Are you sure you want to cancel?"
                                                      preferredStyle:UIAlertControllerStyleAlert];
  [a addAction:[UIAlertAction actionWithTitle:@"No" style:UIAlertActionStyleCancel handler:nil]];
  [a addAction:[UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
    // pop to dashboard or dismiss - replicate RN behavior
  if (self.navigationController) {
      [self.navigationController popToRootViewControllerAnimated:YES];
  } else {
      [self dismissViewControllerAnimated:YES completion:nil];
  }
  }]];
  [self presentViewController:a animated:YES completion:nil];
}

- (NSString *)formattedAppointmentType:(NSString *)type {
  if (![type isKindOfClass:[NSString class]] || type.length == 0) {
    return @"";
  }
  
  // 1. Replace underscores with spaces
  NSString *spaced = [type stringByReplacingOccurrencesOfString:@"_" withString:@" "];
  
  // 2. Capitalize each word
  return [spaced capitalizedString];
}

- (void)showRepresentativePicker {
  if (!self.representativeList || self.representativeList.count == 0) {
    NSLog(@"⚠️ No representatives to display");
    return;
  }
  
  UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Select Representative"
                                                                 message:nil
                                                          preferredStyle:UIAlertControllerStyleActionSheet];
  
  for (NSDictionary *rep in self.representativeList) {
    NSString *repName = rep[@"name"] ?: @"Unnamed";
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:repName
                                                     style:UIAlertActionStyleDefault
                                                   handler:^(UIAlertAction * _Nonnull action) {
      NSLog(@"✅ Selected representative: %@", repName);
      
      // Fill the form fields
      self.repNameField.text = rep[@"name"] ?: @"";
      self.repICField.text = rep[@"ic_passport"] ?: @"";
      self.repEmailField.text = rep[@"email"] ?: @"";
      self.repContactField.text = rep[@"phone"] ?: @"";
      self.repId = rep[@"id"] ?: @"";
      self.icPhoto = rep[@"ic_photo"];
      self.letterPhoto = rep[@"letter"];
      [self loadImage:rep[@"ic_photo"] intoImageView:self.icPhotoView];
      [self loadImage:rep[@"letter"] intoImageView:self.letterPhotoView];
      
      // Optionally show inputs if they are hidden
      [self showRepresentativeInputs];
    }];
    
    [alert addAction:action];
  }
  
  UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"Cancel"
                                                   style:UIAlertActionStyleCancel
                                                 handler:nil];
  [alert addAction:cancel];
  
  [self presentViewController:alert animated:YES completion:nil];
}

- (void)selectRepresentativeOther {
  NSLog(@"✅ Selected 'Other' representative");
  
  self.repNameField.text = @"";
  self.repICField.text = @"";
  self.repEmailField.text = @"";
  self.repContactField.text = @"";
  self.repId = @"";
  
  // Hide overlay
  [UIView animateWithDuration:0.25 animations:^{
    self.repOverlayContainer.alpha = 0;
  } completion:^(BOOL finished) {
    [self.repOverlayContainer.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
  }];
  
  // Make sure toggle is ticked
  self.blnTickRepresentative = YES;
  
  // Show the representative input fields
  [self showRepresentativeInputs];
}

- (void)loadImage:(NSString *)urlString intoImageView:(UIImageView *)imageView {
    if (!urlString) return;

    NSURL *url = [NSURL URLWithString:urlString];
    if (!url) return;

    NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url
                                                             completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data && !error) {
            UIImage *image = [UIImage imageWithData:data];
            if (image) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    imageView.image = image;
                });
            }
        }
    }];
    [task resume];
}

-(void)confirmPressed {
    NSLog(@"⚡ Confirm pressed, blnTickRepresentative = %@", self.blnTickRepresentative ? @"YES" : @"NO");

    if (self.blnTickRepresentative) {
        NSDictionary *repData = @{
            @"data[os]": @"AND",
            @"data[project_id]": @"8",
            @"data[appointment_type]": self.appointmentType,
            @"data[drawing_plan_id]": @"135",
            @"data[appointment_attendee_type]": @"representative",
            @"data[slot_id]": self.slotId,
            @"data[representative_id]": self.repId,
            @"data[imei]": @"AND:2a2f13ff17b1cbb5",
        };

        [AppointmentAPIClient submitRepresentativeAppointment:repData completion:^(BOOL success, NSDictionary * _Nullable response, NSError * _Nullable error) {

            dispatch_async(dispatch_get_main_queue(), ^{
                if (success) {
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Success"
                                                                                   message:@"Your appointment was submitted successfully."
                                                                            preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                               handler:^(UIAlertAction * _Nonnull action) {
                        // Navigate away or dismiss
                        [self.navigationController popViewControllerAnimated:YES];
                    }];
                    [alert addAction:ok];
                    [self presentViewController:alert animated:YES completion:nil];
                } else {
                    NSString *errorMsg = error.localizedDescription ?: @"Failed to submit appointment.";
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Error"
                                                                                   message:errorMsg
                                                                            preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                               handler:nil]; // stay on the page
                    [alert addAction:ok];
                    [self presentViewController:alert animated:YES completion:nil];
                }
            });
        }];
    } else {
        NSDictionary *appointmentData = @{
            @"project_id": @"8",
            @"slot_id": self.slotId,
            @"appointment_type": self.appointmentType,
            @"user_id": @"2170",
            @"appointment_attendee_type": @"joint_owner",
            @"drawing_plan_id": @"135",
        };

        [AppointmentAPIClient submitAppointment:appointmentData completion:^(BOOL success, NSDictionary * _Nullable response, NSError * _Nullable error) {

            dispatch_async(dispatch_get_main_queue(), ^{
                if (success) {
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Success"
                                                                                   message:@"Your appointment was submitted successfully."
                                                                            preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                               handler:^(UIAlertAction * _Nonnull action) {
                        [self.navigationController popViewControllerAnimated:YES];
                    }];
                    [alert addAction:ok];
                    [self presentViewController:alert animated:YES completion:nil];
                } else {
                    NSString *errorMsg = error.localizedDescription ?: @"Failed to submit appointment.";
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Error"
                                                                                   message:errorMsg
                                                                            preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
                    [alert addAction:ok];
                    [self presentViewController:alert animated:YES completion:nil];
                }
            });
        }];
    }
}


- (void)setBlnTickRepresentative:(BOOL)blnTickRepresentative {
    if (_blnTickRepresentative != blnTickRepresentative) {
        NSLog(@"🔄 blnTickRepresentative changed: %@ -> %@", _blnTickRepresentative ? @"YES" : @"NO", blnTickRepresentative ? @"YES" : @"NO");
        _blnTickRepresentative = blnTickRepresentative;
    }
}

@end
