// AppointmentDetailsViewController.mm

#import "AppointmentDetailsViewController.h"
#import "APIClient.h"
#import <WebKit/WebKit.h>
#import <EventKit/EventKit.h>

@interface AppointmentDetailsViewController () <UIScrollViewDelegate>

// 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;
@property (nonatomic, strong) NSString *floorPlanImage;

@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 *remarksField;
@property (nonatomic, strong) UILabel *termsField;
@property (nonatomic, strong) UIStackView *remarksRow;

@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 requestGeneralInfo];
    [self setupNavBar];
    [self setupUnitInfoHeader];
    [self setupTabsBar];
    [self setupSummaryScrollView];
    [self setupOwnerScrollView];
    
    [self showSummary];
  
    NSLog(@"📦 Received Appointment Data: %@", self.appointmentData);
    NSString *text = [NSString stringWithFormat:@"%@", self.appointmentData];
    NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    NSString *filePath = [docsPath stringByAppendingPathComponent:@"appointData.txt"];

    // Convert issueData to a readable string
    NSString *plainText = [NSString stringWithFormat:@"%@", self.appointmentData];

    // Write as plain UTF-8 text
    [plainText writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];

    // Log the path so you can find it
    NSLog(@"📁 appointData saved as plain text to: %@", filePath);
}

#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:UIButtonTypeSystem];
    self.backButton.tag = 1;
    self.backButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.backButton setImage:[UIImage systemImageNamed:@"chevron.left"] forState:UIControlStateNormal];
    self.backButton.tintColor = UIColor.whiteColor;
    [self.backButton addTarget:self action:@selector(backTapped) forControlEvents:UIControlEventTouchUpInside];
    [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_layout_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.tag = 101;
    floorPlan.layer.cornerRadius = 8;
    floorPlan.layer.borderColor = [UIColor colorWithWhite:0.85 alpha:1].CGColor;
    floorPlan.layer.borderWidth = 1;
    floorPlan.clipsToBounds = YES;
    floorPlan.translatesAutoresizingMaskIntoConstraints = NO;
    floorPlan.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleFloorPlanTap:)];
    [floorPlan addGestureRecognizer:tap];
    [header addSubview:floorPlan];

    [NSLayoutConstraint activateConstraints:@[
        [header.topAnchor constraintEqualToAnchor:self.navBar.bottomAnchor constant:30],
        [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:10],
        [unitNumber.leadingAnchor constraintEqualToAnchor:header.leadingAnchor],

        [unitType.topAnchor constraintEqualToAnchor:unitNumber.bottomAnchor constant:10],
        [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:40]
    ]];

    self.unitInfoHeader = header;
}

- (void)loadImage:(NSString *)urlString into:(UIImageView *)imageView {
    if (!urlString || (id)urlString == [NSNull null]) return;

    NSURL *url = [NSURL URLWithString:urlString];
    if (!url) return;

    NSURLSessionDataTask *task =
    [[NSURLSession sharedSession] dataTaskWithURL:url
                                completionHandler:^(NSData *data, NSURLResponse *res, NSError *err) {
        if (err || !data) return;

        UIImage *img = [UIImage imageWithData:data];
        if (!img) return;

        dispatch_async(dispatch_get_main_queue(), ^{
            imageView.image = img;
        });
    }];

    [task resume];
}

