//  AppointmentTimeSlotViewController.mm

#import "AppointmentTimeSlotViewController.h"
#import "AppointmentConfirmationViewController.h"

@interface AppointmentTimeSlotViewController ()

// Header
@property (nonatomic, strong) UIView *headerBar;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *cancelButton;

// Labels
@property (nonatomic, strong) UILabel *unitLabel;
@property (nonatomic, strong) UILabel *unitLabelName;
@property (nonatomic, strong) UILabel *stepLabel;

// Content
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIStackView *contentStack;

// Time slots
@property (nonatomic, strong) NSArray<NSDictionary *> *aryTimeSlot;
@property (nonatomic, strong) NSString *selectedSlotID;
@property (nonatomic, strong) NSString *selectedStartDate;
@property (nonatomic, strong) NSString *selectedStartTime;

// Footer
@property (nonatomic, strong) UIView *footerView;
@property (nonatomic, strong) UIButton *backButton;
@property (nonatomic, strong) UIButton *nextButton;

// Loading
@property (nonatomic, strong) UIActivityIndicatorView *loadingIndicator;

@end

@implementation AppointmentTimeSlotViewController

#pragma mark - Lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;
  
  NSLog(@"📦 Data received by appointmentTimeSlot:"
        "\n projectId: %@"
        "\n projectName: %@"
        "\n drawingPlanId: %@"
        "\n unitName: %@"
        "\n appointmentType: %@"
        "\n timeSlot: %@"
        "\n termsAndCondition: %@"
        "\n representativeList: %@",
        self.projectId,
        self.projectName,
        self.drawingPlanId,
        self.unitName,
        self.appointmentType,
        self.timeSlot,
        self.termsAndCondition,
        self.representativeList);

    // Initialize defaults
    self.aryTimeSlot = @[];
    self.selectedSlotID = @"";
    self.selectedStartDate = @"";
    self.selectedStartTime = @"";

    [self setupHeader];
    [self setupFooter];
    [self setupScrollViewAndContent];
    [self setupLoadingIndicator];

    // If appointmentInfo already provided, consume it
    [self loadAppointmentInfoIfAvailable];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // Optionally track screen view here
}

#pragma mark - Setup UI

- (void)setupHeader {
    UILayoutGuide *safe = self.view.safeAreaLayoutGuide;

    self.headerBar = [[UIView alloc] init];
    self.headerBar.translatesAutoresizingMaskIntoConstraints = NO;
    self.headerBar.backgroundColor = [UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0]; // theme
    [self.view addSubview:self.headerBar];

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

    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.titleLabel.text = @"Make Appointment";
    self.titleLabel.textColor = UIColor.whiteColor;
    self.titleLabel.font = [UIFont systemFontOfSize:18 weight:UIFontWeightMedium];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.headerBar addSubview:self.titleLabel];

    self.cancelButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.cancelButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.cancelButton setImage:[UIImage systemImageNamed:@"xmark"] forState:UIControlStateNormal];
    self.cancelButton.tintColor = UIColor.whiteColor;
    [self.cancelButton addTarget:self action:@selector(cancelPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.headerBar addSubview:self.cancelButton];

    [NSLayoutConstraint activateConstraints:@[
        [self.cancelButton.leadingAnchor constraintEqualToAnchor:self.headerBar.leadingAnchor constant:16],
        [self.cancelButton.centerYAnchor constraintEqualToAnchor:self.headerBar.centerYAnchor],
        [self.cancelButton.widthAnchor constraintEqualToConstant:36],
        [self.cancelButton.heightAnchor constraintEqualToConstant:36],

        [self.titleLabel.centerXAnchor constraintEqualToAnchor:self.headerBar.centerXAnchor],
        [self.titleLabel.centerYAnchor constraintEqualToAnchor:self.headerBar.centerYAnchor]
    ]];
}

