// DrawerViewController.m
#import "DrawerViewController.h"
#import "DrawerController.h"
#import "SyncScreenViewController.h"

@interface DrawerViewController () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UIImageView *avatarView;
@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) UILabel *emailLabel;
@property (nonatomic, strong) UITableView *table;
@property (nonatomic, strong) UIView *headerContainer;

@end

@implementation DrawerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:0.02 green:0.36 blue:0.47 alpha:1.0]; // #035E79-ish

    [self buildUI];
    [self loadDefaultsIfNeeded];
  
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleDrawerAction:)
                                                 name:DrawerDidSelectItemNotification
                                               object:nil];
}

- (void)buildUI {
    self.view.backgroundColor = [UIColor colorWithRed:0.02 green:0.36 blue:0.47 alpha:1.0];

    CGFloat topHeight = (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) ? 180 : 120;

    // HEADER CONTAINER
    self.headerContainer = [[UIView alloc] init];
    self.headerContainer.translatesAutoresizingMaskIntoConstraints = NO;
    self.headerContainer.backgroundColor = [UIColor colorWithRed:0 green:0.42 blue:0.55 alpha:1.0];
    [self.view addSubview:self.headerContainer];

    [NSLayoutConstraint activateConstraints:@[
        [self.headerContainer.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.headerContainer.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.headerContainer.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor],
        [self.headerContainer.heightAnchor constraintEqualToConstant:topHeight],
    ]];

    // TOUCHABLE HEADER
    UIButton *profileTap = [UIButton buttonWithType:UIButtonTypeCustom];
    profileTap.translatesAutoresizingMaskIntoConstraints = NO;
    [profileTap addTarget:self action:@selector(profileTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.headerContainer addSubview:profileTap];

    [NSLayoutConstraint activateConstraints:@[
        [profileTap.leadingAnchor constraintEqualToAnchor:self.headerContainer.leadingAnchor],
        [profileTap.trailingAnchor constraintEqualToAnchor:self.headerContainer.trailingAnchor],
        [profileTap.topAnchor constraintEqualToAnchor:self.headerContainer.topAnchor],
        [profileTap.bottomAnchor constraintEqualToAnchor:self.headerContainer.bottomAnchor],
    ]];

    // AVATAR
    CGFloat avatarSize = (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) ? 100 : 50;
    self.avatarView = [[UIImageView alloc] init];
    self.avatarView.translatesAutoresizingMaskIntoConstraints = NO;
    self.avatarView.layer.cornerRadius = avatarSize / 2.0;
    self.avatarView.clipsToBounds = YES;
    self.avatarView.layer.borderColor = [UIColor whiteColor].CGColor;
    self.avatarView.layer.borderWidth = 1.0;
    self.avatarView.contentMode = UIViewContentModeScaleAspectFill;
    [self.headerContainer addSubview:self.avatarView];

    [NSLayoutConstraint activateConstraints:@[
        [self.avatarView.leadingAnchor constraintEqualToAnchor:self.headerContainer.leadingAnchor constant:18],
        [self.avatarView.centerYAnchor constraintEqualToAnchor:self.headerContainer.centerYAnchor],
        [self.avatarView.widthAnchor constraintEqualToConstant:avatarSize],
        [self.avatarView.heightAnchor constraintEqualToConstant:avatarSize],
    ]];

    // NAME LABEL
    self.nameLabel = [[UILabel alloc] init];
    self.nameLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.nameLabel.textColor = UIColor.whiteColor;
    self.nameLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightRegular];
    self.nameLabel.numberOfLines = 2;
    [self.headerContainer addSubview:self.nameLabel];

    // EMAIL LABEL
    self.emailLabel = [[UILabel alloc] init];
    self.emailLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.emailLabel.textColor = UIColor.whiteColor;
    self.emailLabel.font = [UIFont systemFontOfSize:14];
    [self.headerContainer addSubview:self.emailLabel];

    [NSLayoutConstraint activateConstraints:@[
        [self.nameLabel.leadingAnchor constraintEqualToAnchor:self.avatarView.trailingAnchor constant:16],
        [self.nameLabel.trailingAnchor constraintEqualToAnchor:self.headerContainer.trailingAnchor constant:-18],
        [self.nameLabel.bottomAnchor constraintEqualToAnchor:self.headerContainer.centerYAnchor constant:-4],

        [self.emailLabel.leadingAnchor constraintEqualToAnchor:self.nameLabel.leadingAnchor],
        [self.emailLabel.trailingAnchor constraintEqualToAnchor:self.nameLabel.trailingAnchor],
        [self.emailLabel.topAnchor constraintEqualToAnchor:self.nameLabel.bottomAnchor constant:4],
    ]];

    // MENU TABLE
    self.table = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.table.translatesAutoresizingMaskIntoConstraints = NO;
    self.table.dataSource = self;
    self.table.delegate = self;
    self.table.backgroundColor = UIColor.clearColor;
    self.table.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.table];

    [NSLayoutConstraint activateConstraints:@[
        [self.table.topAnchor constraintEqualToAnchor:self.headerContainer.bottomAnchor],
        [self.table.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.table.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.table.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor],
    ]];
}