- (void)handleFloorPlanTap:(UITapGestureRecognizer *)sender {
    UIImageView *tappedImageView = (UIImageView *)sender.view;
    if (!tappedImageView.image) return;

    UIView *overlay = [[UIView alloc] initWithFrame:self.view.bounds];
    overlay.backgroundColor = [UIColor colorWithWhite:0 alpha:0.95];
    overlay.alpha = 0;
    overlay.tag = 900;
    overlay.userInteractionEnabled = YES;
    [self.view addSubview:overlay];

    UIImageView *fullImageView = [[UIImageView alloc] initWithFrame:overlay.bounds];
    fullImageView.contentMode = UIViewContentModeScaleAspectFit;
    fullImageView.image = tappedImageView.image;
    fullImageView.userInteractionEnabled = YES;
    [overlay addSubview:fullImageView];
  
    fullImageView.translatesAutoresizingMaskIntoConstraints = NO;
    [NSLayoutConstraint activateConstraints:@[
        [fullImageView.topAnchor constraintEqualToAnchor:overlay.topAnchor],
        [fullImageView.leadingAnchor constraintEqualToAnchor:overlay.leadingAnchor],
        [fullImageView.trailingAnchor constraintEqualToAnchor:overlay.trailingAnchor],
        [fullImageView.bottomAnchor constraintEqualToAnchor:overlay.bottomAnchor]
    ]];
  
    UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:overlay.bounds];
    scroll.minimumZoomScale = 1.0;
    scroll.maximumZoomScale = 3.0;
    scroll.delegate = self; // implement viewForZoomingInScrollView
    [overlay addSubview:scroll];
    [scroll addSubview:fullImageView];

    UITapGestureRecognizer *dismissTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeFullImage)];
    [overlay addGestureRecognizer:dismissTap];

    [UIView animateWithDuration:0.25 animations:^{
        overlay.alpha = 1;
    }];
}

- (void)closeFullImage {
    UIView *overlay = [self.view viewWithTag:900];
    if (!overlay) return;

    [UIView animateWithDuration:0.25 animations:^{
        overlay.alpha = 0;
    } completion:^(BOOL finished) {
        [overlay removeFromSuperview];
    }];
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return scrollView.subviews.firstObject;
}

#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 {
    // ---------- Scroll View ----------
    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];

    // Stack inside card
    UIStackView *stack = [[UIStackView alloc] init];
    stack.axis = UILayoutConstraintAxisVertical;
    stack.alignment = UIStackViewAlignmentFill;
    stack.spacing = 16;
    stack.translatesAutoresizingMaskIntoConstraints = NO;
    [self.summaryCard addSubview:stack];

    // ---------- Title ----------
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = @"Appointment Info";
    titleLabel.font = [UIFont boldSystemFontOfSize:16];
    [stack addArrangedSubview:titleLabel];

    // ---------- Field Values ----------
    UILabel *typeValue = [[UILabel alloc] init];
    typeValue.text = self.appointmentData[@"appointment_type"];
    typeValue.font = [UIFont systemFontOfSize:15];

    UILabel *dateValue = [[UILabel alloc] init];
    dateValue.text = self.appointmentData[@"start_date"];
    dateValue.font = [UIFont systemFontOfSize:15];

    UILabel *slotValue = [[UILabel alloc] init];
    slotValue.text = self.appointmentData[@"start_time"];
    slotValue.font = [UIFont systemFontOfSize:15];

    UILabel *locValue = [[UILabel alloc] init];
    locValue.text = @"Ara Residence, 71800 Nilai,\nNegeri Sembilan";
    locValue.font = [UIFont systemFontOfSize:15];
    locValue.numberOfLines = 0;

    // Add rows (left title, right value)
    [stack addArrangedSubview:[self makeRowWithTitle:@"Type" value:typeValue]];
    [stack addArrangedSubview:[self makeRowWithTitle:@"Date" value:dateValue]];
    [stack addArrangedSubview:[self makeRowWithTitle:@"Time Slot" value:slotValue]];
    [stack addArrangedSubview:[self makeRowWithTitle:@"Location" value:locValue]];

    // ---------- Remarks (Collapsible) ----------
    self.remarksField = [[UILabel alloc] init];
    self.remarksField.font = [UIFont systemFontOfSize:15];
    self.remarksField.numberOfLines = 0;

    self.remarksRow = [self makeRowWithTitle:@"Remarks" value:self.remarksField];
    self.remarksRow.hidden = YES;  // default
    [stack addArrangedSubview:self.remarksRow];

    // ---------- Terms & Conditions ----------
    UILabel *termsLabel = [[UILabel alloc] init];
    termsLabel.text = @"Terms & Conditions :";
    termsLabel.font = [UIFont systemFontOfSize:15];
    termsLabel.numberOfLines = 2;
    [termsLabel.widthAnchor constraintEqualToConstant:120].active = YES;

    UIButton *viewButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [viewButton setTitle:@"View here" forState:UIControlStateNormal];
    viewButton.titleLabel.font = [UIFont systemFontOfSize:15 weight:UIFontWeightSemibold];
    [viewButton addTarget:self action:@selector(openTermsDrawer) forControlEvents:UIControlEventTouchUpInside];

    UIStackView *termsRow = [[UIStackView alloc] initWithArrangedSubviews:@[termsLabel, viewButton]];
    termsRow.axis = UILayoutConstraintAxisHorizontal;
    termsRow.spacing = 8;

    [stack addArrangedSubview:termsRow];

    // ---------- Calendar Button ----------
    UIButton *calendarBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [calendarBtn setTitle:@"Add To Calendar" forState:UIControlStateNormal];
    [calendarBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    calendarBtn.backgroundColor = [UIColor systemBlueColor];
    calendarBtn.layer.cornerRadius = 16;
    calendarBtn.titleLabel.font = [UIFont systemFontOfSize:15 weight:UIFontWeightSemibold];
    [calendarBtn.heightAnchor constraintEqualToConstant:44].active = YES;
    [calendarBtn addTarget:self action:@selector(addToCalendarPressed) forControlEvents:UIControlEventTouchUpInside];

    [stack addArrangedSubview:calendarBtn];

    // ---------- Card Layout Constraints ----------
    [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],

        [stack.topAnchor constraintEqualToAnchor:self.summaryCard.topAnchor constant:16],
        [stack.leadingAnchor constraintEqualToAnchor:self.summaryCard.leadingAnchor constant:16],
        [stack.trailingAnchor constraintEqualToAnchor:self.summaryCard.trailingAnchor constant:-16],
        [stack.bottomAnchor constraintEqualToAnchor:self.summaryCard.bottomAnchor constant:-16],
    ]];

    // ---------- Cancel Appointment 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];

    // ---------- Status Logic (Hide + Expand Remarks) ----------
    NSString *status = self.appointmentData[@"status"];
    if ([status.lowercaseString isEqualToString:@"cancelled"]) {
        self.summaryCancelBtn.hidden = YES;

        self.remarksField.text = self.appointmentData[@"reason"];
        self.remarksRow.hidden = NO;
    }

    // ---------- Cancel Button Constraints ----------
    [NSLayoutConstraint activateConstraints:@[
        [self.summaryCancelBtn.topAnchor constraintEqualToAnchor:self.summaryCard.bottomAnchor constant:40],
        [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]
    ]];
}

