//  AccessAppointmentViewController.mm
#import "AccessAppointmentViewController.h"

@interface AccessAppointmentViewController ()

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

// Top unit section
@property (nonatomic, strong) UIView *unitLine;

// Card + fields
@property (nonatomic, strong) UIView *cardView;
@property (nonatomic, strong) UILabel *typeValueLabel;
@property (nonatomic, strong) UILabel *dateValueLabel;
@property (nonatomic, strong) UILabel *timeValueLabel;
@property (nonatomic, strong) UILabel *issuesLabel;

// Buttons
@property (nonatomic, strong) UIButton *cancelButton;
@property (nonatomic, strong) UIButton *calendarButton;

@property (nonatomic, assign) BOOL canCancel;

@end

@implementation AccessAppointmentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithWhite:0.98 alpha:1];

    // Build UI
    [self setupHeader];
    [self setupScrollView];
    [self setupUnitSection];
    [self setupAppointmentCard];
    [self setupIssuesSection];
    [self setupActionButtonsIfNeeded];

    // Fill data
    [self populateData];
}

#pragma mark - Header
- (void)setupHeader {
    self.header = [[UIView alloc] init];
    self.header.translatesAutoresizingMaskIntoConstraints = NO;
    self.header.backgroundColor = [UIColor colorWithRed:0 green:0.45 blue:0.55 alpha:1];
    [self.view addSubview:self.header];

    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    titleLabel.textColor = UIColor.whiteColor;
    titleLabel.font = [UIFont boldSystemFontOfSize:18];
    titleLabel.text = @"Rectification Appointment";
    [self.header addSubview:titleLabel];

    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    backBtn.translatesAutoresizingMaskIntoConstraints = NO;
    [backBtn setImage:[UIImage systemImageNamed:@"chevron.backward"] forState:UIControlStateNormal];
    backBtn.tintColor = UIColor.whiteColor;
    [backBtn addTarget:self action:@selector(onBack) forControlEvents:UIControlEventTouchUpInside];
    [self.header addSubview:backBtn];

    [NSLayoutConstraint activateConstraints:@[
        [self.header.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor],
        [self.header.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.header.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.header.heightAnchor constraintEqualToConstant:48],

        [backBtn.leadingAnchor constraintEqualToAnchor:self.header.leadingAnchor constant:12],
        [backBtn.centerYAnchor constraintEqualToAnchor:self.header.centerYAnchor],

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

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

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

    [NSLayoutConstraint activateConstraints:@[
        [self.scrollView.topAnchor constraintEqualToAnchor:self.header.bottomAnchor constant:10],
        [self.scrollView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.scrollView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.scrollView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor],

        [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 - Unit header section
- (void)setupUnitSection {
    UILabel *forLabel = [[UILabel alloc] init];
    forLabel.translatesAutoresizingMaskIntoConstraints = NO;
    forLabel.text = @"For Unit No. :";
    forLabel.font = [UIFont systemFontOfSize:15 weight:UIFontWeightRegular];
    forLabel.textColor = [UIColor darkGrayColor];
    [self.contentView addSubview:forLabel];

    self.unitLabel = [[UILabel alloc] init];
    self.unitLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.unitLabel.font = [UIFont systemFontOfSize:28 weight:UIFontWeightBold];
    self.unitLabel.textColor = [UIColor blackColor];
    [self.contentView addSubview:self.unitLabel];

    UIView *separator = [[UIView alloc] init];
    separator.translatesAutoresizingMaskIntoConstraints = NO;
    separator.backgroundColor = [UIColor colorWithWhite:0.85 alpha:1];
    [self.contentView addSubview:separator];
    self.unitLine = separator;

    [NSLayoutConstraint activateConstraints:@[
        [forLabel.topAnchor constraintEqualToAnchor:self.contentView.topAnchor constant:18],
        [forLabel.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],

        [self.unitLabel.topAnchor constraintEqualToAnchor:forLabel.bottomAnchor constant:6],
        [self.unitLabel.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],

        [separator.topAnchor constraintEqualToAnchor:self.unitLabel.bottomAnchor constant:16],
        [separator.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],
        [separator.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-16],
        [separator.heightAnchor constraintEqualToConstant:1]
    ]];
}

#pragma mark - Appointment Card
- (void)setupAppointmentCard {
    self.cardView = [[UIView alloc] init];
    self.cardView.translatesAutoresizingMaskIntoConstraints = NO;
    self.cardView.backgroundColor = UIColor.whiteColor;
    self.cardView.layer.cornerRadius = 12;
    self.cardView.layer.shadowColor = [UIColor blackColor].CGColor;
    self.cardView.layer.shadowOpacity = 0.06;
    self.cardView.layer.shadowRadius = 6;
    self.cardView.layer.shadowOffset = CGSizeMake(0, 3);
    [self.contentView addSubview:self.cardView];

    // Title
    UILabel *title = [[UILabel alloc] init];
    title.translatesAutoresizingMaskIntoConstraints = NO;
    title.text = @"Appointment Info";
    title.font = [UIFont boldSystemFontOfSize:18];
    [self.cardView addSubview:title];

    // Type label + pill
    UILabel *typeLabel = [self lightLabelWithText:@"Type :"];
    [self.cardView addSubview:typeLabel];

    self.typeValueLabel = [self pillLabel:@"Rectification"];
    [self.cardView addSubview:self.typeValueLabel];

    // Calendar button (right)
    self.calendarButton = [self calendarBoxButton];
    [self.cardView addSubview:self.calendarButton];

    // Date
    UILabel *dateLabel = [self lightLabelWithText:@"Date :"];
    [self.cardView addSubview:dateLabel];

    self.dateValueLabel = [self regularLabelWithText:@"--"];
    [self.cardView addSubview:self.dateValueLabel];

    // Time
    UILabel *timeLabel = [self lightLabelWithText:@"Time Slot :"];
    [self.cardView addSubview:timeLabel];

    self.timeValueLabel = [self regularLabelWithText:@"--"];
    [self.cardView addSubview:self.timeValueLabel];

    // Layout constraints
    [NSLayoutConstraint activateConstraints:@[
        [self.cardView.topAnchor constraintEqualToAnchor:self.unitLine.bottomAnchor constant:18],
        [self.cardView.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],
        [self.cardView.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-16],

        [title.topAnchor constraintEqualToAnchor:self.cardView.topAnchor constant:16],
        [title.leadingAnchor constraintEqualToAnchor:self.cardView.leadingAnchor constant:16],

        [typeLabel.topAnchor constraintEqualToAnchor:title.bottomAnchor constant:18],
        [typeLabel.leadingAnchor constraintEqualToAnchor:self.cardView.leadingAnchor constant:16],

        [self.typeValueLabel.centerYAnchor constraintEqualToAnchor:typeLabel.centerYAnchor],
        [self.typeValueLabel.leadingAnchor constraintEqualToAnchor:typeLabel.trailingAnchor constant:8],

        [self.calendarButton.centerYAnchor constraintEqualToAnchor:self.typeValueLabel.centerYAnchor],
        [self.calendarButton.trailingAnchor constraintEqualToAnchor:self.cardView.trailingAnchor constant:-12],
        [self.calendarButton.widthAnchor constraintEqualToConstant:92],
        [self.calendarButton.heightAnchor constraintEqualToConstant:46],
        
        [dateLabel.topAnchor constraintEqualToAnchor:typeLabel.bottomAnchor constant:18],
        [dateLabel.leadingAnchor constraintEqualToAnchor:self.cardView.leadingAnchor constant:16],

        [self.dateValueLabel.centerYAnchor constraintEqualToAnchor:dateLabel.centerYAnchor],
        [self.dateValueLabel.leadingAnchor constraintEqualToAnchor:dateLabel.trailingAnchor constant:8],

        [timeLabel.topAnchor constraintEqualToAnchor:dateLabel.bottomAnchor constant:14],
        [timeLabel.leadingAnchor constraintEqualToAnchor:self.cardView.leadingAnchor constant:16],

        [self.timeValueLabel.centerYAnchor constraintEqualToAnchor:timeLabel.centerYAnchor],
        [self.timeValueLabel.leadingAnchor constraintEqualToAnchor:timeLabel.trailingAnchor constant:8],

        // bottom anchor of card (provides contentView sizing)
        [self.timeValueLabel.bottomAnchor constraintEqualToAnchor:self.cardView.bottomAnchor constant:-18]
    ]];
}

#pragma mark - Issues section
- (void)setupIssuesSection {
    UILabel *title = [[UILabel alloc] init];
    title.translatesAutoresizingMaskIntoConstraints = NO;
    title.text = @"Issue(s) Info";
    title.font = [UIFont boldSystemFontOfSize:18];
    [self.contentView addSubview:title];

    self.issuesLabel = [self regularLabelWithText:@"--"];
    self.issuesLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.issuesLabel.numberOfLines = 0;
    [self.contentView addSubview:self.issuesLabel];

    [NSLayoutConstraint activateConstraints:@[
        [title.topAnchor constraintEqualToAnchor:self.cardView.bottomAnchor constant:20],
        [title.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],

        [self.issuesLabel.topAnchor constraintEqualToAnchor:title.bottomAnchor constant:10],
        [self.issuesLabel.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],
        [self.issuesLabel.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-16],
        [self.issuesLabel.bottomAnchor constraintEqualToAnchor:self.contentView.bottomAnchor constant:-30]
    ]];
}

#pragma mark - Action Buttons (Cancel + optional)
- (void)setupActionButtonsIfNeeded {
    // If you always want to show cancel, set this to YES. Otherwise compute based on date/status.
    BOOL shouldShowCancel = NO; // default: no
    // If appointmentData includes a "can_cancel" key, respect it:
    if (self.appointmentData[@"can_cancel"]) {
        shouldShowCancel = [self.appointmentData[@"can_cancel"] boolValue];
    }

    if (!shouldShowCancel) return;

    // Cancel button
    self.cancelButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.cancelButton.translatesAutoresizingMaskIntoConstraints = NO;
    self.cancelButton.backgroundColor = [UIColor colorWithRed:0.86 green:0.27 blue:0.36 alpha:1]; // red
    [self.cancelButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [self.cancelButton setTitle:@"Cancel Appointment" forState:UIControlStateNormal];
    self.cancelButton.layer.cornerRadius = 10;
    [self.cancelButton addTarget:self action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];

    [self.contentView addSubview:self.cancelButton];

    [NSLayoutConstraint activateConstraints:@[
        [self.cancelButton.topAnchor constraintEqualToAnchor:self.cardView.bottomAnchor constant:20],
        [self.cancelButton.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],
        [self.cancelButton.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-16],
        [self.cancelButton.heightAnchor constraintEqualToConstant:52],

        [self.cancelButton.bottomAnchor constraintEqualToAnchor:self.contentView.bottomAnchor constant:-24]
    ]];
}

#pragma mark - Populate data
- (void)populateData {
    // appointmentData expected keys: unit_no, type, date, time_slot, issues
    if (self.appointmentData == nil) return;

    NSString *unitNo = self.appointmentData[@"unit_no"] ?: @"--";
    self.unitLabel.text = unitNo;

    NSString *type = self.appointmentData[@"type"] ?: @"Rectification";
    self.typeValueLabel.text = type;

    // date parsing: accepts yyyy-MM-dd or server format; fallback to raw string
    NSString *rawDate = self.appointmentData[@"date"];
    if (rawDate) {
        NSString *formatted = [self formattedDateStringFromRaw:rawDate];
        self.dateValueLabel.text = formatted;
    }

    NSString *timeSlot = self.appointmentData[@"time_slot"] ?: self.appointmentData[@"time"] ?: @"--";
    self.timeValueLabel.text = timeSlot;

    NSString *issues = self.appointmentData[@"issues"];
    if (!issues && self.appointmentData[@"issue_list"]) {
        NSArray *arr = self.appointmentData[@"issue_list"];
        issues = [arr componentsJoinedByString:@"\n"];
    }
    self.issuesLabel.text = issues ?: @"No issues specified";
}

#pragma mark - Helpers / UI helpers
- (UILabel *)lightLabelWithText:(NSString *)text {
    UILabel *lbl = [[UILabel alloc] init];
    lbl.translatesAutoresizingMaskIntoConstraints = NO;
    lbl.text = text;
    lbl.font = [UIFont systemFontOfSize:15 weight:UIFontWeightRegular];
    lbl.textColor = [UIColor darkGrayColor];
    return lbl;
}

- (UILabel *)regularLabelWithText:(NSString *)text {
    UILabel *lbl = [[UILabel alloc] init];
    lbl.translatesAutoresizingMaskIntoConstraints = NO;
    lbl.text = text;
    lbl.font = [UIFont systemFontOfSize:16 weight:UIFontWeightRegular];
    lbl.textColor = [UIColor blackColor];
    return lbl;
}

- (UILabel *)pillLabel:(NSString *)text {
    UILabel *lbl = [[UILabel alloc] init];
    lbl.translatesAutoresizingMaskIntoConstraints = NO;
    lbl.text = text;
    lbl.textAlignment = NSTextAlignmentCenter;
    lbl.font = [UIFont boldSystemFontOfSize:14];
    lbl.textColor = UIColor.whiteColor;
    lbl.backgroundColor = [UIColor colorWithRed:1.0 green:0.55 blue:0.2 alpha:1];
    lbl.layer.cornerRadius = 14;
    lbl.clipsToBounds = YES;

    // fixed intrinsic size constraints for pill appearance
    [NSLayoutConstraint activateConstraints:@[
        [lbl.widthAnchor constraintGreaterThanOrEqualToConstant:100],
        [lbl.heightAnchor constraintEqualToConstant:28]
    ]];

    return lbl;
}

- (UIButton *)calendarBoxButton {
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
    btn.translatesAutoresizingMaskIntoConstraints = NO;
    btn.layer.cornerRadius = 8;
    btn.layer.borderWidth = 1;
    btn.layer.borderColor = [UIColor colorWithWhite:0.85 alpha:1].CGColor;

    // Compose text + icon using title + image
    UIImage *icon = [UIImage systemImageNamed:@"calendar"];
    [btn setImage:icon forState:UIControlStateNormal];
    btn.tintColor = [UIColor darkGrayColor];

    // multiline title
    [btn setTitle:@"  Add To\n  Calendar" forState:UIControlStateNormal];
    btn.titleLabel.numberOfLines = 2;
    btn.titleLabel.font = [UIFont systemFontOfSize:12];
    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    btn.imageEdgeInsets = UIEdgeInsetsMake(8, 8, 8, 0);
    btn.titleEdgeInsets = UIEdgeInsetsMake(6, 4, 6, 8);

    [btn addTarget:self action:@selector(addToCalendarTapped) forControlEvents:UIControlEventTouchUpInside];

    return btn;
}

#pragma mark - Date formatting
- (NSString *)formattedDateStringFromRaw:(NSString *)raw {
    if (!raw) return @"--";

    // try common formats
    NSArray<NSString *> *formats = @[@"yyyy-MM-dd", @"yyyy-MM-dd HH:mm:ss", @"yyyy-MM-dd'T'HH:mm:ss'Z'"];
    NSDate *d = nil;
    NSDateFormatter *inFmt = [[NSDateFormatter alloc] init];
    inFmt.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];

    for (NSString *fmt in formats) {
        inFmt.dateFormat = fmt;
        d = [inFmt dateFromString:raw];
        if (d) break;
    }
    if (!d) return raw; // fallback

    NSDateFormatter *out = [[NSDateFormatter alloc] init];
    out.locale = [NSLocale localeWithLocaleIdentifier:@"en_US"];
    out.dateFormat = @"dd MMM yyyy";
    return [out stringFromDate:d];
}

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

- (void)addToCalendarTapped {
    // Hook: create event using EventKit if you want
    UIAlertController *a = [UIAlertController alertControllerWithTitle:@"Add to Calendar"
                                                               message:@"Calendar integration not implemented yet."
                                                        preferredStyle:UIAlertControllerStyleAlert];
    [a addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:a animated:YES completion:nil];
}

- (void)cancelPressed {
    UIAlertController *confirm = [UIAlertController alertControllerWithTitle:@"Cancel Appointment"
                                                                     message:@"Are you sure you want to cancel this appointment?"
                                                              preferredStyle:UIAlertControllerStyleAlert];
    [confirm addAction:[UIAlertAction actionWithTitle:@"No" style:UIAlertActionStyleCancel handler:nil]];
    [confirm addAction:[UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        [self showReasonPopupForCancellation];
    }]];
    [self presentViewController:confirm animated:YES completion:nil];
}

- (void)showReasonPopupForCancellation {
    UIAlertController *reasonAlert =
    [UIAlertController alertControllerWithTitle:@"Reason for Cancellation"
                                        message:@"Please tell us why you want to cancel this appointment."
                                 preferredStyle:UIAlertControllerStyleAlert];

    [reasonAlert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"Enter reason...";
    }];

    [reasonAlert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil]];
    [reasonAlert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        NSString *remarks = reasonAlert.textFields.firstObject.text ?: @"";
        [self sendCancellationRequestWithReason:remarks];
    }]];

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

- (void)sendCancellationRequestWithReason:(NSString *)remarks {
    if (remarks.length == 0) remarks = @"No reason provided";
    if (!self.appointmentData[@"id"]) {
        NSLog(@"No appointment id, aborting cancellation");
        return;
    }

    // call API - placeholder
    // [AppointmentAPIClient fetchCancelAppointment:self.appointmentData[@"id"] reason:remarks completion:...]
    // For now simulate success:
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        UIAlertController *status = [UIAlertController alertControllerWithTitle:@"Appointment Cancelled"
                                                                        message:@"Your appointment has been cancelled."
                                                                 preferredStyle:UIAlertControllerStyleAlert];
        [status addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self dismissViewControllerAnimated:YES completion:nil];
        }]];
        [self presentViewController:status animated:YES completion:nil];
    });
}

@end
