//  AppointmentDetailsViewController.mm

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

@interface AppointmentDetailsViewController ()

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

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

@property (nonatomic, strong) UIView *statusBanner;
@property (nonatomic, strong) UILabel *statusLabel;
@property (nonatomic, strong) UILabel *reasonLabel;

@property (nonatomic, strong) UIView *summaryCard;
@property (nonatomic, strong) UIView *repCard;
@property (nonatomic, strong) UIView *buttonSection;
@property (nonatomic, strong) UIView *tabsBar;
@property (nonatomic, strong) UIView *summaryContainer;
@property (nonatomic, strong) UIView *ownerInfoContainer;

@property (nonatomic, strong) UIView *loadingOverlay;

@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) UIButton *summaryBtn;
@property (nonatomic, strong) UIButton *ownerBtn;

@end


@implementation AppointmentDetailsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;

    [self setupNavBar];
    [self setupScrollView];
    [self setupStatusBanner];
    [self setupUnitInfoHeader];
    [self setupTabs];
    [self setupContainers];
    [self setupSummaryCard];
    [self setupButtonSection];
    [self setupLoadingOverlay];

    [self applyAppointmentDataToUI];
}

#pragma mark - Navigation Bar

- (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.titleLabel = [[UILabel alloc] init];
    self.titleLabel.text = @"Appointment Details";
    self.titleLabel.textColor = UIColor.whiteColor;
    self.titleLabel.font = [UIFont boldSystemFontOfSize:17];
    self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.navBar addSubview:self.titleLabel];

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

    [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.contentView addSubview:header];

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

    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.statusBanner.topAnchor constant:20],
        [header.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],
        [header.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-16],

        [unitText.topAnchor constraintEqualToAnchor:header.topAnchor],
        [unitText.leadingAnchor constraintEqualToAnchor:header.leadingAnchor],

        [unitNumber.topAnchor constraintEqualToAnchor:unitText.bottomAnchor constant:4],
        [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 - ScrollView

- (void)setupScrollView {
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.translatesAutoresizingMaskIntoConstraints = NO;

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

    [self.view addSubview:self.scrollView];
    [self.scrollView addSubview:self.contentView];

    [NSLayoutConstraint activateConstraints:@[
        [self.scrollView.topAnchor constraintEqualToAnchor:self.navBar.bottomAnchor],
        [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 - Status Banner

- (void)setupStatusBanner {
    self.statusBanner = [[UIView alloc] init];
    self.statusBanner.layer.cornerRadius = 12;
    self.statusBanner.translatesAutoresizingMaskIntoConstraints = NO;
    [self.contentView addSubview:self.statusBanner];

    self.statusLabel = [[UILabel alloc] init];
    self.statusLabel.font = [UIFont boldSystemFontOfSize:18];
    self.statusLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.statusBanner addSubview:self.statusLabel];

    self.reasonLabel = [[UILabel alloc] init];
    self.reasonLabel.font = [UIFont systemFontOfSize:14];
    self.reasonLabel.numberOfLines = 0;
    self.reasonLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.statusBanner addSubview:self.reasonLabel];

    [NSLayoutConstraint activateConstraints:@[
        [self.statusBanner.topAnchor constraintEqualToAnchor:self.contentView.topAnchor constant:20],
        [self.statusBanner.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],
        [self.statusBanner.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-16],

        [self.statusLabel.topAnchor constraintEqualToAnchor:self.statusBanner.topAnchor constant:16],
        [self.statusLabel.leadingAnchor constraintEqualToAnchor:self.statusBanner.leadingAnchor constant:16],

        [self.reasonLabel.topAnchor constraintEqualToAnchor:self.statusLabel.bottomAnchor constant:8],
        [self.reasonLabel.leadingAnchor constraintEqualToAnchor:self.statusBanner.leadingAnchor constant:16],
        [self.reasonLabel.trailingAnchor constraintEqualToAnchor:self.statusBanner.trailingAnchor constant:-16],
        [self.reasonLabel.bottomAnchor constraintEqualToAnchor:self.statusBanner.bottomAnchor constant:-16],
    ]];
}

#pragma mark - Appointment Summary Card

- (void)setupSummaryCard {
    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.summaryContainer addSubview:self.summaryCard];

    UILabel *title = [[UILabel alloc] init];
    title.text = @"Appointment Summary";
    title.font = [UIFont boldSystemFontOfSize:16];
    title.translatesAutoresizingMaskIntoConstraints = NO;
    [self.summaryContainer addSubview:title];

    [NSLayoutConstraint activateConstraints:@[
        [self.summaryCard.topAnchor constraintEqualToAnchor:self.tabsBar.bottomAnchor constant:20],
        [self.summaryCard.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],
        [self.summaryCard.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-16],

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

    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[@"type"]);
    self.dateField = makeField(@"Date :", self.appointmentData[@"date"]);
    self.slotField = makeField(@"Time Slot :", self.appointmentData[@"time"]);
    self.locField = makeField(@"Location :", self.appointmentData[@"location"]);
    self.termsField = makeField(@"Terms &\n Conditions :", @"View Here");
  
    UIButton *calendarBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    calendarBtn.layer.cornerRadius = 12;
    calendarBtn.layer.borderWidth = 1;
    calendarBtn.layer.borderColor = [UIColor colorWithWhite:0.8 alpha:1].CGColor;
    calendarBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [calendarBtn setImage:[UIImage systemImageNamed:@"calendar"] forState:UIControlStateNormal];
    [calendarBtn setTitle:@"  Add To Calendar" forState:UIControlStateNormal];
    [calendarBtn setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
    calendarBtn.translatesAutoresizingMaskIntoConstraints = NO;
    [self.summaryContainer addSubview:calendarBtn];
  
    [NSLayoutConstraint activateConstraints:@[
        [self.typeField.topAnchor constraintEqualToAnchor:title.bottomAnchor constant:10],
        [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:10],
        [self.dateField.leadingAnchor constraintEqualToAnchor:self.typeField.leadingAnchor],
        [self.dateField.trailingAnchor constraintEqualToAnchor:self.typeField.trailingAnchor],

        [self.slotField.topAnchor constraintEqualToAnchor:self.dateField.bottomAnchor constant:10],
        [self.slotField.leadingAnchor constraintEqualToAnchor:self.typeField.leadingAnchor],
        [self.slotField.trailingAnchor constraintEqualToAnchor:self.typeField.trailingAnchor],

        [self.locField.topAnchor constraintEqualToAnchor:self.slotField.bottomAnchor constant:10],
        [self.locField.leadingAnchor constraintEqualToAnchor:self.typeField.leadingAnchor],
        [self.locField.trailingAnchor constraintEqualToAnchor:self.typeField.trailingAnchor],
        
        [self.termsField.topAnchor constraintEqualToAnchor:self.locField.bottomAnchor constant:10],
        [self.termsField.leadingAnchor constraintEqualToAnchor:self.typeField.leadingAnchor],
        [self.termsField.trailingAnchor constraintEqualToAnchor:self.typeField.trailingAnchor],
        
        [calendarBtn.topAnchor constraintEqualToAnchor:self.termsField.bottomAnchor constant:10],
        [calendarBtn.leadingAnchor constraintEqualToAnchor:self.typeField.leadingAnchor],
        [calendarBtn.trailingAnchor constraintEqualToAnchor:self.typeField.trailingAnchor],
        [calendarBtn.heightAnchor constraintEqualToConstant:44],

        [self.summaryCard.bottomAnchor constraintEqualToAnchor:calendarBtn.bottomAnchor constant:16]
    ]];
}

#pragma mark - Summary Tabs
- (void)setupTabs {
    UIView *tabs = [[UIView alloc] init];
    tabs.translatesAutoresizingMaskIntoConstraints = NO;
    [self.contentView addSubview:tabs];

    self.summaryBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.summaryBtn.backgroundColor = [UIColor colorWithRed:0 green:0.45 blue:0.55 alpha:1];
    [self.summaryBtn setTitle:@"Summary" forState:UIControlStateNormal];
    self.summaryBtn.layer.cornerRadius = 20;
    self.summaryBtn.translatesAutoresizingMaskIntoConstraints = NO;

    self.ownerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.ownerBtn.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];
    self.ownerBtn.layer.cornerRadius = 20;
    [self.ownerBtn setTitle:@"Owner Info" forState:UIControlStateNormal];
    self.ownerBtn.translatesAutoresizingMaskIntoConstraints = NO;

    [tabs addSubview:self.summaryBtn];
    [tabs addSubview:self.ownerBtn];
    [self.summaryBtn addTarget:self action:@selector(showSummary) forControlEvents:UIControlEventTouchUpInside];
    [self.ownerBtn addTarget:self action:@selector(showOwnerInfo) forControlEvents:UIControlEventTouchUpInside];

    [NSLayoutConstraint activateConstraints:@[
        [tabs.topAnchor constraintEqualToAnchor:self.unitInfoHeader.bottomAnchor constant:20],
        [tabs.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],
        [tabs.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-16],

        [self.summaryBtn.topAnchor constraintEqualToAnchor:tabs.topAnchor],
        [self.summaryBtn.leadingAnchor constraintEqualToAnchor:tabs.leadingAnchor],
        [self.summaryBtn.widthAnchor constraintEqualToAnchor:tabs.widthAnchor multiplier:0.5],
        [self.summaryBtn.heightAnchor constraintEqualToConstant:40],

        [self.ownerBtn.topAnchor constraintEqualToAnchor:tabs.topAnchor],
        [self.ownerBtn.trailingAnchor constraintEqualToAnchor:tabs.trailingAnchor],
        [self.ownerBtn.widthAnchor constraintEqualToAnchor:tabs.widthAnchor multiplier:0.5],
        [self.ownerBtn.heightAnchor constraintEqualToConstant:40],

        [tabs.bottomAnchor constraintEqualToAnchor:self.summaryBtn.bottomAnchor]
    ]];

    self.tabsBar = tabs;
}

- (void)showSummary {
    self.summaryContainer.hidden = NO;
    self.ownerInfoContainer.hidden = YES;

    // Update tab colors
    self.summaryBtn.backgroundColor = [UIColor colorWithRed:0 green:0.45 blue:0.55 alpha:1];
    self.ownerBtn.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];
}

- (void)showOwnerInfo {
    self.summaryContainer.hidden = YES;
    self.ownerInfoContainer.hidden = NO;

    // Update tab colors
    self.summaryBtn.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];
    self.ownerBtn.backgroundColor = [UIColor colorWithRed:0 green:0.45 blue:0.55 alpha:1];
}

#pragma mark - Containers
- (void)setupContainers {
    self.summaryContainer = [[UIView alloc] init];
    self.summaryContainer.translatesAutoresizingMaskIntoConstraints = NO;
    [self.contentView addSubview:self.summaryContainer];

    self.ownerInfoContainer = [[UIView alloc] init];
    self.ownerInfoContainer.translatesAutoresizingMaskIntoConstraints = NO;
    self.ownerInfoContainer.hidden = YES;   // Start hidden
    [self.contentView addSubview:self.ownerInfoContainer];

    [NSLayoutConstraint activateConstraints:@[
        [self.summaryContainer.topAnchor constraintEqualToAnchor:self.tabsBar.bottomAnchor constant:20],
        [self.summaryContainer.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor],
        [self.summaryContainer.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor],

        [self.ownerInfoContainer.topAnchor constraintEqualToAnchor:self.tabsBar.bottomAnchor constant:20],
        [self.ownerInfoContainer.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor],
        [self.ownerInfoContainer.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor],
    ]];
}

#pragma mark - Representative Card

- (void)setupRepresentativeCard {
    self.repCard = [[UIView alloc] init];
    self.repCard.backgroundColor = UIColor.whiteColor;
    self.repCard.layer.cornerRadius = 12;
    self.repCard.layer.borderColor = [UIColor colorWithWhite:0.9 alpha:1].CGColor;
    self.repCard.layer.borderWidth = 1;
    self.repCard.translatesAutoresizingMaskIntoConstraints = NO;
    [self.ownerInfoContainer addSubview:self.repCard];

    UILabel *title = [[UILabel alloc] init];
    title.text = @"Representative";
    title.font = [UIFont boldSystemFontOfSize:16];
    title.translatesAutoresizingMaskIntoConstraints = NO;
    [self.ownerInfoContainer addSubview:title];

    [NSLayoutConstraint activateConstraints:@[
        [self.repCard.topAnchor constraintEqualToAnchor:self.ownerInfoContainer.topAnchor constant:0],
        [self.repCard.leadingAnchor constraintEqualToAnchor:self.ownerInfoContainer.leadingAnchor constant:16],
        [self.repCard.trailingAnchor constraintEqualToAnchor:self.ownerInfoContainer.trailingAnchor constant:-16],
        [self.repCard.bottomAnchor constraintEqualToAnchor:self.ownerInfoContainer.bottomAnchor constant:-20],

        [title.topAnchor constraintEqualToAnchor:self.repCard.topAnchor constant:16],
        [title.leadingAnchor constraintEqualToAnchor:self.repCard.leadingAnchor constant:16],
    ]];
}

#pragma mark - Buttons Section
- (UIButton *)buildCancelButton {
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelBtn.backgroundColor = [UIColor colorWithRed:1.0 green:0.45 blue:0.45 alpha:1];
    cancelBtn.layer.cornerRadius = 12;
    [cancelBtn setTitle:@"Cancel Appointment" forState:UIControlStateNormal];
    cancelBtn.titleLabel.font = [UIFont boldSystemFontOfSize:17];
    [cancelBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    cancelBtn.translatesAutoresizingMaskIntoConstraints = NO;
    [cancelBtn addTarget:self
                  action:@selector(cancelPressed)
        forControlEvents:UIControlEventTouchUpInside];
    return cancelBtn;
}

- (void)setupButtonSection {
    self.buttonSection = [[UIView alloc] init];
    self.buttonSection.translatesAutoresizingMaskIntoConstraints = NO;
    [self.summaryContainer addSubview:self.buttonSection];

    UIButton *cancelBtn = [self buildCancelButton];
    [self.buttonSection addSubview:cancelBtn];

    [NSLayoutConstraint activateConstraints:@[
        [self.buttonSection.topAnchor constraintEqualToAnchor:self.summaryCard.bottomAnchor constant:30],
        [self.buttonSection.leadingAnchor constraintEqualToAnchor:self.summaryContainer.leadingAnchor],
        [self.buttonSection.trailingAnchor constraintEqualToAnchor:self.summaryContainer.trailingAnchor],
        [self.buttonSection.bottomAnchor constraintEqualToAnchor:self.summaryContainer.bottomAnchor constant:-50],

        [cancelBtn.topAnchor constraintEqualToAnchor:self.buttonSection.topAnchor],
        [cancelBtn.leadingAnchor constraintEqualToAnchor:self.summaryContainer.leadingAnchor constant:16],
        [cancelBtn.trailingAnchor constraintEqualToAnchor:self.summaryContainer.trailingAnchor constant:-16],
        [cancelBtn.heightAnchor constraintEqualToConstant:55],
    ]];
}

- (void)setupOwnerInfoButtons {
    UIView *ownerButtonSection = [[UIView alloc] init];
    ownerButtonSection.translatesAutoresizingMaskIntoConstraints = NO;
    [self.ownerInfoContainer addSubview:ownerButtonSection];

    UIButton *cancelBtn2 = [self buildCancelButton];
    [ownerButtonSection addSubview:cancelBtn2];

    [NSLayoutConstraint activateConstraints:@[
        [ownerButtonSection.topAnchor constraintEqualToAnchor:self.repCard.bottomAnchor constant:30],
        [ownerButtonSection.leadingAnchor constraintEqualToAnchor:self.ownerInfoContainer.leadingAnchor],
        [ownerButtonSection.trailingAnchor constraintEqualToAnchor:self.ownerInfoContainer.trailingAnchor],
        [ownerButtonSection.bottomAnchor constraintEqualToAnchor:self.ownerInfoContainer.bottomAnchor constant:-50],

        [cancelBtn2.topAnchor constraintEqualToAnchor:ownerButtonSection.topAnchor],
        [cancelBtn2.leadingAnchor constraintEqualToAnchor:self.ownerInfoContainer.leadingAnchor constant:16],
        [cancelBtn2.trailingAnchor constraintEqualToAnchor:self.ownerInfoContainer.trailingAnchor constant:-16],
        [cancelBtn2.heightAnchor constraintEqualToConstant:55]
    ]];
}

#pragma mark - Loading Overlay

- (void)setupLoadingOverlay {
    self.loadingOverlay = [[UIView alloc] initWithFrame:self.view.bounds];
    self.loadingOverlay.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.4];
    self.loadingOverlay.hidden = YES;

    UIActivityIndicatorView *spin = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleLarge];
    spin.color = UIColor.whiteColor;
    spin.center = self.loadingOverlay.center;

    [self.loadingOverlay addSubview:spin];
    [self.view addSubview:self.loadingOverlay];

    [spin startAnimating];
}