- (UIStackView *)makeRowWithTitle:(NSString *)title value:(UIView *)valueView {
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = [NSString stringWithFormat:@"%@ :", title];
    titleLabel.font = [UIFont systemFontOfSize:15];
    titleLabel.textColor = UIColor.darkGrayColor;
    titleLabel.numberOfLines = 1;
    [titleLabel.widthAnchor constraintEqualToConstant:120].active = YES;

    UIStackView *row = [[UIStackView alloc] initWithArrangedSubviews:@[titleLabel, valueView]];
    row.axis = UILayoutConstraintAxisHorizontal;
    row.spacing = 8;
    row.alignment = UIStackViewAlignmentTop;

    return row;
}

- (void)openTermsDrawer {
    NSDictionary *tnc = self.appointmentData[@"appointment_tnc"];
    NSString *htmlString = tnc[@"content"];
    if (!htmlString || ![htmlString isKindOfClass:[NSString class]]) {
        return;
    }

    [self showBottomDrawerWithHTML:htmlString];
}

- (void)showBottomDrawerWithHTML:(NSString *)html {
    UIWindow *window = UIApplication.sharedApplication.keyWindow;

    // Dimmed background
    UIView *dimView = [[UIView alloc] initWithFrame:window.bounds];
    dimView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
    dimView.alpha = 0;
    dimView.tag = 9991;

    UITapGestureRecognizer *dismissTap =
        [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeBottomDrawer)];
    [dimView addGestureRecognizer:dismissTap];
    [window addSubview:dimView];

    // Drawer container
    CGFloat height = window.frame.size.height * 0.80;

    UIView *drawer = [[UIView alloc] initWithFrame:CGRectMake(0,
        window.frame.size.height,
        window.frame.size.width,
        height)];
    drawer.backgroundColor = UIColor.whiteColor;
    drawer.layer.cornerRadius = 16;
    drawer.clipsToBounds = YES;
    drawer.tag = 9992;
    [window addSubview:drawer];

    // Header label
    UILabel *header = [[UILabel alloc] initWithFrame:CGRectMake(16, 16, drawer.frame.size.width - 32, 28)];
    header.text = @"Terms & Conditions";
    header.font = [UIFont boldSystemFontOfSize:18];
    [drawer addSubview:header];

    // Close button
    UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    closeBtn.frame = CGRectMake(drawer.frame.size.width - 50, 12, 40, 34);
    [closeBtn setTitle:@"✕" forState:UIControlStateNormal];
    closeBtn.titleLabel.font = [UIFont boldSystemFontOfSize:22];
    [closeBtn addTarget:self action:@selector(closeBottomDrawer) forControlEvents:UIControlEventTouchUpInside];
    [drawer addSubview:closeBtn];

    // WebView
    WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 60, drawer.frame.size.width, height - 60)];
    NSString *styledHTML = [NSString stringWithFormat:
        @"<html>"
        "<head>"
        "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0\">"
        "<style>"
        "body { font-size: 14px; font-family: -apple-system; line-height: 1.5; padding: 12px; background-color: #F9F9F9; }"
        "p { margin-bottom: 12px; }"
        "</style>"
        "</head>"
        "<body>%@</body>"
        "</html>",
        html
    ];
    [webView loadHTMLString:styledHTML baseURL:nil];
    [drawer addSubview:webView];

    // Animate up
    [UIView animateWithDuration:0.3 animations:^{
        dimView.alpha = 1;
        drawer.frame = CGRectMake(0,
            window.frame.size.height - height,
            window.frame.size.width,
            height);
    }];
}

