// DrawerViewController.m
#import "DrawerViewController.h"
#import "DrawerController.h"
#import "SyncScreenViewController.h"
#import "ImageCacheHelper.h"
#import "ProfileViewController.h"
#import "NotificationViewController.h"
#import "HelpViewController.h"
#import "AnnounceViewController.h"
#import "ProjectViewController.h"

static NSString * const ProfileDidUpdateNotification = @"ProfileDidUpdateNotification";

@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;
@property (nonatomic, weak, readwrite) DrawerController *drawerController;
@end

@implementation DrawerViewController

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

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

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)buildUI {
    self.view.backgroundColor = [UIColor clearColor];

    CGFloat topHeight = 110;

    // 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 colorWithRed:0.02 green:0.36 blue:0.47 alpha:1.0];
    self.table.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.table];

    [NSLayoutConstraint activateConstraints:@[
        [self.table.topAnchor constraintEqualToAnchor:self.headerContainer.bottomAnchor],
//        [self.table.topAnchor constraintEqualToAnchor:self.view.topAnchor constant:topHeight],
        [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";

    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": @"list", @"icon": @"", @"hidden": @YES} mutableCopy],
            [@{@"title": @"Notification", @"action": @"notification", @"icon": @"bell.fill"} mutableCopy],
            [@{@"title": @"Announcement", @"action": @"announcement", @"icon": @"megaphone"} mutableCopy],
            [@{@"title": @"Help", @"action": @"help", @"icon": @"questionmark"} mutableCopy],
            [@{@"title": @"Sync", @"action": @"sync", @"icon": @"arrow.trianglehead.2.clockwise.rotate.90"} mutableCopy],
            [@{@"title": @"Logout", @"action": @"logout", @"icon": @"rectangle.portrait.and.arrow.right"} mutableCopy]
        ] mutableCopy];
    }
    [self.table reloadData];
}

#pragma mark - Profile tap
- (void)profileTapped {
    NSLog(@"Sidemenu header tapped");
    DrawerController *drawerController = self.drawerController;
    [drawerController closeDrawer];
    ProfileViewController *vc = [[ProfileViewController alloc] init];
    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:vc animated:YES completion:nil];
}

#pragma mark - Table datasource/delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSPredicate *predicate =
    [NSPredicate predicateWithBlock:^BOOL(NSDictionary *item, NSDictionary *bindings) {
        return ![item[@"hidden"] boolValue];
    }];

    return [[self.menuItems filteredArrayUsingPredicate:predicate] 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;
        cell.imageView.contentMode = UIViewContentModeScaleAspectFit;
    }

    NSDictionary *item = [self visibleMenuItems][indexPath.row];
    cell.textLabel.text = item[@"title"] ?: @"";

    NSString *iconName = item[@"icon"];
    if (iconName.length > 0) {
        UIImage *icon = [UIImage systemImageNamed:iconName];
        cell.imageView.image = icon;
        cell.imageView.tintColor = UIColor.whiteColor; // optional, make it match text color
    } else {
        cell.imageView.image = nil;
    }

    return cell;
}

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

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

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

- (NSArray *)visibleMenuItems {
    NSPredicate *predicate =
    [NSPredicate predicateWithBlock:^BOOL(NSDictionary *item, NSDictionary *bindings) {
        return ![item[@"hidden"] boolValue];
    }];
    return [self.menuItems filteredArrayUsingPredicate:predicate];
}

- (void)showHiddenButton:(BOOL)show {
    for (NSMutableDictionary *item in self.menuItems) {
        if ([item[@"action"] isEqualToString:@"list"]) {
            item[@"hidden"] = @(!show);
        }
    }
    [self.table reloadData]; // ensures table updates immediately
}

- (void)handleShowHiddenButton:(NSNotification *)notification {
    NSLog(@"hidden button toggled");
    BOOL show = [notification.object boolValue];
    [self showHiddenButton:show];
}

- (void)handleDrawerAction:(NSNotification *)notification {
    NSString *action = notification.object;
    NSLog(@"Drawer action: %@", action);

    DrawerController *drawerController = self.drawerController;
    NSLog(@"drawerController: %@", drawerController);
    if (!drawerController) return;

    UIViewController *mainVC = drawerController.mainViewController;
    UINavigationController *nav = nil;

    if ([mainVC isKindOfClass:[UINavigationController class]]) {
        nav = (UINavigationController *)mainVC;
    } else {
        NSLog(@"❌ mainVC is not UINavigationController");
        return;
    }

    // Always close drawer first
    [drawerController closeDrawer];

    if ([action isEqualToString:@"list"]) {
        ProjectViewController *vc = [[ProjectViewController alloc] init];
        vc.drawerController = drawerController;
        [nav setViewControllers:@[vc] animated:NO]; // reset stack to Project list
    }
    else if ([action isEqualToString:@"notification"]) {
        NotificationViewController *vc = [[NotificationViewController alloc] init];
        vc.drawerController = drawerController;
        [nav pushViewController:vc animated:YES];
    }
    else if ([action isEqualToString:@"announcement"]) {
        AnnouncementViewController *vc = [[AnnouncementViewController alloc] init];
        [nav pushViewController:vc animated:YES];
    }
    else if ([action isEqualToString:@"help"]) {
        HelpViewController *vc = [[HelpViewController alloc] init];
        [nav pushViewController:vc animated:YES];
    }
    else if ([action isEqualToString:@"sync"]) {
        SyncScreenViewController *vc = [[SyncScreenViewController alloc] init];
        [nav pushViewController:vc animated:YES];
    }
    else if ([action isEqualToString:@"logout"]) {
        [self logoutTapped];
    }
}


- (void)onProfileUpdated:(NSNotification *)notification {
    NSDictionary *info = notification.userInfo;
    
    NSLog(@"profile update received");

    NSString *name = info[@"name"] ?: @"Guest User";
    NSString *email = info[@"email"] ?: @"guest@example.com";
    NSString *avatarURLString = info[@"avatar"];

    dispatch_async(dispatch_get_main_queue(), ^{
        self.nameLabel.text = name;
        self.emailLabel.text = email;

        if (avatarURLString.length > 0) {
            NSURL *url = [NSURL URLWithString:avatarURLString];
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                [ImageCacheHelper loadImageWithURL:url completion:^(UIImage *image) {
                    self.avatarView.image = image;
                }];
            });
        } else {
            self.avatarView.image = [UIImage imageNamed:@"small_placeholder"];
        }
    });
}

- (void)logoutTapped {
    UIAlertController *alert =
    [UIAlertController alertControllerWithTitle:@"Alert"
                                        message:@"Are you sure you want to logout?"
                                 preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *cancel =
    [UIAlertAction actionWithTitle:@"No"
                             style:UIAlertActionStyleCancel
                           handler:nil];

    UIAlertAction *confirm =
    [UIAlertAction actionWithTitle:@"Yes"
                             style:UIAlertActionStyleDestructive
                           handler:^(UIAlertAction * _Nonnull action) {

        // Clear session
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"userToken"];
        [[NSUserDefaults standardUserDefaults] synchronize];

        // Exit profile
        [self dismissViewControllerAnimated:YES completion:nil];
    }];

    [alert addAction:cancel];
    [alert addAction:confirm];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)attachDrawerController:(DrawerController *)drawerController {
    _drawerController = drawerController;
}

@end
