// AppointmentDetailsViewController.mm

#import "AppointmentDetailsViewController.h"
#import "AppointmentAPIClient.h"
#import <WebKit/WebKit.h>

@interface AppointmentDetailsViewController ()

// Fixed UI
@property (nonatomic, strong) UIView *navBar;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *backButton;
@property (nonatomic, strong) UIView *unitInfoHeader;
@property (nonatomic, strong) UIView *tabsBar;
@property (nonatomic, strong) UIButton *summaryBtn;
@property (nonatomic, strong) UIButton *ownerBtn;

// Scrollable content for each tab
@property (nonatomic, strong) UIScrollView *summaryScrollView;
@property (nonatomic, strong) UIView *summaryContentView;
@property (nonatomic, strong) UIView *summaryCard;
@property (nonatomic, strong) UIButton *summaryCancelBtn;
@property (nonatomic, strong) UILabel *typeField;
@property (nonatomic, strong) UILabel *dateField;
@property (nonatomic, strong) UILabel *slotField;
@property (nonatomic, strong) UILabel *locField;
@property (nonatomic, strong) UILabel *termsField;

@property (nonatomic, strong) UIScrollView *ownerScrollView;
@property (nonatomic, strong) UIView *ownerContentView;
@property (nonatomic, strong) NSMutableArray<UIView *> *ownerCards;
@property (nonatomic, strong) UIButton *ownerCancelBtn;


@end

@implementation AppointmentDetailsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;
    
    [self setupNavBar];
    [self setupUnitInfoHeader];
    [self setupTabsBar];
    [self setupSummaryScrollView];
    [self setupOwnerScrollView];
    
    [self showSummary]; // default tab
}

#pragma mark - NavBar
- (void)setupNavBar {
    self.navBar = [[UIView alloc] init];
    self.navBar.backgroundColor = [UIColor colorWithRed:0 green:0.45 blue:0.55 alpha:1];
    self.navBar.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.navBar];
    
    self.backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.backButton setImage:[UIImage imageNamed:@"icon_white_back"] forState:UIControlStateNormal];
    [self.backButton addTarget:self action:@selector(backTapped) forControlEvents:UIControlEventTouchUpInside];
    self.backButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.navBar addSubview:self.backButton];
    
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.text = @"Appointment Details";
    self.titleLabel.font = [UIFont boldSystemFontOfSize:17];
    self.titleLabel.textColor = UIColor.whiteColor;
    self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.navBar addSubview:self.titleLabel];
    
    [NSLayoutConstraint activateConstraints:@[
        [self.navBar.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor],
        [self.navBar.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.navBar.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.navBar.heightAnchor constraintEqualToConstant:50],
        
        [self.backButton.leadingAnchor constraintEqualToAnchor:self.navBar.leadingAnchor constant:10],
        [self.backButton.centerYAnchor constraintEqualToAnchor:self.navBar.centerYAnchor],
        [self.backButton.widthAnchor constraintEqualToConstant:30],
        [self.backButton.heightAnchor constraintEqualToConstant:30],
        
        [self.titleLabel.centerXAnchor constraintEqualToAnchor:self.navBar.centerXAnchor],
        [self.titleLabel.centerYAnchor constraintEqualToAnchor:self.navBar.centerYAnchor],
    ]];
}

