//  UnitViewController.mm
#import "UnitViewController.h"
#import "DashboardViewController.h"
#import "APIConfig.h"

@interface UnitViewController () <UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate>

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

@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, copy) NSArray *filteredUnits;

@end

@implementation UnitViewController

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

    self.filteredUnits = self.units;
  
  if (self.filteredUnits.count == 1){
    NSDictionary *unit = self.filteredUnits.firstObject;
    
    dispatch_async(dispatch_get_main_queue(), ^{
      [self openUnit:unit];
    });
  }
  
    [self setupHeader];
    [self setupSearchBar];
    [self setupTableView];
}

- (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];
  
  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];
  
  self.titleLabel = [[UILabel alloc] init];
  self.titleLabel.text = self.projectName ?: @"";
  self.titleLabel.textColor = UIColor.whiteColor;
  self.titleLabel.font = [UIFont boldSystemFontOfSize:18];
  self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
  [self.headerView addSubview:self.titleLabel];
  
  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],
    
    [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],
    
    [self.titleLabel.centerXAnchor constraintEqualToAnchor:self.headerView.centerXAnchor],
    [self.titleLabel.centerYAnchor constraintEqualToAnchor:self.headerView.centerYAnchor],
  ]];
}

#pragma mark - Search Bar
- (void)setupSearchBar {
    self.searchBar = [[UISearchBar alloc] init];
    self.searchBar.placeholder = @"Search";
    self.searchBar.searchBarStyle = UISearchBarStyleMinimal;
    self.searchBar.delegate = self;
    self.searchBar.translatesAutoresizingMaskIntoConstraints = NO;

    [self.view addSubview:self.searchBar];

    [NSLayoutConstraint activateConstraints:@[
        [self.searchBar.topAnchor constraintEqualToAnchor:self.headerView.bottomAnchor constant:8],
        [self.searchBar.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:16],
        [self.searchBar.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:-16],
        [self.searchBar.heightAnchor constraintEqualToConstant:44]
    ]];
}

- (void)searchBar:(UISearchBar *)searchBar
    textDidChange:(NSString *)searchText {

    if (searchText.length == 0) {
        self.filteredUnits = self.units;
    } else {
        NSPredicate *predicate =
        [NSPredicate predicateWithBlock:^BOOL(NSDictionary *unit, NSDictionary *bindings) {
            NSString *name = unit[@"unit"] ?: @"";
            return [name localizedCaseInsensitiveContainsString:searchText];
        }];

        self.filteredUnits = [self.units filteredArrayUsingPredicate:predicate];
    }

    [self.tableView reloadData];
}

#pragma mark - Table View
- (void)setupTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero
                                                  style:UITableViewStylePlain];
    self.tableView.translatesAutoresizingMaskIntoConstraints = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;

    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = UIColor.systemBackgroundColor;

    [self.tableView registerClass:UITableViewCell.class
           forCellReuseIdentifier:@"UnitCell"];

    [self.view addSubview:self.tableView];

    [NSLayoutConstraint activateConstraints:@[
        [self.tableView.topAnchor constraintEqualToAnchor:self.searchBar.bottomAnchor constant:8],
        [self.tableView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.tableView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.tableView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor]
    ]];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.filteredUnits.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell =
        [tableView dequeueReusableCellWithIdentifier:@"UnitCell"
                                        forIndexPath:indexPath];

    // ---- Reset reused cell ----
    for (UIView *subview in cell.contentView.subviews) {
        [subview removeFromSuperview];
    }

    NSDictionary *unit = self.filteredUnits[indexPath.row];

    // ---- Label ----
    UILabel *label = [[UILabel alloc] init];
    label.text = unit[@"unit"] ?: unit[@"name"] ?: @"";
    label.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
    label.translatesAutoresizingMaskIntoConstraints = NO;

    // ---- Arrow ----
    UIImageView *arrow = [[UIImageView alloc] initWithImage:
        [UIImage systemImageNamed:@"chevron.right"]];
    arrow.tintColor = UIColor.systemGrayColor;
    arrow.translatesAutoresizingMaskIntoConstraints = NO;

    // ---- Card styling ----
    cell.backgroundColor = UIColor.clearColor;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    cell.contentView.backgroundColor = UIColor.whiteColor;
    cell.contentView.layer.cornerRadius = 12;
    cell.contentView.layer.borderWidth = 1;
    cell.contentView.layer.borderColor = UIColor.systemGray4Color.CGColor;
    cell.contentView.clipsToBounds = YES;

    // ---- Add views ----
    [cell.contentView addSubview:label];
    [cell.contentView addSubview:arrow];

    // ---- Constraints ----
    [NSLayoutConstraint activateConstraints:@[
        // Label
        [label.leadingAnchor constraintEqualToAnchor:cell.contentView.leadingAnchor constant:16],
        [label.centerYAnchor constraintEqualToAnchor:cell.contentView.centerYAnchor],
        [label.trailingAnchor constraintEqualToAnchor:arrow.leadingAnchor constant:-8],

        // Arrow
        [arrow.trailingAnchor constraintEqualToAnchor:cell.contentView.trailingAnchor constant:-12],
        [arrow.centerYAnchor constraintEqualToAnchor:cell.contentView.centerYAnchor],
        [arrow.widthAnchor constraintEqualToConstant:12],
        [arrow.heightAnchor constraintEqualToConstant:18],
    ]];

    return cell;
}

- (void)tableView:(UITableView *)tableView
  willDisplayCell:(UITableViewCell *)cell
forRowAtIndexPath:(NSIndexPath *)indexPath {

    cell.contentView.frame =
        CGRectInset(cell.contentView.frame, 16, 8);
}

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

- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    NSDictionary *unit = self.filteredUnits[indexPath.row];
    NSLog(@"🏠 Selected unit: %@", unit[@"unit"]);

    [self openUnit:unit];
}

#pragma mark - Helper
- (void)onBack {
  [self.navigationController popViewControllerAnimated:YES];
}

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

- (void)openUnit:(NSDictionary *)unit {
    NSLog(@"🏠 Auto-opening unit: %@", unit[@"unit"]);
    NSString *projectId = [unit[@"project_id"] description];
    NSString *drawingPlanId = [unit[@"id"] description];
    [APIConfig setDrawingPlanId:drawingPlanId];

    NSLog(@"self.projectLogo: %@", self.projectLogo);
    DashboardViewController *vc = [[DashboardViewController alloc] init];
    vc.projectCode = unit[@"name"] ?: @"";
    vc.projectName = self.projectName;
    vc.projectId = projectId ?: @"";
    vc.drawingPlanId = drawingPlanId ?: @"";
    vc.drawerController = self.drawerController;
    vc.projectLogo = self.projectLogo;
    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self.navigationController pushViewController:vc animated:YES];
}

@end
