//  ProjectViewController.mm
#import "ProjectViewController.h"
#import "APIClient.h"
#import "APIConfig.h"
#import "UnitViewController.h"
#import "ImageCacheHelper.h"

static NSString * const ProfileDidUpdateNotification = @"ProfileDidUpdateNotification";

@interface ProjectCardCell : UICollectionViewCell
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UILabel *nameLabel;
@end

@implementation ProjectCardCell

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.contentView.backgroundColor = UIColor.secondarySystemBackgroundColor;
        self.layer.cornerRadius = 8;
        self.layer.shadowColor = UIColor.blackColor.CGColor;
        self.layer.shadowOpacity = 0.15;
        self.layer.shadowOffset = CGSizeMake(0, 4);
        self.layer.shadowRadius = 6;
        self.layer.masksToBounds = NO;

        self.contentView.layer.cornerRadius = 8;
        self.contentView.clipsToBounds = YES;

        // image
        self.imageView = [[UIImageView alloc] init];
        self.imageView.contentMode = UIViewContentModeScaleAspectFill;
        self.imageView.translatesAutoresizingMaskIntoConstraints = NO;
        [self.contentView addSubview:self.imageView];
        
        // label
        self.nameLabel = [[UILabel alloc] init];
        self.nameLabel.font = [UIFont boldSystemFontOfSize:18];
        self.nameLabel.textColor = UIColor.whiteColor;
//        self.nameLabel.backgroundColor =
//            [[UIColor blackColor] colorWithAlphaComponent:0.35];
        self.nameLabel.numberOfLines = 2;
        self.nameLabel.translatesAutoresizingMaskIntoConstraints = NO;
        [self.contentView addSubview:self.nameLabel];
        
        // constraints
        [NSLayoutConstraint activateConstraints:@[
            [self.imageView.topAnchor constraintEqualToAnchor:self.contentView.topAnchor],
            [self.imageView.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor],
            [self.imageView.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor],
            [self.imageView.bottomAnchor constraintEqualToAnchor:self.contentView.bottomAnchor],

            [self.nameLabel.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:8],
            [self.nameLabel.trailingAnchor constraintLessThanOrEqualToAnchor:self.contentView.trailingAnchor constant:-8],
            [self.nameLabel.bottomAnchor constraintEqualToAnchor:self.contentView.bottomAnchor constant:-8],
        ]];
    }
    return self;
}

@end

@interface ProjectViewController () <UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIButton *backButton;
@property (nonatomic, strong) UILabel *titleLabel;

@property (nonatomic, strong) UICollectionView *projectCollectionView;

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSArray *projects;

@property (nonatomic, strong) UIView *loadingOverlay;
@property (nonatomic, strong) UIActivityIndicatorView *spinner;
@property (nonatomic, strong) UILabel *loadingLabel;
@property (nonatomic, assign) BOOL isLoadingDashboard;
@property (nonatomic, assign) BOOL didLoadDashboard;

@end

@implementation ProjectViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.systemBackgroundColor;
    [self checkAndRefreshAPIs];
    [self setupHeader];
    [self setupCollectionView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = YES;
}

- (instancetype)initWithClientID:(NSString *)clientID
                       clientCode:(NSString *)clientCode
                        userToken:(NSString *)userToken {
    self = [super initWithNibName:nil bundle:nil];
    if (self) {
        _ClientID = [clientID copy];
        _ClientCode = [clientCode copy];
        _user_token = [userToken copy];
    }
    return self;
}

- (void)checkAndRefreshAPIs {
    NSLog(@"🔍 Checking credentials...");
    NSLog(@"ClientID: %@", self.ClientID);
    NSLog(@"ClientCode: %@", self.ClientCode);
    NSLog(@"user_token: %@", self.user_token);
  
   [self showLoadingOverlay:@"Loading..."];

   if (![self isReadyToLoadDashboard]) {
       NSLog(@"⏳ Waiting for all credentials to be ready...");
       return;
   }
 
   if (_isLoadingDashboard) return;

   self.isLoadingDashboard = YES;

   NSLog(@"✅ All credentials ready. ClientID: %@, ClientCode: %@, user_token: %@",
         self.ClientID, self.ClientCode, self.user_token);
 
   
   [APIConfig setAuthTokem:self.user_token];
   [APIConfig setClientId:self.ClientID];
//     self.ClientCode = @"spt";
    [self requestCompanyCode];
}