- (void)closeBottomDrawer {
    UIWindow *window = UIApplication.sharedApplication.keyWindow;

    UIView *dimView = [window viewWithTag:9991];
    UIView *drawer = [window viewWithTag:9992];

    if (!drawer || !dimView) return;

    [UIView animateWithDuration:0.3 animations:^{
        dimView.alpha = 0;
        drawer.frame = CGRectMake(0,
            window.frame.size.height,
            drawer.frame.size.width,
            drawer.frame.size.height);
    } completion:^(BOOL finished) {
        [drawer removeFromSuperview];
        [dimView removeFromSuperview];
    }];
}

- (void)addToCalendarPressed {
    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[@"status"]];
                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[@"start_date"],
                                         self.appointmentData[@"start_time"]];
                NSString *endString = [NSString stringWithFormat:@"%@ %@",
                                       self.appointmentData[@"end_date"],
                                       self.appointmentData[@"end_time"]];
                
                event.startDate = [formatter dateFromString:startString];
                event.endDate = [formatter dateFromString:endString];
                
                // 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];
            });
        }
    }];
}


#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],
    ]];
    
      UIView *previous = nil;

      NSArray *primaryArray = self.appointmentData[@"primary_buyer"];
      NSDictionary *primaryOwner = nil;
      if ([primaryArray isKindOfClass:[NSArray class]] && primaryArray.count > 0) {
          primaryOwner = primaryArray[0]; // ✅ take first element
      }
      NSArray *jointOwners = self.appointmentData[@"joint_buyer"];

      // ---------------------------
      //  PRIMARY OWNER CARD
      // ---------------------------
      if (primaryOwner) {
          UIView *primaryCard = [self createOwnerCard:@"Primary Owner"
                                                       owner:primaryOwner];

          [self.ownerContentView addSubview:primaryCard];

          [NSLayoutConstraint activateConstraints:@[
              [primaryCard.topAnchor constraintEqualToAnchor:self.ownerContentView.topAnchor constant:10],
              [primaryCard.leadingAnchor constraintEqualToAnchor:self.ownerContentView.leadingAnchor constant:20],
              [primaryCard.trailingAnchor constraintEqualToAnchor:self.ownerContentView.trailingAnchor constant:-20],
          ]];

          previous = primaryCard;
      }

      // ---------------------------
      //  JOINT OWNERS COMBINED CARD
      // ---------------------------
      if (jointOwners.count > 0) {
          UIView *jointCard = [self createJointOwnersCard:jointOwners];
          [self.ownerContentView addSubview:jointCard];

          [NSLayoutConstraint activateConstraints:@[
              [jointCard.topAnchor constraintEqualToAnchor:previous.bottomAnchor constant:20],
              [jointCard.leadingAnchor constraintEqualToAnchor:self.ownerContentView.leadingAnchor constant:20],
              [jointCard.trailingAnchor constraintEqualToAnchor:self.ownerContentView.trailingAnchor constant:-20],
          ]];

          previous = jointCard;
      }
  
      // ---------- Cancel Button ----------
      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];
  
      NSString *status = self.appointmentData[@"status"];
      if ([status.lowercaseString isEqualToString:@"cancelled"]) {
          self.ownerCancelBtn.hidden = YES;
      }
      
      [NSLayoutConstraint activateConstraints:@[
          [self.ownerCancelBtn.topAnchor constraintEqualToAnchor:previous.bottomAnchor constant:40],
          [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]
      ]];
  }