#pragma mark - Apply Data

- (void)applyAppointmentDataToUI {
    self.loadingOverlay.hidden = YES;

    NSString *status = self.appointmentData[@"appointment_status"];

    if ([status isEqualToString:@"Pending"]) {
        self.statusBanner.backgroundColor = [UIColor colorWithRed:0.95 green:0.8 blue:0.2 alpha:1];
    } else if ([status isEqualToString:@"Approved"]) {
        self.statusBanner.backgroundColor = [UIColor colorWithRed:0 green:0.7 blue:0.3 alpha:1];
    } else if ([status isEqualToString:@"Rejected"]) {
        self.statusBanner.backgroundColor = [UIColor colorWithRed:0.9 green:0.2 blue:0.2 alpha:1];
    } else {
        self.statusBanner.backgroundColor = [UIColor lightGrayColor];
    }

    self.statusLabel.text = status;
    self.reasonLabel.text = self.appointmentData[@"rejected_reason"];
  
    self.typeField.text = [NSString stringWithFormat:@"Type : %@", self.appointmentData[@"appointment_type"]];
    self.dateField.text = [NSString stringWithFormat:@"Date : %@", self.appointmentData[@"appointment_date"]];
    self.slotField.text = [NSString stringWithFormat:@"Time Slot : %@", self.appointmentData[@"appointment_time"]];
    self.locField.text = [NSString stringWithFormat:@"Location : %@", self.appointmentData[@"location"]];
}

#pragma mark - Actions

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

#pragma mark - cancel button
- (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

