//  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 *loadingOverlay;

@end


@implementation AppointmentDetailsViewController

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

    [self setupNavBar];
    [self setupScrollView];
    [self setupStatusBanner];
  [self setupUnitInfoHeader];
    [self setupSummaryCard];
    [self setupRepresentativeCard];
    [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.contentView.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.contentView addSubview:self.summaryCard];

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

    [NSLayoutConstraint activateConstraints:@[
        [self.summaryCard.topAnchor constraintEqualToAnchor:self.statusBanner.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;
    };

    UILabel *typeField = makeField(@"Type :", self.appointmentData[@"type"]);
    UILabel *dateField = makeField(@"Date :", self.appointmentData[@"date"]);
    UILabel *slotField = makeField(@"Time Slot :", self.appointmentData[@"time"]);
    UILabel *locField = makeField(@"Location :", self.appointmentData[@"location"]);
  
    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.summaryCard addSubview:calendarBtn];

}

#pragma mark - Summary Tabs

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

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

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

    [tabs addSubview:summaryBtn];
    [tabs addSubview:ownerBtn];

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

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

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

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

    self.tabsBar = tabs;
}


#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.contentView addSubview:self.repCard];

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

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

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

#pragma mark - Buttons Section

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

    [NSLayoutConstraint activateConstraints:@[
        [self.buttonSection.topAnchor constraintEqualToAnchor:self.summaryCard.bottomAnchor constant:30],
        [self.buttonSection.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor],
        [self.buttonSection.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor],
        [self.buttonSection.bottomAnchor constraintEqualToAnchor:self.contentView.bottomAnchor constant:-40],
        [self.buttonSection.heightAnchor constraintEqualToConstant:200], // dynamic later
    ]];
  
    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];

    [self.buttonSection addSubview:cancelBtn];

    [NSLayoutConstraint activateConstraints:@[
        [cancelBtn.topAnchor constraintEqualToAnchor:self.buttonSection.topAnchor],
        [cancelBtn.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],
        [cancelBtn.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-16],
        [cancelBtn.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"];

    // TODO: fill summary card fields
    // TODO: fill representative card fields
    // TODO: build action buttons based on status
}

#pragma mark - Actions

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

- (void) cancelPressed {
//  [AppointmentAPIClient fetch:self.appointmentID reason:something completion:^(NSDictionary *data, NSError *error) {
//    if (error) {
//      NSLog(@"Error %@", error.localizedDescription);
//      return;
//    }
//  }];
}

@end

