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

@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:20];
        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;

@end

@implementation ProjectViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.systemBackgroundColor;
    [self requestProjectList];
    [self requestCompanyCode];
    [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;
}

#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];

  [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:48],
    
    [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 = 16;
    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:8],
        [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
    cell.imageView.image = [UIImage systemImageNamed:@"photo"];
    
    NSDictionary *project = self.projects[indexPath.item];
    
    // Project name
    id projectName = project[@"project_name"];
    cell.nameLabel.text = [projectName isKindOfClass:[NSString class]] ? projectName : @"";

    // Get logo URL safely
    NSString *logo = project[@"logo"];
    NSString *thumb = project[@"logo_thumbnail"];

    NSString *logoURLString = (logo.length > 0) ? logo :
                              (thumb.length > 0) ? thumb : nil;


    NSURL *url = [NSURL URLWithString:logoURLString ?: @""];

    // Async load image safely
    if (url) {
        NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url
                                                                 completionHandler:^(NSData * _Nullable data,
                                                                                     NSURLResponse * _Nullable response,
                                                                                     NSError * _Nullable error) {
            UIImage *image = data ? [UIImage imageWithData:data] : nil;
            if (!image) return; // leave placeholder
            
            dispatch_async(dispatch_get_main_queue(), ^{
                // Only update if the cell is still visible at this indexPath
                ProjectCardCell *updateCell = (ProjectCardCell *)[collectionView cellForItemAtIndexPath:indexPath];
                if (updateCell) {
                    updateCell.imageView.image = image;
                }
            });
        }];
        [task resume];
    }

    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *project = self.projects[indexPath.item];
  
    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 = 200; // OG-style banner height

    return CGSizeMake(width, height);
}

#pragma mark - API
- (void)requestProjectList {
    [APIClient requestProjectList:^(BOOL success, NSDictionary *data, NSError *error) {
      
        // debug
        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);

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

        // RN parity: status_code check
        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;
        }
      
        if (!error) {
            self.projects = projects;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.collectionView reloadData];
                if (self.projects.count == 1) {
                    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];
                    
                    [self collectionView:self.collectionView didSelectItemAtIndexPath:indexPath];
                }
            });
        }
    }];
}

- (void)requestCompanyCode {
  [APIClient requestCompanyCode:@"kita" 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);

        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;
        }

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

          // 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];
        }
    }];
}

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

@end