- (void)setupScrollViewAndContent {
    UILayoutGuide *safe = self.view.safeAreaLayoutGuide;

    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.footerView.topAnchor] // space for footer
    ]];

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

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

    // Main vertical stack
    self.contentStack = [[UIStackView alloc] init];
    self.contentStack.translatesAutoresizingMaskIntoConstraints = NO;
    self.contentStack.axis = UILayoutConstraintAxisVertical;
    self.contentStack.spacing = 12;
    [container addSubview:self.contentStack];

    [NSLayoutConstraint activateConstraints:@[
        [self.contentStack.topAnchor constraintEqualToAnchor:container.topAnchor constant:16],
        [self.contentStack.leadingAnchor constraintEqualToAnchor:container.leadingAnchor constant:16],
        [self.contentStack.trailingAnchor constraintEqualToAnchor:container.trailingAnchor constant:-16],
        [self.contentStack.bottomAnchor constraintLessThanOrEqualToAnchor:container.bottomAnchor constant:-16]
    ]];

    // Move labels into stack
    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.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.stepLabel = [[UILabel alloc] init];
    self.stepLabel.text = @"Step 2/3: Select your preferred time";
    self.stepLabel.font = [UIFont systemFontOfSize:14];
    self.stepLabel.textColor = [UIColor blackColor];
    self.stepLabel.textAlignment = NSTextAlignmentCenter;
    self.stepLabel.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1.0];
    self.stepLabel.layer.cornerRadius = 6.0;
    self.stepLabel.clipsToBounds = YES;
    [[self.stepLabel.heightAnchor constraintEqualToConstant:30] setActive:YES];

    // Section header for time slots
    UILabel *timeSlotHeader = [[UILabel alloc] init];
    timeSlotHeader.text = @"Available Time Slots";
    timeSlotHeader.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
    timeSlotHeader.textColor = [UIColor darkGrayColor];
    timeSlotHeader.textAlignment = NSTextAlignmentLeft;

    [self.contentStack addArrangedSubview:self.unitLabel];
    [self.contentStack addArrangedSubview:self.unitLabelName];
    [self.contentStack addArrangedSubview:self.stepLabel];
    [self.contentStack addArrangedSubview:timeSlotHeader];
}

- (void)setupFooter {
    self.footerView = [[UIView alloc] init];
    self.footerView.translatesAutoresizingMaskIntoConstraints = NO;
    self.footerView.backgroundColor = UIColor.whiteColor;
    self.footerView.layer.shadowOpacity = 0.1;
    self.footerView.layer.shadowOffset = CGSizeMake(0, -1);
    [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]
    ]];

    // Back button
    self.backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.backButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.backButton setTitle:@"Back" forState:UIControlStateNormal];
    self.backButton.layer.cornerRadius = 20;
    self.backButton.layer.borderWidth = 1;
    self.backButton.layer.borderColor = [UIColor colorWithRed:0.055 green:0.451 blue:0.573 alpha:1.0].CGColor;
    [self.backButton setTitleColor:[UIColor colorWithRed:0.055 green:0.451 blue:0.573 alpha:1.0] forState:UIControlStateNormal];
    [self.backButton addTarget:self action:@selector(backTapped:) forControlEvents:UIControlEventTouchUpInside];

    // Next button
    self.nextButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.nextButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.nextButton setTitle:@"Next" forState:UIControlStateNormal];
    self.nextButton.layer.cornerRadius = 20;
    self.nextButton.backgroundColor = [UIColor colorWithRed:0.055 green:0.451 blue:0.573 alpha:1.0];
    [self.nextButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [self.nextButton addTarget:self action:@selector(nextTapped:) forControlEvents:UIControlEventTouchUpInside];

    UIStackView *stack = [[UIStackView alloc] initWithArrangedSubviews:@[self.backButton, self.nextButton]];
    stack.translatesAutoresizingMaskIntoConstraints = NO;
    stack.axis = UILayoutConstraintAxisHorizontal;
    stack.spacing = 12;
    stack.distribution = UIStackViewDistributionFillEqually;

    [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]
    ]];
}

- (void)setupLoadingIndicator {
    self.loadingIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleLarge];
    self.loadingIndicator.translatesAutoresizingMaskIntoConstraints = NO;
    self.loadingIndicator.hidesWhenStopped = YES;
    [self.view addSubview:self.loadingIndicator];
    [NSLayoutConstraint activateConstraints:@[
        [self.loadingIndicator.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor],
        [self.loadingIndicator.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor]
    ]];
}