#pragma mark - Unit Info Header
- (void)setupUnitInfoHeader {
    UIView *header = [[UIView alloc] init];
    header.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:header];

    // Line 1: "For Unit No.:"
    UILabel *unitText = [[UILabel alloc] init];
    unitText.text = @"For Unit No.:";
    unitText.textColor = UIColor.darkGrayColor;
    unitText.font = [UIFont systemFontOfSize:14];
    unitText.translatesAutoresizingMaskIntoConstraints = NO;
    [header addSubview:unitText];

    // Line 2: the actual unit number
    UILabel *unitNumber = [[UILabel alloc] init];
    unitNumber.text = self.appointmentData[@"unit_no"];
    unitNumber.font = [UIFont boldSystemFontOfSize:22];
    unitNumber.translatesAutoresizingMaskIntoConstraints = NO;
    [header addSubview:unitNumber];

    UILabel *unitType = [[UILabel alloc] init];
    unitType.text = self.appointmentData[@"unit_type"];
    unitType.font = [UIFont systemFontOfSize:14];
    unitType.textColor = UIColor.grayColor;
    unitType.translatesAutoresizingMaskIntoConstraints = NO;
    [header addSubview:unitType];

    UIImageView *floorPlan = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"placeholder_floorplan"]];
    floorPlan.layer.cornerRadius = 8;
    floorPlan.layer.borderColor = [UIColor colorWithWhite:0.85 alpha:1].CGColor;
    floorPlan.layer.borderWidth = 1;
    floorPlan.clipsToBounds = YES;
    floorPlan.translatesAutoresizingMaskIntoConstraints = NO;
    [header addSubview:floorPlan];

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

        // Stack unit labels vertically
        [unitText.topAnchor constraintEqualToAnchor:header.topAnchor],
        [unitText.leadingAnchor constraintEqualToAnchor:header.leadingAnchor],

        [unitNumber.topAnchor constraintEqualToAnchor:unitText.bottomAnchor constant:2],
        [unitNumber.leadingAnchor constraintEqualToAnchor:header.leadingAnchor],

        [unitType.topAnchor constraintEqualToAnchor:unitNumber.bottomAnchor constant:2],
        [unitType.leadingAnchor constraintEqualToAnchor:header.leadingAnchor],

        [floorPlan.centerYAnchor constraintEqualToAnchor:header.centerYAnchor],
        [floorPlan.trailingAnchor constraintEqualToAnchor:header.trailingAnchor],
        [floorPlan.widthAnchor constraintEqualToConstant:120],
        [floorPlan.heightAnchor constraintEqualToConstant:120],

        [header.bottomAnchor constraintEqualToAnchor:unitType.bottomAnchor constant:20]
    ]];

    self.unitInfoHeader = header;
}


#pragma mark - Tabs
- (void)setupTabsBar {
    self.tabsBar = [[UIView alloc] init];
    self.tabsBar.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.tabsBar];
    
    self.summaryBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.summaryBtn setTitle:@"Summary" forState:UIControlStateNormal];
    self.summaryBtn.backgroundColor = [UIColor colorWithRed:0 green:0.45 blue:0.55 alpha:1];
    self.summaryBtn.layer.cornerRadius = 20;
    [self.summaryBtn addTarget:self action:@selector(showSummary) forControlEvents:UIControlEventTouchUpInside];
    self.summaryBtn.translatesAutoresizingMaskIntoConstraints = NO;
    [self.tabsBar addSubview:self.summaryBtn];
    
    self.ownerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.ownerBtn setTitle:@"Owner Info" forState:UIControlStateNormal];
    self.ownerBtn.backgroundColor = [UIColor lightGrayColor];
    self.ownerBtn.layer.cornerRadius = 20;
    [self.ownerBtn addTarget:self action:@selector(showOwnerInfo) forControlEvents:UIControlEventTouchUpInside];
    self.ownerBtn.translatesAutoresizingMaskIntoConstraints = NO;
    [self.tabsBar addSubview:self.ownerBtn];
    
    [NSLayoutConstraint activateConstraints:@[
        [self.tabsBar.topAnchor constraintEqualToAnchor:self.unitInfoHeader.bottomAnchor constant:10],
        [self.tabsBar.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:16],
        [self.tabsBar.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:-16],
        [self.tabsBar.heightAnchor constraintEqualToConstant:40],
        
        [self.summaryBtn.leadingAnchor constraintEqualToAnchor:self.tabsBar.leadingAnchor],
        [self.summaryBtn.topAnchor constraintEqualToAnchor:self.tabsBar.topAnchor],
        [self.summaryBtn.bottomAnchor constraintEqualToAnchor:self.tabsBar.bottomAnchor],
        [self.summaryBtn.widthAnchor constraintEqualToAnchor:self.tabsBar.widthAnchor multiplier:0.5],
        
        [self.ownerBtn.trailingAnchor constraintEqualToAnchor:self.tabsBar.trailingAnchor],
        [self.ownerBtn.topAnchor constraintEqualToAnchor:self.tabsBar.topAnchor],
        [self.ownerBtn.bottomAnchor constraintEqualToAnchor:self.tabsBar.bottomAnchor],
        [self.ownerBtn.widthAnchor constraintEqualToAnchor:self.tabsBar.widthAnchor multiplier:0.5],
    ]];
}

