// DrawerController.m
#import "DrawerController.h"
#import "DashboardViewController.h"

NSString * const DrawerDidSelectItemNotification = @"DrawerDidSelectItemNotification";

@interface DrawerController () <UIGestureRecognizerDelegate>

@property (nonatomic, strong) DashboardViewController *mainVC;
@property (nonatomic, strong) UIViewController *drawerVC;
@property (nonatomic, strong) UIView *overlayView;
@property (nonatomic, assign) BOOL drawerOpen;
@property (nonatomic, assign) CGFloat drawerWidth;
@property (nonatomic, strong) UIPanGestureRecognizer *panGR;
@property (nonatomic, strong) NSLayoutConstraint *drawerLeadingConstraint;

@end

@implementation DrawerController

#pragma mark - Initializer
- (instancetype)initWithDrawerViewController:(UIViewController *)drawer
                                   clientID:(NSString *)clientID
                                 clientCode:(NSString *)clientCode
                                  userToken:(NSString *)user_token {
    self = [super initWithNibName:nil bundle:nil];
    if (!self) return nil;

    // 1️⃣ Initialize DashboardViewController with props
    _mainVC = [[DashboardViewController alloc] initWithClientID:clientID
                                                     clientCode:clientCode
                                                      userToken:user_token];

    // 2️⃣ Set back-reference to drawerController
    _mainVC.drawerController = self;

    // 3️⃣ Save props locally
    _ClientID = [clientID copy];
    _ClientCode = [clientCode copy];
    _user_token = [user_token copy];

    // 4️⃣ Set drawer VC and drawer width
    _drawerVC = drawer;
    _drawerWidth = MIN([UIScreen mainScreen].bounds.size.width * 0.78, 360);

    return self;
}

#pragma mark - View Lifecycle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blackColor];

    [self setupDrawer];
    [self setupOverlay];
    [self setupMainVC];
    [self setupPanGesture];

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

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

#pragma mark - Getters
- (UIViewController *)mainViewController {
    return _mainVC;
}

- (UIViewController *)drawerViewController {
    return _drawerVC;
}

#pragma mark - Setup UI
- (void)setupDrawer {
    [self addChildViewController:self.drawerVC];
    self.drawerVC.view.translatesAutoresizingMaskIntoConstraints = NO;
    self.drawerVC.view.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:self.drawerVC.view];
    [self.drawerVC didMoveToParentViewController:self];

    self.drawerLeadingConstraint =
        [self.drawerVC.view.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:-self.drawerWidth];

    [self.drawerVC.view.widthAnchor constraintEqualToConstant:self.drawerWidth].active = YES;
    [self.drawerVC.view.topAnchor constraintEqualToAnchor:self.view.topAnchor].active = YES;
    [self.drawerVC.view.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor].active = YES;
    self.drawerLeadingConstraint.active = YES;
}

- (void)setupOverlay {
    // Overlay only covers the mainVC, not the drawer
    self.overlayView = [[UIView alloc] initWithFrame:self.mainVC.view.frame];
    self.overlayView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.4];
    self.overlayView.alpha = 0.0;
    self.overlayView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

    // Tap gesture to close drawer
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeDrawer)];
    [self.overlayView addGestureRecognizer:tap];

    // Add overlay **below** the drawer so it doesn't block menu interactions
    [self.view insertSubview:self.overlayView belowSubview:self.drawerVC.view];
}

- (void)setupMainVC {
    [self addChildViewController:self.mainVC];
    self.mainVC.view.frame = self.view.bounds;
    self.mainVC.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:self.mainVC.view];
    [self.mainVC didMoveToParentViewController:self];
}

- (void)setupPanGesture {
    self.panGR = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
    self.panGR.delegate = self;
    [self.mainVC.view addGestureRecognizer:self.panGR];
}

#pragma mark - Drawer Actions
- (void)openDrawer {
    // Make sure overlay and drawer are on top
    [self.view bringSubviewToFront:self.overlayView];
    [self.view bringSubviewToFront:self.drawerVC.view];

    self.drawerLeadingConstraint.constant = 0;

    [UIView animateWithDuration:0.25 animations:^{
        [self.view layoutIfNeeded];
        self.overlayView.alpha = 1.0;
    }];

    self.drawerOpen = YES;
}

- (void)closeDrawer {
    self.drawerLeadingConstraint.constant = -self.drawerWidth;

    [UIView animateWithDuration:0.25 animations:^{
        [self.view layoutIfNeeded];
        self.overlayView.alpha = 0.0;
    }];

    self.drawerOpen = NO;
}

- (void)toggleDrawer {
    if (self.drawerOpen) [self closeDrawer];
    else [self openDrawer];
}

- (BOOL)isDrawerOpen {
    return self.drawerOpen;
}

#pragma mark - Pan Gesture
- (void)handlePan:(UIPanGestureRecognizer *)pan {
    CGPoint translation = [pan translationInView:self.view];
    CGFloat x = translation.x;
    static CGFloat startX;

    if (pan.state == UIGestureRecognizerStateBegan) {
        startX = self.mainVC.view.transform.tx;
    } else if (pan.state == UIGestureRecognizerStateChanged) {
        CGFloat newTx = startX + x;
        newTx = MAX(0, newTx);
        newTx = MIN(self.drawerWidth, newTx);

        CGFloat progress = newTx / self.drawerWidth;
        self.mainVC.view.transform = CGAffineTransformMakeTranslation(newTx, 0);
        self.drawerLeadingConstraint.constant = -self.drawerWidth + newTx;
        [self.view layoutIfNeeded];
        self.overlayView.alpha = progress;
    } else if (pan.state == UIGestureRecognizerStateEnded || pan.state == UIGestureRecognizerStateCancelled) {
        CGFloat velocityX = [pan velocityInView:self.view].x;
        CGFloat currentTx = self.mainVC.view.transform.tx;

        BOOL shouldOpen = NO;
        if (fabs(velocityX) > 400) {
            shouldOpen = (velocityX > 0);
        } else {
            shouldOpen = currentTx > (self.drawerWidth * 0.45);
        }

        if (shouldOpen) [self openDrawer];
        else [self closeDrawer];
    }
}

#pragma mark - Notification
- (void)menuItemSelected:(NSNotification *)note {
    [self closeDrawer];
}

#pragma mark - Gesture Delegate
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    if (gestureRecognizer == self.panGR) {
        CGPoint v = [self.panGR velocityInView:self.view];
        return fabs(v.x) > fabs(v.y);
    }
    return YES;
}

#pragma mark - Prop Setters
- (void)setClientID:(NSString *)ClientID {
    _ClientID = [ClientID copy];
    if ([self.mainVC respondsToSelector:NSSelectorFromString(@"setClientID:")]) {
        [self.mainVC setValue:_ClientID forKey:@"ClientID"];
    }
}

- (void)setClientCode:(NSString *)ClientCode {
    _ClientCode = [ClientCode copy];
    if ([self.mainVC respondsToSelector:NSSelectorFromString(@"setClientCode:")]) {
        [self.mainVC setValue:_ClientCode forKey:@"ClientCode"];
    }
}

- (void)setUser_token:(NSString *)user_token {
    _user_token = [user_token copy];
    if ([self.mainVC respondsToSelector:NSSelectorFromString(@"setUser_token:")]) {
        [self.mainVC setValue:_user_token forKey:@"user_token"];
    }
}

@end
