//  AppointmentTimeSlotViewController.mm

#import "AppointmentTimeSlotViewController.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 appointment:"
        "\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 setupScrollViewAndContent];
    [self setupFooter];
    [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.view.safeAreaLayoutGuide.bottomAnchor constant:-80] // 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]
    ]];

    // Unit label
    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.view 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.view addSubview:self.unitLabelName];

    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.translatesAutoresizingMaskIntoConstraints = NO;
    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.view addSubview:self.stepLabel];

    [NSLayoutConstraint activateConstraints:@[
        [self.unitLabel.topAnchor constraintEqualToAnchor:self.headerBar.bottomAnchor constant:16],
        [self.unitLabel.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:16],
        [self.unitLabel.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:-16],

        [self.unitLabelName.topAnchor constraintEqualToAnchor:self.unitLabel.bottomAnchor constant:8],
        [self.unitLabelName.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:16],
        [self.unitLabelName.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:-16],
        
        [self.stepLabel.topAnchor constraintEqualToAnchor:self.unitLabelName.bottomAnchor constant:16],
        [self.stepLabel.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:16],
        [self.stepLabel.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:-16],
        [self.stepLabel.heightAnchor constraintEqualToConstant:30]
    ]];
}

- (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.appointmentInfo && [self.appointmentInfo isKindOfClass:[NSDictionary class]]) {
        // Populate UI and state from appointmentInfo
        NSArray *timeSlots = self.appointmentInfo[@"time_slot"];
        if ([timeSlots isKindOfClass:[NSArray class]]) {
            self.aryTimeSlot = timeSlots;
        } else {
            self.aryTimeSlot = @[];
        }

        // Build time slot UI now that we have data
        [self rebuildTimeSlotViews];
    }
}

#pragma mark - Time Slot UI (2-column grid)

- (void)rebuildTimeSlotViews {
    // First remove any previously added time-slot views from contentStack (after the step container)
    // Find index of step container in contentStack then remove everything after it, or simply remove any arranged subviews that are not the first 3
    // We'll remove any arranged subviews after the step container to keep labels intact.
    while (self.contentStack.arrangedSubviews.count > 3) {
        UIView *v = self.contentStack.arrangedSubviews.lastObject;
        [self.contentStack removeArrangedSubview:v];
        [v removeFromSuperview];
    }

    // Create container for time slots
    UIView *slotsContainer = [[UIView alloc] init];
    slotsContainer.translatesAutoresizingMaskIntoConstraints = NO;
    [self.contentStack addArrangedSubview:slotsContainer];

    // 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;

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

        // Right slot (may not exist)
        UIButton *rightBtn = nil;
        if (i + 1 < count) {
            NSDictionary *right = self.aryTimeSlot[i+1];
            rightBtn = [self createTimeSlotButtonForIndex:i+1 slot:right];
            rightBtn.translatesAutoresizingMaskIntoConstraints = NO;
            [row addSubview:rightBtn];
        }

        [slotsContainer addSubview:row];

        // Layout row children
        CGFloat padding = 0;
        [NSLayoutConstraint activateConstraints:@[
            [row.leadingAnchor constraintEqualToAnchor:slotsContainer.leadingAnchor],
            [row.trailingAnchor constraintEqualToAnchor:slotsContainer.trailingAnchor],
            // height fixed same as RN (40)
            [row.heightAnchor constraintEqualToConstant:40],
        ]];

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

        if (rightBtn) {
            [NSLayoutConstraint activateConstraints:@[
                [rightBtn.trailingAnchor constraintEqualToAnchor:row.trailingAnchor constant:0],
                [rightBtn.topAnchor constraintEqualToAnchor:row.topAnchor constant:0],
                [rightBtn.bottomAnchor constraintEqualToAnchor:row.bottomAnchor constant:0],
                [rightBtn.leadingAnchor constraintEqualToAnchor:leftBtn.trailingAnchor constant:20],
                [rightBtn.widthAnchor constraintEqualToAnchor:leftBtn.widthAnchor]
            ]];
        } else {
            // if right missing, fill space with empty view to keep alignment
            UIView *filler = [[UIView alloc] init];
            filler.translatesAutoresizingMaskIntoConstraints = NO;
            [row addSubview:filler];
            [NSLayoutConstraint activateConstraints:@[
                [filler.leadingAnchor constraintEqualToAnchor:leftBtn.trailingAnchor constant:20],
                [filler.trailingAnchor constraintEqualToAnchor:row.trailingAnchor constant:0],
                [filler.topAnchor constraintEqualToAnchor:row.topAnchor constant:0],
                [filler.bottomAnchor constraintEqualToAnchor:row.bottomAnchor constant:0]
            ]];
        }

        // Add spacing below each row
        UIView *spacer = [[UIView alloc] init];
        spacer.translatesAutoresizingMaskIntoConstraints = NO;
        spacer.backgroundColor = UIColor.clearColor;
        [self.contentStack addArrangedSubview:row];
        [self.contentStack addArrangedSubview:spacer];
        [NSLayoutConstraint activateConstraints:@[
            [spacer.heightAnchor constraintEqualToConstant:8]
        ]];
    }
}

- (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]);
    } else {
        // push AppointmentConfirmationViewController (assumes it exists)
        // You must replace the below lines with your app's confirmation screen push
        UIViewController *conf = [NSClassFromString(@"AppointmentConfirmationViewController") new];
        if (conf) {
            if ([conf respondsToSelector:@selector(setAppointmentInfo:)]) {
                // prefer setter if exists
                [conf setValue:[obj copy] forKey:@"appointmentInfo"];
            }
            [self.navigationController pushViewController:conf animated:YES];
        } else {
            // fallback: just log
            NSLog(@"Next tapped - appointment object: %@", obj);
        }
    }
}

- (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


