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

NSString * const DrawerDidSelectItemNotification = @"DrawerDidSelectItemNotification";

@interface DrawerController () <UIGestureRecognizerDelegate>

@property (nonatomic, strong) ProjectViewController *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 = [[ProjectViewController 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];
    NSLog(@"🟩 DrawerController loaded. mainVC = %@", self.mainVC);
    [[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.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor 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 {
    [self.view bringSubviewToFront:self.overlayView];
    [self.view bringSubviewToFront:self.drawerVC.view];

    self.drawerLeadingConstraint.constant = 0; // moves drawer fully into view

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

    self.drawerOpen = YES;
}

- (void)closeDrawer {
    self.drawerLeadingConstraint.constant = self.drawerWidth; // moves drawer offscreen

    [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;
        // Clamp between 0 (open) and -drawerWidth (closed)
        newTx = MIN(0, newTx);
        newTx = MAX(-self.drawerWidth, newTx);

        CGFloat progress = fabs(newTx / self.drawerWidth);
        self.mainVC.view.transform = CGAffineTransformMakeTranslation(newTx, 0);
        self.drawerLeadingConstraint.constant = newTx; // trailing anchor moves from +drawerWidth → 0
        [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); // left swipe opens drawer
        } else {
            shouldOpen = fabs(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];
    NSLog(@"🟩 DrawerController setClientID: %@", _ClientID);

    UIViewController *targetVC = self.mainVC;
    if ([targetVC isKindOfClass:[UINavigationController class]]) {
        targetVC = ((UINavigationController *)targetVC).topViewController;
    }

    if ([targetVC respondsToSelector:@selector(setClientID:)]) {
        [targetVC setValue:_ClientID forKey:@"ClientID"];
    }
}

- (void)setClientCode:(NSString *)ClientCode {
    _ClientCode = [ClientCode copy];
    NSLog(@"🟩 DrawerController setClientCode: %@", _ClientCode);

    UIViewController *targetVC = self.mainVC;
    if ([targetVC isKindOfClass:[UINavigationController class]]) {
        targetVC = ((UINavigationController *)targetVC).topViewController;
    }

    if ([targetVC respondsToSelector:@selector(setClientCode:)]) {
        [targetVC setValue:_ClientCode forKey:@"ClientCode"];
    }
}

- (void)setUser_token:(NSString *)user_token {
    _user_token = [user_token copy];
    NSLog(@"🟩 DrawerController setUser_token: %@", _user_token);

    UIViewController *targetVC = self.mainVC;
    if ([targetVC isKindOfClass:[UINavigationController class]]) {
        targetVC = ((UINavigationController *)targetVC).topViewController;
    }

    if ([targetVC respondsToSelector:@selector(setUser_token:)]) {
        [targetVC setValue:_user_token forKey:@"user_token"];
    }
}

@end
