//  AccessAppointmentViewController.mm
#import "AccessAppointmentViewController.h"
#import <EventKit/EventKit.h>
#import "APIClient.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;
@property (nonatomic, strong) UILabel *issuesTitle;

// 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 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 ---
    UILabel *typeLabel = [self lightLabelWithText:@"Type :"];
    [self.cardView addSubview:typeLabel];

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

    // --- Calendar button ---
    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];

    // --- Issues section (stack view) ---
    self.issuesTitle = [[UILabel alloc] init];
    self.issuesTitle.translatesAutoresizingMaskIntoConstraints = NO;
    self.issuesTitle.text = @"Issue(s) Info";
    self.issuesTitle.font = [UIFont boldSystemFontOfSize:18];

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

    UIStackView *issuesStack = [[UIStackView alloc] init];
    issuesStack.translatesAutoresizingMaskIntoConstraints = NO;
    issuesStack.axis = UILayoutConstraintAxisVertical;
    issuesStack.spacing = 6;
    [issuesStack addArrangedSubview:self.issuesTitle];
    [issuesStack addArrangedSubview:self.issuesLabel];
    [self.cardView addSubview:issuesStack];

    // --- Layout constraints ---
    [NSLayoutConstraint activateConstraints:@[
        // Card position
        [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
        [title.topAnchor constraintEqualToAnchor:self.cardView.topAnchor constant:16],
        [title.leadingAnchor constraintEqualToAnchor:self.cardView.leadingAnchor constant:16],

        // Type
        [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],

        // Date
        [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],

        // Time
        [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],

        // Issues stack
        [issuesStack.topAnchor constraintEqualToAnchor:self.timeValueLabel.bottomAnchor constant:16],
        [issuesStack.leadingAnchor constraintEqualToAnchor:self.cardView.leadingAnchor constant:16],
        [issuesStack.trailingAnchor constraintEqualToAnchor:self.cardView.trailingAnchor constant:-16],
        [issuesStack.bottomAnchor constraintEqualToAnchor:self.cardView.bottomAnchor constant:-16]
    ]];
}

#pragma mark - Action Buttons (Cancel + optional)
- (void)setupActionButtonsIfNeeded {
    NSString *status = self.appointmentData[@"appointment_status"];
  
    // Only show cancel button if status is "Confirmed"
    BOOL shouldShowCancel = [status isEqualToString:@"Confirmed"];
    
    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.unitID ?: @"--";
    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[@"appointment_date"];
    if (rawDate) {
        NSString *formatted = [self formattedDateStringFromRaw:rawDate];
        self.dateValueLabel.text = formatted;
    }

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

    NSArray *issuesArray = self.appointmentData[@"Issues"];
    if (!issuesArray || issuesArray.count == 0) {
        self.issuesTitle.hidden = YES;
        self.issuesLabel.hidden = YES;
        NSLog(@"Hiding Issues");
    } else {
        self.issuesTitle.hidden = NO;
        self.issuesLabel.hidden = NO;
        NSLog(@"Showing issues");

        NSMutableArray *refs = [NSMutableArray array];
        NSMutableArray *numLines = [NSMutableArray array];
        NSInteger idx = 1;
        for (NSDictionary *issueDict in issuesArray) {
            NSString *ref = issueDict[@"reference"];
          if (ref) {
              [numLines addObject:[NSString stringWithFormat:@"%ld. %@", (long)idx, ref]];
              idx++;
          }
        }
        self.issuesLabel.text = [numLines componentsJoinedByString:@"\n"];
    }
}

#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 {
    EKEventStore *eventStore = [[EKEventStore alloc] init];
    
    // Request access to Calendar
    [eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
            dispatch_async(dispatch_get_main_queue(), ^{
                EKEvent *event = [EKEvent eventWithEventStore:eventStore];
                
                // Set title
                NSString *title = [NSString stringWithFormat:@"[%@] %@: %@.",
                                   self.appointmentData[@"project_name"],
                                   self.appointmentData[@"unit_no"],
                                   self.appointmentData[@"appointment_type"]];
                event.title = title;
                
                // Set start & end dates
                NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                formatter.dateFormat = @"dd MMM yyyy hh:mm a";
                
                NSString *startString = [NSString stringWithFormat:@"%@ %@",
                                         self.appointmentData[@"appointment_date"],
                                         self.appointmentData[@"appointment_time"]];
                
                event.startDate = [formatter dateFromString:startString];
                
                // Add to default calendar
                event.calendar = [eventStore defaultCalendarForNewEvents];
                
                NSError *err = nil;
                [eventStore saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
                
                if (err) {
                    NSLog(@"❌ Error saving event: %@", err);
                } else {
                    NSLog(@"✅ Event saved successfully");
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Success"
                                                                                   message:@"Event added to Calendar"
                                                                            preferredStyle:UIAlertControllerStyleAlert];
                    [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];
                    [self presentViewController:alert animated:YES completion:nil];
                }
            });
        } else {
            NSLog(@"❌ Calendar permission not granted: %@", error);
            dispatch_async(dispatch_get_main_queue(), ^{
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Permission Denied"
                                                                               message:@"Enable Calendar access in Settings"
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];
                [self presentViewController:alert 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(@"❌ Cannot cancel appointment: appointmentID is nil");
        return;
    }

    [APIClient requestCancelAppointment:self.appointmentData[@"appointment_id"]
                                          reason:remarks
                                      completion:^(NSDictionary *data, NSError *error)
    {
        dispatch_async(dispatch_get_main_queue(), ^{

            NSString *title;
            NSString *message;

            if (error) {
                title = @"Cancellation Failed";
                message = error.localizedDescription ?: @"An unknown error occurred.";
            } else {
                title = @"Appointment Cancelled";
                message = @"Your appointment has been successfully cancelled.";
            }

            UIAlertController *statusAlert =
            [UIAlertController alertControllerWithTitle:title
                                                message:message
                                         preferredStyle:UIAlertControllerStyleAlert];

            [statusAlert addAction:[UIAlertAction actionWithTitle:@"OK"
                                                            style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * _Nonnull action) {
//                 Optional: dismiss this screen if you want after user taps OK
              [self dismissViewControllerAnimated:YES completion:nil];
            }]];

            [self presentViewController:statusAlert animated:YES completion:nil];
        });
    }];
}

@end