// Updated createOwnerCardWithData
- (UIView *)createOwnerCard:(NSString *)title owner:(NSDictionary *)owner {
  UIView *card = [[UIView alloc] init];
    card.translatesAutoresizingMaskIntoConstraints = NO;
    card.backgroundColor = UIColor.whiteColor;
    card.layer.cornerRadius = 10;
    card.layer.borderColor = [UIColor blackColor].CGColor; // card outline
    card.layer.borderWidth = 1;
    card.layer.shadowColor = [UIColor colorWithWhite:0 alpha:0.1].CGColor;
    card.layer.shadowOpacity = 0.2;
    card.layer.shadowOffset = CGSizeMake(0, 2);

     UILabel *header = [[UILabel alloc] init];
     header.text = title;
     header.font = [UIFont boldSystemFontOfSize:16];
     header.translatesAutoresizingMaskIntoConstraints = NO;
     [card addSubview:header];

     UILabel *name = [self makeFieldLabel:[NSString stringWithFormat:@"Name: %@", owner[@"name"]]];
     UILabel *email = [self makeFieldLabel:[NSString stringWithFormat:@"Email: %@", owner[@"email"]]];
     UILabel *contact = [self makeFieldLabel:[NSString stringWithFormat:@"Contact: %@", owner[@"contact"]]];

     [card addSubview:name];
     [card addSubview:email];
     [card addSubview:contact];

     [NSLayoutConstraint activateConstraints:@[
         [header.topAnchor constraintEqualToAnchor:card.topAnchor constant:16],
         [header.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:16],
         [header.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-16],

         [name.topAnchor constraintEqualToAnchor:header.bottomAnchor constant:14],
         [name.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:16],

         [email.topAnchor constraintEqualToAnchor:name.bottomAnchor constant:6],
         [email.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:16],

         [contact.topAnchor constraintEqualToAnchor:email.bottomAnchor constant:6],
         [contact.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:16],

         [contact.bottomAnchor constraintEqualToAnchor:card.bottomAnchor constant:-16],
     ]];

     return card;
 }