#pragma mark - Data handling

- (void)loadAppointmentInfoIfAvailable {
    if (self.timeSlot && [self.timeSlot isKindOfClass:[NSArray class]]) {
        self.aryTimeSlot = self.timeSlot;
    } else {
        self.aryTimeSlot = @[];
    }

    [self rebuildTimeSlotViews];
}


#pragma mark - Time Slot UI (2-column grid)
- (void)rebuildTimeSlotViews {
    // Remove previous time slot views (keep first 4: unitLabel, unitLabelName, stepLabel, header)
    while (self.contentStack.arrangedSubviews.count > 4) {
        UIView *v = self.contentStack.arrangedSubviews.lastObject;
        [self.contentStack removeArrangedSubview:v];
        [v removeFromSuperview];
    }

    // Build rows: two items per row
    NSInteger count = self.aryTimeSlot.count;
    for (NSInteger i = 0; i < count; i += 2) {
        UIView *row = [[UIView alloc] init];
        row.translatesAutoresizingMaskIntoConstraints = NO;
        row.backgroundColor = UIColor.clearColor;
        [[row.heightAnchor constraintEqualToConstant:40] setActive:YES];

        // Left slot
        NSDictionary *left = self.aryTimeSlot[i];
        UIButton *leftBtn = [self createTimeSlotButtonForIndex:i slot:left];
        [row addSubview:leftBtn];

        [NSLayoutConstraint activateConstraints:@[
            [leftBtn.leadingAnchor constraintEqualToAnchor:row.leadingAnchor],
            [leftBtn.topAnchor constraintEqualToAnchor:row.topAnchor],
            [leftBtn.bottomAnchor constraintEqualToAnchor:row.bottomAnchor],
            [leftBtn.widthAnchor constraintEqualToAnchor:row.widthAnchor multiplier:0.5 constant:-10]
        ]];

        // Right slot
        if (i + 1 < count) {
            NSDictionary *right = self.aryTimeSlot[i+1];
            UIButton *rightBtn = [self createTimeSlotButtonForIndex:i+1 slot:right];
            [row addSubview:rightBtn];
            [NSLayoutConstraint activateConstraints:@[
                [rightBtn.leadingAnchor constraintEqualToAnchor:leftBtn.trailingAnchor constant:20],
                [rightBtn.trailingAnchor constraintEqualToAnchor:row.trailingAnchor],
                [rightBtn.topAnchor constraintEqualToAnchor:row.topAnchor],
                [rightBtn.bottomAnchor constraintEqualToAnchor:row.bottomAnchor],
                [rightBtn.widthAnchor constraintEqualToAnchor:leftBtn.widthAnchor]
            ]];
        }

        [self.contentStack addArrangedSubview:row];

        // Spacer between rows
        UIView *spacer = [[UIView alloc] init];
        spacer.translatesAutoresizingMaskIntoConstraints = NO;
        [spacer.heightAnchor constraintEqualToConstant:8].active = YES;
        [self.contentStack addArrangedSubview:spacer];
    }
}

- (UIButton *)createTimeSlotButtonForIndex:(NSInteger)index slot:(NSDictionary *)slot {
    NSString *startTime = slot[@"start_time"] ?: @"";
    NSString *slotID = [slot[@"slot_id"] ?: slot[@"id"] stringValue] ?: @"";
    NSString *startDate = slot[@"start_date"] ?: @"";

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
    btn.tag = index; // identify which slot
    btn.translatesAutoresizingMaskIntoConstraints = NO;
    btn.layer.cornerRadius = 20;
    btn.layer.borderWidth = 0.5;
    btn.layer.borderColor = [UIColor colorWithWhite:0.63 alpha:1.0].CGColor;
    btn.backgroundColor = UIColor.clearColor;
    [btn setTitle:[self convertTimeString:startTime] forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor colorWithWhite:0.14 alpha:1.0] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:14];

    // store identifying info using associated objects? easiest is set accessibilityValue
    btn.accessibilityIdentifier = slotID;
    btn.accessibilityValue = startDate;
    [btn addTarget:self action:@selector(timeSlotTapped:) forControlEvents:UIControlEventTouchUpInside];

    // If already selected, style it
    if (self.selectedSlotID && [self.selectedSlotID isEqualToString:slotID]) {
        btn.layer.borderColor = [UIColor colorWithRed:0.055 green:0.451 blue:0.573 alpha:1.0].CGColor;
        btn.backgroundColor = [UIColor colorWithRed:0.863 green:0.969 blue:1.0 alpha:1.0]; // light blue
    }

    return btn;
}