- (void)loadDefaultsIfNeeded {
    if (!self.profileName) self.profileName = @"Guest User";
    if (!self.profileEmail) self.profileEmail = @"guest@example.com";
    if (!self.profileImageURL) self.profileImageURL = nil;

    self.nameLabel.text = self.profileName;
    self.emailLabel.text = self.profileEmail;

    if (self.profileImageURL) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSData *d = [NSData dataWithContentsOfURL:self.profileImageURL];
            UIImage *img = d ? [UIImage imageWithData:d] : [UIImage imageNamed:@"small_placeholder"];
            dispatch_async(dispatch_get_main_queue(), ^{
                self.avatarView.image = img;
            });
        });
    } else {
        self.avatarView.image = [UIImage imageNamed:@"small_placeholder"];
    }

    if (!self.menuItems) {
        self.menuItems = @[
            @{@"title": @"Project List", @"action": @"projectList"},
            @{@"title": @"Notification", @"action": @"notification"},
            @{@"title": @"Announcement", @"action": @"announcement"},
            @{@"title": @"Help", @"action": @"help"},
            @{@"title": @"Sync", @"action": @"sync"},
            @{@"title": @"Logout", @"action": @"logout"}
        ];
    }
    [self.table reloadData];
}

#pragma mark - Profile tap
- (void)profileTapped {
    // Post a notification to navigate
    [[NSNotificationCenter defaultCenter] postNotificationName:DrawerDidSelectItemNotification object:nil userInfo:@{@"action": @"profile"}];
}

#pragma mark - Table datasource/delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.menuItems.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellId = @"drawerCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        cell.backgroundColor = [UIColor clearColor];
        cell.textLabel.textColor = [UIColor whiteColor];
        cell.textLabel.font = [UIFont systemFontOfSize:16];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    NSDictionary *item = self.menuItems[indexPath.row];
    cell.textLabel.text = item[@"title"] ?: @"";
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return 56; }

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *item = self.menuItems[indexPath.row];
    NSString *action = item[@"action"];

    [[NSNotificationCenter defaultCenter] postNotificationName:@"DrawerDidSelectItemNotification"
                                                        object:action];
}

- (void)handleDrawerAction:(NSNotification *)notification {
    NSString *action = notification.object;

    if ([action isEqualToString:@"projectList"]) {
//        [self openProjectList];
      NSLog(@"navigating to Project List");
    }
    else if ([action isEqualToString:@"notification"]) {
//        [self openNotification];
      NSLog(@"navigating to Notification");

    }
    else if ([action isEqualToString:@"announcement"]) {
//        [self openAnnouncement];
      NSLog(@"navigating to Announcement");

    }
    else if ([action isEqualToString:@"help"]) {
//        [self openHelp];
      NSLog(@"navigating to Help");

    }
    else if ([action isEqualToString:@"sync"]) {
      NSLog(@"navigating to Sync");
    
      SyncScreenViewController *nextVC = [[SyncScreenViewController alloc] init];
      nextVC.modalPresentationStyle = UIModalPresentationFullScreen;
      [self presentViewController:nextVC animated:YES completion:nil];
    }
    else if ([action isEqualToString:@"logout"]) {
//        [self performLogout];
      NSLog(@"navigating to Logout");

    }
}



@end