#pragma mark - Summary ScrollView
- (void)setupSummaryScrollView {
    self.summaryScrollView = [[UIScrollView alloc] init];
    self.summaryScrollView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.summaryScrollView];
    
    self.summaryContentView = [[UIView alloc] init];
    self.summaryContentView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.summaryScrollView addSubview:self.summaryContentView];
    
    [NSLayoutConstraint activateConstraints:@[
        [self.summaryScrollView.topAnchor constraintEqualToAnchor:self.tabsBar.bottomAnchor constant:10],
        [self.summaryScrollView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.summaryScrollView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.summaryScrollView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor],
        
        [self.summaryContentView.topAnchor constraintEqualToAnchor:self.summaryScrollView.topAnchor],
        [self.summaryContentView.leadingAnchor constraintEqualToAnchor:self.summaryScrollView.leadingAnchor],
        [self.summaryContentView.trailingAnchor constraintEqualToAnchor:self.summaryScrollView.trailingAnchor],
        [self.summaryContentView.bottomAnchor constraintEqualToAnchor:self.summaryScrollView.bottomAnchor],
        [self.summaryContentView.widthAnchor constraintEqualToAnchor:self.summaryScrollView.widthAnchor],
    ]];
    
    // Summary card
    self.summaryCard = [[UIView alloc] init];
    self.summaryCard.backgroundColor = UIColor.whiteColor;
    self.summaryCard.layer.cornerRadius = 12;
    self.summaryCard.layer.borderWidth = 1;
    self.summaryCard.layer.borderColor = [UIColor colorWithWhite:0.9 alpha:1].CGColor;
    self.summaryCard.translatesAutoresizingMaskIntoConstraints = NO;
    [self.summaryContentView addSubview:self.summaryCard];
    
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = @"Appointment Info";
    titleLabel.font = [UIFont boldSystemFontOfSize:16];
    titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.summaryCard addSubview:titleLabel];
  
    UILabel *(^makeField)(NSString*, NSString*) = ^UILabel*(NSString *label, NSString *value) {
        UILabel *field = [[UILabel alloc] init];
        field.numberOfLines = 0;
        field.font = [UIFont systemFontOfSize:15];
        field.text = [NSString stringWithFormat:@"%@ %@", label, value];
        field.translatesAutoresizingMaskIntoConstraints = NO;
        [self.summaryCard addSubview:field];
        return field;
    };

    self.typeField = makeField(@"Type:", self.appointmentData[@"appointment_type"]);
    self.dateField = makeField(@"Date:", self.appointmentData[@"appointment_date"]);
    self.slotField = makeField(@"Time Slot:", self.appointmentData[@"appointment_time"]);
    self.locField = makeField(@"Location:", self.appointmentData[@"location"]);
    self.termsField = makeField(@"Terms & Conditions:", @"View Here");

    [NSLayoutConstraint activateConstraints:@[
        [self.summaryCard.topAnchor constraintEqualToAnchor:self.summaryContentView.topAnchor constant:20],
        [self.summaryCard.leadingAnchor constraintEqualToAnchor:self.summaryContentView.leadingAnchor constant:16],
        [self.summaryCard.trailingAnchor constraintEqualToAnchor:self.summaryContentView.trailingAnchor constant:-16],
        
        [titleLabel.topAnchor constraintEqualToAnchor:self.summaryCard.topAnchor constant:16],
        [titleLabel.leadingAnchor constraintEqualToAnchor:self.summaryCard.leadingAnchor constant:16],
        [titleLabel.trailingAnchor constraintEqualToAnchor:self.summaryCard.trailingAnchor constant:-16],
        [titleLabel.bottomAnchor constraintEqualToAnchor:self.summaryCard.bottomAnchor constant:-16],
        
        [self.typeField.topAnchor constraintEqualToAnchor:titleLabel.bottomAnchor constant:12],
        [self.typeField.leadingAnchor constraintEqualToAnchor:self.summaryCard.leadingAnchor constant:16],
        [self.typeField.trailingAnchor constraintEqualToAnchor:self.summaryCard.trailingAnchor constant:-16],
        
        [self.dateField.topAnchor constraintEqualToAnchor:self.typeField.bottomAnchor constant:12],
        [self.dateField.leadingAnchor constraintEqualToAnchor:self.summaryCard.leadingAnchor constant:16],
        [self.dateField.trailingAnchor constraintEqualToAnchor:self.summaryCard.trailingAnchor constant:-16],
        
        [self.slotField.topAnchor constraintEqualToAnchor:self.dateField.bottomAnchor constant:12],
        [self.slotField.leadingAnchor constraintEqualToAnchor:self.summaryCard.leadingAnchor constant:16],
        [self.slotField.trailingAnchor constraintEqualToAnchor:self.summaryCard.trailingAnchor constant:-16],
        
        [self.locField.topAnchor constraintEqualToAnchor:self.slotField.bottomAnchor constant:12],
        [self.locField.leadingAnchor constraintEqualToAnchor:self.summaryCard.leadingAnchor constant:16],
        [self.locField.trailingAnchor constraintEqualToAnchor:self.summaryCard.trailingAnchor constant:-16],
        
        [self.termsField.topAnchor constraintEqualToAnchor:self.locField.bottomAnchor constant:12],
        [self.termsField.leadingAnchor constraintEqualToAnchor:self.summaryCard.leadingAnchor constant:16],
        [self.termsField.trailingAnchor constraintEqualToAnchor:self.summaryCard.trailingAnchor constant:-16],
    ]];
    
    // Cancel button
    self.summaryCancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.summaryCancelBtn setTitle:@"Cancel Appointment" forState:UIControlStateNormal];
    self.summaryCancelBtn.backgroundColor = [UIColor systemRedColor];
    self.summaryCancelBtn.layer.cornerRadius = 12;
    [self.summaryCancelBtn addTarget:self action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
    self.summaryCancelBtn.translatesAutoresizingMaskIntoConstraints = NO;
    [self.summaryContentView addSubview:self.summaryCancelBtn];
    
    [NSLayoutConstraint activateConstraints:@[
        [self.summaryCancelBtn.topAnchor constraintEqualToAnchor:self.termsField.bottomAnchor constant:20],
        [self.summaryCancelBtn.leadingAnchor constraintEqualToAnchor:self.summaryContentView.leadingAnchor constant:16],
        [self.summaryCancelBtn.trailingAnchor constraintEqualToAnchor:self.summaryContentView.trailingAnchor constant:-16],
        [self.summaryCancelBtn.heightAnchor constraintEqualToConstant:55],
        [self.summaryCancelBtn.bottomAnchor constraintEqualToAnchor:self.summaryContentView.bottomAnchor constant:-20] // important for scrolling
    ]];
}

