//  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:0],
        [self.searchBar.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:16],
        [self.searchBar.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:-16],
        [self.searchBar.heightAnchor constraintEqualToConstant:72]
    ]];
}

- (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];
  
    UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 50)];
    footerLabel.text = @"All items displayed";
    footerLabel.textColor = UIColor.systemGrayColor;
    footerLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightMedium];
    footerLabel.textAlignment = NSTextAlignmentCenter;

    self.tableView.tableFooterView = footerLabel;

    [NSLayoutConstraint activateConstraints:@[
        [self.tableView.topAnchor constraintEqualToAnchor:self.searchBar.bottomAnchor constant:12],
        [self.tableView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:16],
        [self.tableView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:-16],
        [self.tableView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor constant:self.view.safeAreaInsets.bottom]
    ]];
}

- (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];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    // ---- 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 colorWithRed:0.0 green:0.5 blue:0.6 alpha:1.0];
    arrow.translatesAutoresizingMaskIntoConstraints = NO;

    // ---- Card styling ----
    UIView *cardView = [[UIView alloc] init];
    cardView.backgroundColor = UIColor.whiteColor;
    cardView.layer.cornerRadius = 12;
    cardView.layer.borderWidth = 1;
    cardView.layer.borderColor = UIColor.systemGray4Color.CGColor;
    cardView.translatesAutoresizingMaskIntoConstraints = NO;
    [cell.contentView addSubview:cardView];

    // Put label & arrow inside cardView
    [cardView addSubview:label];
    [cardView addSubview:arrow];

    // ---- Constraints ----
    [NSLayoutConstraint activateConstraints:@[
        // Cardview
        [cardView.topAnchor constraintEqualToAnchor:cell.contentView.topAnchor constant:8],   // vertical spacing top
        [cardView.bottomAnchor constraintEqualToAnchor:cell.contentView.bottomAnchor constant:-8], // vertical spacing bottom
        [cardView.leadingAnchor constraintEqualToAnchor:cell.contentView.leadingAnchor constant:0], // horizontal spacing
        [cardView.trailingAnchor constraintEqualToAnchor:cell.contentView.trailingAnchor constant:0],
        
        // 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 66;
}

- (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(@"lotid: %@", unit[@"lot_id"]);

    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.lotId = unit[@"lot_id"] ?: @"";
    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self.navigationController pushViewController:vc animated:YES];
}

@end