#pragma mark - Header Setup
- (void)setupHeader {
  self.headerView = [[UIView alloc] init];
  self.headerView.backgroundColor = [UIColor colorWithRed:0.0 green:0.5 blue:0.6 alpha:1.0];
  self.headerView.translatesAutoresizingMaskIntoConstraints = NO;
  [self.view addSubview:self.headerView];
  
  UIButton *menuButton = [UIButton buttonWithType:UIButtonTypeCustom];
  menuButton.translatesAutoresizingMaskIntoConstraints = NO;
  [menuButton setImage:[UIImage systemImageNamed:@"line.horizontal.3"] forState:UIControlStateNormal];
  menuButton.tintColor = UIColor.whiteColor;
  [menuButton addTarget:self action:@selector(handleMenuButtonTapped) forControlEvents:UIControlEventTouchUpInside];
  [self.headerView addSubview:menuButton];
  
  self.backButton = [UIButton buttonWithType:UIButtonTypeCustom];
  [self.backButton setImage:[UIImage systemImageNamed:@"chevron.backward"]
                   forState:UIControlStateNormal];
  self.backButton.tintColor = UIColor.whiteColor;
  [self.backButton addTarget:self
                      action:@selector(onBack)
            forControlEvents:UIControlEventTouchUpInside];
  self.backButton.translatesAutoresizingMaskIntoConstraints = NO;
  [self.headerView addSubview:self.backButton];
  
  [NSLayoutConstraint activateConstraints:@[
    [self.headerView.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor],
    [self.headerView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
    [self.headerView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
    [self.headerView.heightAnchor constraintEqualToConstant:44],
    
    [self.backButton.leadingAnchor constraintEqualToAnchor:self.headerView.leadingAnchor constant:8],
    [self.backButton.centerYAnchor constraintEqualToAnchor:self.headerView.centerYAnchor],
    [self.backButton.widthAnchor constraintEqualToConstant:32],
    [self.backButton.heightAnchor constraintEqualToConstant:32],
    
    [menuButton.trailingAnchor constraintEqualToAnchor:self.headerView.trailingAnchor constant:-16],
    [menuButton.centerYAnchor constraintEqualToAnchor:self.headerView.centerYAnchor],
    [menuButton.widthAnchor constraintEqualToConstant:26],
    [menuButton.heightAnchor constraintEqualToConstant:26],
  ]];
}

#pragma mark - Setup Collection View
- (void)setupCollectionView {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.minimumLineSpacing = 12;
    layout.minimumInteritemSpacing = 16;
    layout.sectionInset = UIEdgeInsetsMake(16, 16, 16, 16);
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    self.collectionView.translatesAutoresizingMaskIntoConstraints = NO;
    self.collectionView.backgroundColor = UIColor.systemBackgroundColor;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    // register cell class
    [self.collectionView registerClass:[ProjectCardCell class] forCellWithReuseIdentifier:@"ProjectCardCell"];
    
    [self.view addSubview:self.collectionView];
    
    // constraints
    [NSLayoutConstraint activateConstraints:@[
        [self.collectionView.topAnchor constraintEqualToAnchor:self.headerView.bottomAnchor constant:20],
        [self.collectionView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.collectionView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.collectionView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor]
    ]];
}

#pragma mark - UICollectionView DataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.projects.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                          cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    ProjectCardCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ProjectCardCell"
                                                                      forIndexPath:indexPath];
    
    // Default placeholder
    NSBundle *bundle = [NSBundle bundleForClass:[self class]];
    UIImage *placeholderImage = [UIImage imageNamed:@"img_placeholder" 
                                             inBundle:bundle 
                        compatibleWithTraitCollection:nil];
    cell.imageView.image = placeholderImage;
    
    NSDictionary *project = self.projects[indexPath.item];
    
    // Project name
    id projectName = project[@"project_name"];
    cell.nameLabel.text = [projectName isKindOfClass:[NSString class]] ? projectName : @"";

    // Determine logo URL
    NSString *logoURLString = project[@"logo"];
    if (!logoURLString.length) logoURLString = project[@"logo_thumbnail"];
    
    // Use ImageCacheHelper for async loading & caching
    [ImageCacheHelper loadImageWithURL:[NSURL URLWithString:logoURLString ?: @""] completion:^(UIImage *image) {
        if (image) {
            // Ensure the cell is still visible
            ProjectCardCell *updateCell = (ProjectCardCell *)[collectionView cellForItemAtIndexPath:indexPath];
            if (updateCell) {
                updateCell.imageView.image = image;
            }
        }
    }];

    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *project = self.projects[indexPath.item];
    [APIConfig setProjectId:[project[@"id"] description]];

    UnitViewController *vc = [[UnitViewController alloc] init];
    vc.projectId = [project[@"id"] description];
    vc.projectName = project[@"project_name"];
    vc.units = project[@"unit"];
    vc.drawerController = self.drawerController;
    vc.projectLogo = project[@"logo"] ?: project[@"logo_thumbnail"];
    vc.modalPresentationStyle = UIModalPresentationFullScreen;
  
    [self.navigationController pushViewController:vc animated:YES];
}

- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout *)collectionViewLayout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath {

    CGFloat horizontalInset = 16 * 2; // section inset left + right
    CGFloat width = collectionView.bounds.size.width - horizontalInset;
    CGFloat height = 140; // OG-style banner height

    return CGSizeMake(width, height);
}

#pragma mark - Loading Overlay
- (void)showLoadingOverlay:(NSString *)message {
    if (!self.loadingOverlay) {
        // Full screen overlay
        self.loadingOverlay = [[UIView alloc] init];
        self.loadingOverlay.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
        self.loadingOverlay.translatesAutoresizingMaskIntoConstraints = NO;
        [self.view addSubview:self.loadingOverlay];

        [NSLayoutConstraint activateConstraints:@[
            [self.loadingOverlay.topAnchor constraintEqualToAnchor:self.view.topAnchor],
            [self.loadingOverlay.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor],
            [self.loadingOverlay.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
            [self.loadingOverlay.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        ]];
      
        // Spinner
        self.spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleLarge];
        self.spinner.color = UIColor.whiteColor;
        self.spinner.translatesAutoresizingMaskIntoConstraints = NO;
        [self.loadingOverlay addSubview:self.spinner];
        [self.spinner startAnimating];

        // Label
        self.loadingLabel = [[UILabel alloc] init];
        self.loadingLabel.textColor = UIColor.whiteColor;
        self.loadingLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
        self.loadingLabel.translatesAutoresizingMaskIntoConstraints = NO;
        self.loadingLabel.textAlignment = NSTextAlignmentCenter;
        self.loadingLabel.text = message ?: @"Loading";
        [self.loadingOverlay addSubview:self.loadingLabel];

        // Constraints
        [NSLayoutConstraint activateConstraints:@[
            [self.spinner.centerXAnchor constraintEqualToAnchor:self.loadingOverlay.centerXAnchor],
            [self.spinner.centerYAnchor constraintEqualToAnchor:self.loadingOverlay.centerYAnchor],

            [self.loadingLabel.topAnchor constraintEqualToAnchor:self.spinner.bottomAnchor constant:16],
            [self.loadingLabel.centerXAnchor constraintEqualToAnchor:self.loadingOverlay.centerXAnchor]
        ]];
    } else {
        self.loadingLabel.text = message ?: @"Loading";
    }

    [self.view addSubview:self.loadingOverlay];
}

- (void)hideLoadingOverlay {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.spinner stopAnimating];
        [self.loadingOverlay removeFromSuperview];
        self.spinner = nil;
        self.loadingLabel = nil;
        self.loadingOverlay = nil;
    });
}

#pragma mark - API
- (void)requestProjectList {
    [APIClient requestProjectList:^(BOOL success, NSDictionary *data, NSError *error) {
      
        // Save debug file
        NSString *plainText = [NSString stringWithFormat:@"%@", data];
        NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
        NSString *filePath = [docsPath stringByAppendingPathComponent:@"projectList.txt"];
        [plainText writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
        NSLog(@"📁 projectList saved as plain text to: %@", filePath);

        [self hideLoadingOverlay];
        self.isLoadingDashboard = NO;

        if (error || !data) {
            NSLog(@"❌ Project list API failed: %@", error);
            return;
        }

        if (data[@"status_code"]) {
            NSLog(@"❌ API status error: %@", data[@"message"]);
            return;
        }

        NSDictionary *appData = data[@"AppData"];
        if (![appData[@"status"] isEqualToString:@"success"]) {
            NSLog(@"❌ API failure: %@", appData[@"message"]);
            return;
        }

        NSArray *projects = data[@"Data"];
        if (![projects isKindOfClass:[NSArray class]]) {
            NSLog(@"❌ Invalid project list format");
            return;
        }

        self.projects = projects;

        dispatch_async(dispatch_get_main_queue(), ^{
            [self.collectionView reloadData];
            // Auto-select first project if only 1
            if (self.projects.count == 1) {
                NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];
                [self collectionView:self.collectionView didSelectItemAtIndexPath:indexPath];
            }
        });
    }];
}