- (UIView *)createJointOwnersCard:(NSArray *)owners {
    UIView *card = [[UIView alloc] init];
    card.translatesAutoresizingMaskIntoConstraints = NO;
    card.backgroundColor = UIColor.whiteColor;
    card.layer.cornerRadius = 10;
    card.layer.borderColor = [UIColor blackColor].CGColor; // card outline
    card.layer.borderWidth = 1;
    card.layer.shadowColor = [UIColor colorWithWhite:0 alpha:0.1].CGColor;
    card.layer.shadowOpacity = 0.2;
    card.layer.shadowOffset = CGSizeMake(0, 2);

    UILabel *header = [[UILabel alloc] init];
    header.text = @"Joint Owners";
    header.font = [UIFont boldSystemFontOfSize:16];
    header.translatesAutoresizingMaskIntoConstraints = NO;
    [card addSubview:header];

    UIView *previous = header;

    [NSLayoutConstraint activateConstraints:@[
        [header.topAnchor constraintEqualToAnchor:card.topAnchor constant:16],
        [header.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:16],
    ]];

    for (int i = 0; i < owners.count; i++) {
        NSDictionary *owner = owners[i];

        // Container for each owner
        UIView *ownerContainer = [[UIView alloc] init];
        ownerContainer.translatesAutoresizingMaskIntoConstraints = NO;
        [card addSubview:ownerContainer];

        UILabel *name = [self makeFieldLabel:[NSString stringWithFormat:@"Name: %@", owner[@"name"] ?: @""]];
        UILabel *email = [self makeFieldLabel:[NSString stringWithFormat:@"Email: %@", owner[@"email"] ?: @""]];
        UILabel *contact = [self makeFieldLabel:[NSString stringWithFormat:@"Contact: %@", owner[@"contact"] ?: @""]];

        [ownerContainer addSubview:name];
        [ownerContainer addSubview:email];
        [ownerContainer addSubview:contact];

        // Layout labels inside ownerContainer
        [NSLayoutConstraint activateConstraints:@[
            [name.topAnchor constraintEqualToAnchor:ownerContainer.topAnchor],
            [name.leadingAnchor constraintEqualToAnchor:ownerContainer.leadingAnchor constant:0],

            [email.topAnchor constraintEqualToAnchor:name.bottomAnchor constant:4],
            [email.leadingAnchor constraintEqualToAnchor:ownerContainer.leadingAnchor constant:0],

            [contact.topAnchor constraintEqualToAnchor:email.bottomAnchor constant:4],
            [contact.leadingAnchor constraintEqualToAnchor:ownerContainer.leadingAnchor constant:0],
            [contact.bottomAnchor constraintEqualToAnchor:ownerContainer.bottomAnchor constant:0]
        ]];

        // Layout ownerContainer inside card
        [NSLayoutConstraint activateConstraints:@[
            [ownerContainer.topAnchor constraintEqualToAnchor:previous.bottomAnchor constant:12],
            [ownerContainer.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:16],
            [ownerContainer.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-16]
        ]];

        previous = ownerContainer;

        // Add separator line after each owner except the last one
        if (i < owners.count - 1) {
            UIView *separator = [[UIView alloc] init];
            separator.backgroundColor = UIColor.blackColor;
            separator.translatesAutoresizingMaskIntoConstraints = NO;
            [card addSubview:separator];

            [NSLayoutConstraint activateConstraints:@[
                [separator.topAnchor constraintEqualToAnchor:previous.bottomAnchor constant:8],
                [separator.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:16],
                [separator.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-16],
                [separator.heightAnchor constraintEqualToConstant:1]
            ]];

            previous = separator;
        }
    }

    [NSLayoutConstraint activateConstraints:@[
        [previous.bottomAnchor constraintEqualToAnchor:card.bottomAnchor constant:-16]
    ]];

    return card;
}

- (UILabel *)makeFieldLabel:(NSString *)text {
    UILabel *lbl = [[UILabel alloc] init];
    lbl.font = [UIFont systemFontOfSize:14];
    lbl.textColor = UIColor.darkGrayColor;
    lbl.text = text;
    lbl.translatesAutoresizingMaskIntoConstraints = NO;
    return lbl;
}

#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 dismissViewControllerAnimated:YES completion:nil];
}

- (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";
    }

    if (!self.appointmentData[@"id"]) {
        NSLog(@"❌ Cannot cancel appointment: appointmentID is nil");
        return;
    }

    [APIClient requestCancelAppointment:self.appointmentData[@"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];
        });
    }];
}

-(void) requestGeneralInfo {
  [APIClient requestGeneralInfo:^(NSDictionary *data, NSError *error) {
      if (error) return;
      NSDictionary *generalInfo = data[@"Data"];
      self.floorPlanImage = generalInfo[@"image"];
      NSLog(@"self.floorPlanImage: %@",self.floorPlanImage);

      dispatch_async(dispatch_get_main_queue(), ^{
          [self updateFloorPlanImage];
      });
  }];
}

- (void)updateFloorPlanImage {
    // Make sure the UIImageView exists
    if (!self.unitInfoHeader) return;

    UIImageView *floorPlan = [self.unitInfoHeader viewWithTag:101]; // use a tag
    if (!floorPlan) return;

    [self loadImage:self.floorPlanImage into:floorPlan];
}

@end