#pragma mark - Owner ScrollView
#pragma mark - Owner ScrollView (Dynamic Cards)
- (void)setupOwnerScrollView {
    self.ownerScrollView = [[UIScrollView alloc] init];
    self.ownerScrollView.translatesAutoresizingMaskIntoConstraints = NO;
    self.ownerScrollView.hidden = YES;
    [self.view addSubview:self.ownerScrollView];
    
    self.ownerContentView = [[UIView alloc] init];
    self.ownerContentView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.ownerScrollView addSubview:self.ownerContentView];
    
    [NSLayoutConstraint activateConstraints:@[
        [self.ownerScrollView.topAnchor constraintEqualToAnchor:self.tabsBar.bottomAnchor constant:10],
        [self.ownerScrollView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.ownerScrollView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.ownerScrollView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor],
        
        [self.ownerContentView.topAnchor constraintEqualToAnchor:self.ownerScrollView.topAnchor],
        [self.ownerContentView.leadingAnchor constraintEqualToAnchor:self.ownerScrollView.leadingAnchor],
        [self.ownerContentView.trailingAnchor constraintEqualToAnchor:self.ownerScrollView.trailingAnchor],
        [self.ownerContentView.bottomAnchor constraintEqualToAnchor:self.ownerScrollView.bottomAnchor],
        [self.ownerContentView.widthAnchor constraintEqualToAnchor:self.ownerScrollView.widthAnchor],
    ]];
    
    NSArray *owners = self.appointmentData[@"owners"]; // Array of dictionaries
    UIView *previousCard = nil;
    
    for (NSDictionary *ownerData in owners) {
        UIView *card = [self createOwnerCardWithData:ownerData];
        [self.ownerContentView addSubview:card];
        
        [NSLayoutConstraint activateConstraints:@[
            [card.leadingAnchor constraintEqualToAnchor:self.ownerContentView.leadingAnchor constant:16],
            [card.trailingAnchor constraintEqualToAnchor:self.ownerContentView.trailingAnchor constant:-16],
            [card.heightAnchor constraintEqualToConstant:120],
        ]];
        
        if (previousCard) {
            [card.topAnchor constraintEqualToAnchor:previousCard.bottomAnchor constant:16].active = YES;
        } else {
            [card.topAnchor constraintEqualToAnchor:self.ownerContentView.topAnchor constant:20].active = YES;
        }
        previousCard = card;
    }
    
    // Cancel button at the bottom
    self.ownerCancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.ownerCancelBtn setTitle:@"Cancel Appointment" forState:UIControlStateNormal];
    self.ownerCancelBtn.backgroundColor = [UIColor systemRedColor];
    self.ownerCancelBtn.layer.cornerRadius = 12;
    [self.ownerCancelBtn addTarget:self action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
    self.ownerCancelBtn.translatesAutoresizingMaskIntoConstraints = NO;
    [self.ownerContentView addSubview:self.ownerCancelBtn];
    
    [NSLayoutConstraint activateConstraints:@[
        [self.ownerCancelBtn.topAnchor constraintEqualToAnchor:previousCard ? previousCard.bottomAnchor : self.ownerContentView.topAnchor constant:20],
        [self.ownerCancelBtn.leadingAnchor constraintEqualToAnchor:self.ownerContentView.leadingAnchor constant:16],
        [self.ownerCancelBtn.trailingAnchor constraintEqualToAnchor:self.ownerContentView.trailingAnchor constant:-16],
        [self.ownerCancelBtn.heightAnchor constraintEqualToConstant:55],
        [self.ownerCancelBtn.bottomAnchor constraintEqualToAnchor:self.ownerContentView.bottomAnchor constant:-20]
    ]];
}