- (void)requestCompanyCode {
  [APIClient requestCompanyCode:self.ClientCode completion:^(BOOL success, NSDictionary *data, NSError *error) {
      
        // debug
        NSString *plainText = [NSString stringWithFormat:@"%@", data];
        NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
        NSString *filePath = [docsPath stringByAppendingPathComponent:@"companyCode.txt"];
        [plainText writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
        NSLog(@"📁 companyCode saved as plain text to: %@", filePath);
        [self hideLoadingOverlay];
        self.isLoadingDashboard = NO;
    
        if (error || !data) {
            NSLog(@"❌ Company Code API failed: %@", error);
            return;
        }

        // RN parity: status_code check
        if (data[@"status_code"]) {
            NSLog(@"❌ Company Code error: %@", data[@"message"]);
            return;
        }

        NSDictionary *appData = data[@"AppData"];
        if (![appData[@"status"] isEqualToString:@"success"]) {
            NSLog(@"❌ API failure: %@", appData[@"message"]);
            return;
        }
      
        if (!error) {
          NSString *rawURL = data[@"Data"][@"url_path"];
          NSString *baseURL = rawURL;
          
          NSLog(@"base url: %@", baseURL);

          // remove trailing slash if exists
          if ([baseURL hasSuffix:@"/"]) {
              baseURL = [baseURL substringToIndex:baseURL.length - 1];
          }

          // append /api
          baseURL = [baseURL stringByAppendingString:@"/api"];
          NSLog(@"baseURL: %@", baseURL);
          [APIConfig setBaseURL:baseURL];
          [self requestProjectList];
          [self requestProfile];
        }
    }];
}

-(void) requestProfile {
  [APIClient requestProfile:^(BOOL success, NSDictionary *data, NSError *error) {
    
      // Save debug file
      NSString *plainText = [NSString stringWithFormat:@"%@", data];
      NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
      NSString *filePath = [docsPath stringByAppendingPathComponent:@"profile.txt"];
      [plainText writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
      NSLog(@"📁 profile saved as plain text to: %@", filePath);

      [self hideLoadingOverlay];
      self.isLoadingDashboard = NO;

      if (error || !data) {
          NSLog(@"❌ Project list API failed: %@", error);
          return;
      }

      if (data[@"status_code"]) {
          NSLog(@"❌ API status error: %@", data[@"message"]);
          return;
      }

      NSDictionary *appData = data[@"AppData"];
      if (![appData[@"status"] isEqualToString:@"success"]) {
          NSLog(@"❌ API failure: %@", appData[@"message"]);
          return;
      }

      NSDictionary *profile = data[@"Data"];
      if (![profile isKindOfClass:[NSDictionary class]]) {
          NSLog(@"❌ Invalid profile list format");
          return;
      }
    
      dispatch_async(dispatch_get_main_queue(), ^{
              NSDictionary *profileInfo = @{
                  @"name": profile[@"name"] ?: @"",
                  @"email": profile[@"email"] ?: @"",
                  @"avatar": profile[@"avatar"] ?: @""
              };
          NSLog(@"profile info ready to be used");
          [[NSNotificationCenter defaultCenter] postNotificationName:ProfileDidUpdateNotification
                                                              object:nil
                                                            userInfo:profileInfo];
      });
  }];
}

#pragma mark - Helper
- (void)onBack {
  [self.drawerController closeDrawer];
  
  [[NSNotificationCenter defaultCenter] postNotificationName:@"QmsDashboardDidCloseNotification" object:nil userInfo:@{@"status": @"closed"}];
}

- (void)handleMenuButtonTapped {
    NSLog(@"🍔 Menu button tapped");
    if (self.drawerController) {
        [self.drawerController toggleDrawer];
    } else {
        NSLog(@"⚠️ drawerController not set on DashboardViewController");
    }
}

- (BOOL)isReadyToLoadDashboard {
    return (
        self.ClientID.length > 0 &&
        self.ClientCode.length > 0 &&
        self.user_token.length > 0 &&
        ![self.ClientID isEqualToString:@"clientID_loading"] &&
        ![self.ClientCode isEqualToString:@"clientCode_loading"] &&
        ![self.user_token isEqualToString:@"userToken_loading"]
    );
}

- (void)checkIfReady {
    if ([self isReadyToLoadDashboard] && !self.didLoadDashboard && !self.isLoadingDashboard) {
        NSLog(@"✅ Dashboard ready!");

        self.didLoadDashboard = YES;

        [self checkAndRefreshAPIs];
    }
}

#pragma mark - prop setter
- (void)setClientID:(NSString *)ClientID {
    NSLog(@"🟨 ProjectVC setClientID: %@", ClientID);
    _ClientID = [ClientID copy];
    NSLog(@"🟢 ProjectViewController received ClientID: %@", _ClientID);

    [self checkIfReady];
}

- (void)setClientCode:(NSString *)ClientCode {
    NSLog(@"🟨 ProjectVC setClientCode: %@", ClientCode);
    _ClientCode = [ClientCode copy];
    NSLog(@"🟢 ProjectViewController received ClientCode: %@", _ClientCode);

    [self checkIfReady];
}

- (void)setUser_token:(NSString *)user_token {
    NSLog(@"🟨 ProjectVC setUser_token: %@", user_token);
    _user_token = [user_token copy];
    NSLog(@"🟢 ProjectViewController received user_token: %@", _user_token);

    [self checkIfReady];
}

@end