#pragma mark - Actions

- (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
        [self.navigationController popToRootViewControllerAnimated:YES];
    }]];
    [self presentViewController:a animated:YES completion:nil];
}

- (void)backTapped:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)nextTapped:(id)sender {
    if (self.selectedSlotID.length == 0 ||
        self.selectedStartDate.length == 0 ||
        self.selectedStartTime.length == 0) {

        UIAlertController *a = [UIAlertController alertControllerWithTitle:@"Alert"
                                                                   message:@"Please select a time slot to continue."
                                                            preferredStyle:UIAlertControllerStyleAlert];
        [a addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:nil]];
        [self presentViewController:a animated:YES completion:nil];
        return;
    }

    NSMutableDictionary *obj = [self.appointmentInfo mutableCopy] ?: [NSMutableDictionary dictionary];
    obj[@"slot_id"] = self.selectedSlotID;
    obj[@"start_date"] = self.selectedStartDate;
    obj[@"start_time"] = self.selectedStartTime;

    if (self.didSelectAppointment) {
        self.didSelectAppointment([obj copy]);
        return;
    }

    AppointmentConfirmationViewController *appointVC = [[AppointmentConfirmationViewController alloc] init];
    appointVC.slotId = self.selectedSlotID;
    appointVC.startDate = self.selectedStartDate;
    appointVC.startTime = self.selectedStartTime;
    appointVC.projectId = self.projectId;
    appointVC.projectName = self.projectName;
    appointVC.termsAndCondition = self.termsAndCondition;
    appointVC.appointmentType = self.appointmentType;
  appointVC.representativeList = self.representativeList;
    appointVC.modalPresentationStyle = UIModalPresentationFullScreen;

    [self presentViewController:appointVC animated:YES completion:nil];
}

- (void)timeSlotTapped:(UIButton *)sender {
    NSString *slotID = sender.accessibilityIdentifier ?: @"";
    NSString *startDate = sender.accessibilityValue ?: @"";

    // find slot object to get start_time
    NSInteger idx = sender.tag;
    NSDictionary *slot = nil;
    if (idx >= 0 && idx < self.aryTimeSlot.count) slot = self.aryTimeSlot[idx];

    NSString *startTime = slot[@"start_time"] ?: @"";

    self.selectedSlotID = slotID;
    self.selectedStartDate = startDate;
    self.selectedStartTime = startTime;

    // Refresh UI: rebuild the slot views to reapply selected state
    [self rebuildTimeSlotViews];
}

#pragma mark - Helpers

- (NSString *)convertTimeString:(NSString *)timeStr {
    // expects "HH:mm:ss" return "HH:mm"
    if (!timeStr || timeStr.length == 0) return @"";
    NSDateFormatter *in = [[NSDateFormatter alloc] init];
    in.dateFormat = @"HH:mm:ss";
    NSDate *d = [in dateFromString:timeStr];
    if (!d) {
        // try HH:mm
        in.dateFormat = @"HH:mm";
        d = [in dateFromString:timeStr];
    }
    NSDateFormatter *out = [[NSDateFormatter alloc] init];
    out.dateFormat = @"HH:mm";
    if (d) return [out stringFromDate:d];
    return timeStr;
}

#pragma mark - Loading

- (void)setLoading:(BOOL)loading {
    dispatch_async(dispatch_get_main_queue(), ^{
        if (loading) {
            [self.loadingIndicator startAnimating];
        } else {
            [self.loadingIndicator stopAnimating];
        }
    });
}

@end