#pragma mark - Helper: Create Owner Card
- (UIView *)createOwnerCardWithData:(NSDictionary *)ownerData {
    UIView *card = [[UIView alloc] init];
    card.backgroundColor = UIColor.whiteColor;
    card.layer.cornerRadius = 12;
    card.layer.borderColor = [UIColor colorWithWhite:0.9 alpha:1].CGColor;
    card.layer.borderWidth = 1;
    card.translatesAutoresizingMaskIntoConstraints = NO;
    
    UILabel *nameLabel = [[UILabel alloc] init];
    nameLabel.text = [NSString stringWithFormat:@"Name: %@", ownerData[@"name"]];
    nameLabel.font = [UIFont boldSystemFontOfSize:16];
    nameLabel.translatesAutoresizingMaskIntoConstraints = NO;
    
    UILabel *typeLabel = [[UILabel alloc] init];
    typeLabel.text = [NSString stringWithFormat:@"Type: %@", ownerData[@"type"]]; // Primary/Joint
    typeLabel.font = [UIFont systemFontOfSize:14];
    typeLabel.textColor = UIColor.darkGrayColor;
    typeLabel.translatesAutoresizingMaskIntoConstraints = NO;
    
    [card addSubview:nameLabel];
    [card addSubview:typeLabel];
    
    [NSLayoutConstraint activateConstraints:@[
        [nameLabel.topAnchor constraintEqualToAnchor:card.topAnchor constant:16],
        [nameLabel.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:16],
        [nameLabel.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-16],
        
        [typeLabel.topAnchor constraintEqualToAnchor:nameLabel.bottomAnchor constant:8],
        [typeLabel.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:16],
        [typeLabel.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-16],
    ]];
    
    return card;
}

#pragma mark - Tab Actions
- (void)showSummary {
    self.summaryScrollView.hidden = NO;
    self.ownerScrollView.hidden = YES;
    self.summaryBtn.backgroundColor = [UIColor colorWithRed:0 green:0.45 blue:0.55 alpha:1];
    self.ownerBtn.backgroundColor = UIColor.lightGrayColor;
}

- (void)showOwnerInfo {
    self.summaryScrollView.hidden = YES;
    self.ownerScrollView.hidden = NO;
    self.summaryBtn.backgroundColor = UIColor.lightGrayColor;
    self.ownerBtn.backgroundColor = [UIColor colorWithRed:0 green:0.45 blue:0.55 alpha:1];
}

#pragma mark - Actions
- (void)backTapped {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)cancelPressed {

    // STEP 1 — Confirmation alert
    UIAlertController *confirmAlert =
    [UIAlertController alertControllerWithTitle:@"Cancel Appointment"
                                        message:@"Are you sure you want to cancel this appointment?"
                                 preferredStyle:UIAlertControllerStyleAlert];

    // NO button — dismiss only
    [confirmAlert addAction:[UIAlertAction actionWithTitle:@"No"
                                                     style:UIAlertActionStyleCancel
                                                   handler:nil]];

    // YES button — go to step 2
    [confirmAlert addAction:[UIAlertAction actionWithTitle:@"Yes"
                                                     style:UIAlertActionStyleDestructive
                                                   handler:^(UIAlertAction * _Nonnull action)
    {
        [self showReasonPopupForCancellation];
    }]];

    [self presentViewController:confirmAlert 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];

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

    // CANCEL button — closes this popup only
    [reasonAlert addAction:[UIAlertAction actionWithTitle:@"Cancel"
                                                    style:UIAlertActionStyleCancel
                                                  handler:nil]];

    // OK button — execute API
    [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";
    }

    [AppointmentAPIClient fetchCancelAppointment:self.appointmentID
                                          reason:remarks
                                      completion:^(NSDictionary *data, NSError *error)
    {
        if (error) {
            NSLog(@"❌ Cancel Error: %@", error.localizedDescription);
            return;
        }

        NSLog(@"✅ Appointment cancelled successfully.");

        // Optional: close screen after cancel success
        dispatch_async(dispatch_get_main_queue(), ^{
            [self dismissViewControllerAnimated:YES completion:nil];
        });
    }];
}

@end
