//  ManageAccountViewController.mm

#import "ManageAccountViewController.h"

@interface ManageAccountViewController () <UITableViewDelegate, UITableViewDataSource>

// Header
@property (nonatomic, strong) UIView *headerBar;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *backButton;

// Table
@property (nonatomic, strong) UITableView *accountTable;

@property (nonatomic, strong) UIView *dimmedOverlay;
@property (nonatomic, strong) UIView *addLinkSheet;

@property (nonatomic, strong) UIView *footerView;

@end

@implementation ManageAccountViewController

#pragma mark - Init with accounts
- (instancetype)initWithAccounts:(NSArray<NSDictionary *> *)accounts {
    self = [super init];
    if (self) {
        _accounts = accounts;
    }
    return self;
}

#pragma mark - View Lifecycle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;
    
    [self setupHeader];
    [self setupFooter];
    [self setupTable];
}

#pragma mark - Header
- (void)setupHeader {
    UILayoutGuide *safe = self.view.safeAreaLayoutGuide;
    
    self.headerBar = [[UIView alloc] init];
    self.headerBar.backgroundColor = [UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0];
    self.headerBar.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.headerBar];
    
    [NSLayoutConstraint activateConstraints:@[
        [self.headerBar.topAnchor constraintEqualToAnchor:safe.topAnchor],
        [self.headerBar.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.headerBar.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.headerBar.heightAnchor constraintEqualToConstant:44],
    ]];
    
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.text = @"Manage Accounts";
    self.titleLabel.font = [UIFont systemFontOfSize:18 weight:UIFontWeightMedium];
    self.titleLabel.textColor = UIColor.whiteColor;
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    
    self.backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.backButton setImage:[UIImage systemImageNamed:@"chevron.backward"] forState:UIControlStateNormal];
    self.backButton.tintColor = UIColor.whiteColor;
    [self.backButton addTarget:self action:@selector(onBack) forControlEvents:UIControlEventTouchUpInside];
    
    for (UIView *sub in @[self.titleLabel, self.backButton]) {
        sub.translatesAutoresizingMaskIntoConstraints = NO;
        [self.headerBar addSubview:sub];
    }
    
    [NSLayoutConstraint activateConstraints:@[
        [self.backButton.leadingAnchor constraintEqualToAnchor:self.headerBar.leadingAnchor constant:16],
        [self.backButton.centerYAnchor constraintEqualToAnchor:self.headerBar.centerYAnchor],
        [self.backButton.widthAnchor constraintEqualToConstant:24],
        [self.backButton.heightAnchor constraintEqualToConstant:24],
        
        [self.titleLabel.centerXAnchor constraintEqualToAnchor:self.headerBar.centerXAnchor],
        [self.titleLabel.centerYAnchor constraintEqualToAnchor:self.headerBar.centerYAnchor],
    ]];
}

- (void)onBack {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - Table
- (void)setupTable {
    self.accountTable = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.accountTable.delegate = self;
    self.accountTable.dataSource = self;
    self.accountTable.rowHeight = UITableViewAutomaticDimension;
    self.accountTable.estimatedRowHeight = 110;
    self.accountTable.tableFooterView = [UIView new];
    self.accountTable.translatesAutoresizingMaskIntoConstraints = NO;
    
    [self.view addSubview:self.accountTable];
    
    [NSLayoutConstraint activateConstraints:@[
        [self.accountTable.topAnchor constraintEqualToAnchor:self.headerBar.bottomAnchor],
        [self.accountTable.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.accountTable.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.accountTable.bottomAnchor constraintEqualToAnchor:self.footerView.topAnchor],
    ]];
}

#pragma mark - Table DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.accounts.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *account = self.accounts[indexPath.row];
    return [self accountCellForTable:tableView atIndexPath:indexPath withData:account];
}

#pragma mark - Table Cell Setup
- (UITableViewCell *)accountCellForTable:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath withData:(NSDictionary *)account {
    static NSString *cellId = @"AccountCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        [self setupAccountCellSubviews:cell];
    }
    
    [self configureAccountCell:cell withData:account];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)setupAccountCellSubviews:(UITableViewCell *)cell {
    UIImageView *profileImageView = [[UIImageView alloc] init];
    profileImageView.tag = 1000;
    profileImageView.layer.cornerRadius = 20;
    profileImageView.clipsToBounds = YES;
    profileImageView.backgroundColor = UIColor.systemGray4Color;
    profileImageView.translatesAutoresizingMaskIntoConstraints = NO;
    [cell.contentView addSubview:profileImageView];
    
    UILabel *nameLabel = [[UILabel alloc] init];
    nameLabel.tag = 1001;
    nameLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightSemibold];
    nameLabel.translatesAutoresizingMaskIntoConstraints = NO;
    
    UILabel *companyLabel = [[UILabel alloc] init];
    companyLabel.tag = 1002;
    companyLabel.font = [UIFont systemFontOfSize:13];
    companyLabel.textColor = UIColor.systemGrayColor;
    companyLabel.translatesAutoresizingMaskIntoConstraints = NO;
    
    UILabel *dotLabel = [[UILabel alloc] init];
    dotLabel.text = @"·";
    dotLabel.tag = 1003;
    dotLabel.font = [UIFont systemFontOfSize:13];
    dotLabel.textColor = UIColor.systemGray3Color;
    dotLabel.translatesAutoresizingMaskIntoConstraints = NO;
    
    UILabel *userLabel = [[UILabel alloc] init];
    userLabel.tag = 1004;
    userLabel.font = [UIFont systemFontOfSize:13];
    userLabel.textColor = UIColor.systemGrayColor;
    userLabel.translatesAutoresizingMaskIntoConstraints = NO;
    
    for (UIView *sub in @[nameLabel, companyLabel, dotLabel, userLabel]) {
        [cell.contentView addSubview:sub];
    }
  
    UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [deleteButton setTitle:@"Remove from Device" forState:UIControlStateNormal];
    [deleteButton setTitleColor:UIColor.systemRedColor forState:UIControlStateNormal];
    deleteButton.tintColor = UIColor.systemRedColor;
    deleteButton.layer.borderWidth = 0.5;
    deleteButton.layer.borderColor = UIColor.systemRedColor.CGColor;
    deleteButton.layer.cornerRadius = 12;
    deleteButton.titleLabel.font = [UIFont systemFontOfSize:13 weight:UIFontWeightRegular];
    deleteButton.translatesAutoresizingMaskIntoConstraints = NO;
    deleteButton.tag = 1005;
    [deleteButton addTarget:self action:@selector(deleteButtonTapped:)
           forControlEvents:UIControlEventTouchUpInside];

    [cell.contentView addSubview:deleteButton];
    
    [NSLayoutConstraint activateConstraints:@[
        [profileImageView.leadingAnchor constraintEqualToAnchor:cell.contentView.leadingAnchor constant:16],
        [profileImageView.topAnchor constraintEqualToAnchor:cell.contentView.topAnchor constant:16],
        [profileImageView.widthAnchor constraintEqualToConstant:40],
        [profileImageView.heightAnchor constraintEqualToConstant:40],
        
        [nameLabel.topAnchor constraintEqualToAnchor:cell.contentView.topAnchor constant:16],
        [nameLabel.leadingAnchor constraintEqualToAnchor:profileImageView.trailingAnchor constant:12],
        [nameLabel.trailingAnchor constraintLessThanOrEqualToAnchor:cell.contentView.trailingAnchor constant:-16],
        
        [companyLabel.topAnchor constraintEqualToAnchor:nameLabel.bottomAnchor constant:4],
        [companyLabel.leadingAnchor constraintEqualToAnchor:nameLabel.leadingAnchor],
        
        [dotLabel.centerYAnchor constraintEqualToAnchor:companyLabel.centerYAnchor],
        [dotLabel.leadingAnchor constraintEqualToAnchor:companyLabel.trailingAnchor constant:6],
        
        [userLabel.centerYAnchor constraintEqualToAnchor:companyLabel.centerYAnchor],
        [userLabel.leadingAnchor constraintEqualToAnchor:dotLabel.trailingAnchor constant:6],
        [userLabel.trailingAnchor constraintLessThanOrEqualToAnchor:cell.contentView.trailingAnchor constant:-16],
        
        [deleteButton.topAnchor constraintEqualToAnchor:userLabel.bottomAnchor constant:12],
        [deleteButton.trailingAnchor constraintEqualToAnchor:cell.contentView.trailingAnchor constant:-16],
        [deleteButton.leadingAnchor constraintEqualToAnchor:cell.contentView.leadingAnchor constant:16],
        [deleteButton.heightAnchor constraintEqualToConstant:36],
        [deleteButton.bottomAnchor constraintEqualToAnchor:cell.contentView.bottomAnchor constant:-12], // ⭐ THIS
    ]];
}

- (void)configureAccountCell:(UITableViewCell *)cell withData:(NSDictionary *)account {
    UILabel *nameLabel = [cell.contentView viewWithTag:1001];
    UILabel *companyLabel = [cell.contentView viewWithTag:1002];
    UILabel *userLabel = [cell.contentView viewWithTag:1004];
    
    nameLabel.text = account[@"name"];
    companyLabel.text = account[@"company_code"];
    userLabel.text = account[@"userName"];
}

- (void)deleteButtonTapped:(UIButton *)sender {
    // Get the cell from the button
    UITableViewCell *cell = (UITableViewCell *)sender.superview.superview;
    NSIndexPath *indexPath = [self.accountTable indexPathForCell:cell];
    
    if (indexPath) {
        NSMutableArray *mutableAccounts = [self.accounts mutableCopy];
        NSDictionary *deletedAccount = mutableAccounts[indexPath.row];
        [mutableAccounts removeObjectAtIndex:indexPath.row];
        self.accounts = [mutableAccounts copy];

        // Animate deletion
        [self.accountTable deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        NSLog(@"Deleted account: %@", deletedAccount[@"name"]);
    }
}

#pragma mark - Footer Button
-(void)setupFooter {
    self.footerView = [[UIView alloc] init];
    self.footerView.backgroundColor = UIColor.clearColor;
    [self.view addSubview:self.footerView];
    self.footerView.translatesAutoresizingMaskIntoConstraints = NO;

    [NSLayoutConstraint activateConstraints:@[
        [self.footerView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.footerView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.footerView.bottomAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.bottomAnchor],
        [self.footerView.heightAnchor constraintEqualToConstant:64],
    ]];
  
    UIButton *footerButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [footerButton setTitle:@"Add Account" forState:UIControlStateNormal];
    footerButton.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    footerButton.backgroundColor = [UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0];
    footerButton.tintColor = UIColor.whiteColor;
    footerButton.layer.cornerRadius = 12;
    [footerButton addTarget:self action:@selector(addAccountsTapped)
           forControlEvents:UIControlEventTouchUpInside];

    [self.footerView addSubview:footerButton];
    footerButton.translatesAutoresizingMaskIntoConstraints = NO;

    [NSLayoutConstraint activateConstraints:@[
        [footerButton.bottomAnchor constraintEqualToAnchor:self.footerView.safeAreaLayoutGuide.bottomAnchor],
        [footerButton.centerXAnchor constraintEqualToAnchor:self.footerView.centerXAnchor],
        [footerButton.heightAnchor constraintEqualToConstant:48],
        [footerButton.leadingAnchor constraintEqualToAnchor:self.footerView.leadingAnchor constant:20],
        [footerButton.trailingAnchor constraintEqualToAnchor:self.footerView.trailingAnchor constant:-20],
    ]];
}

#pragma mark - Add Account
- (void)dismissAddLinkSheet:(void(^)(void))completion {
    [UIView animateWithDuration:0.3 animations:^{
        self.addLinkSheet.transform = CGAffineTransformMakeTranslation(0, 300);
        self.dimmedOverlay.alpha = 0;
    } completion:^(BOOL finished) {
        [self.addLinkSheet removeFromSuperview];
        [self.dimmedOverlay removeFromSuperview];
        if (completion) completion();
    }];
}

- (void)dismissAddLinkSheetButtonTapped:(id)sender {
    [self dismissAddLinkSheet:nil]; // no completion needed
}

- (UIView *)buildDimmedOverlay {
    UIView *overlay = [[UIView alloc] initWithFrame:self.view.bounds];
    overlay.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
    overlay.alpha = 0;
    overlay.userInteractionEnabled = YES;

    // Tap to dismiss
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                          action:@selector(dismissAddLinkSheetButtonTapped:)];
    tap.cancelsTouchesInView = NO; // <-- allow touches to pass to sheet buttons
    [overlay addGestureRecognizer:tap];

    return overlay;
}

-(void)addAccountsTapped{
  NSLog(@"Add Accounts Tapped");
  [self dismissAddLinkSheet:^{
      // now fully dismissed, safe to show new sheet
      self.dimmedOverlay = [self buildDimmedOverlay];
      self.addLinkSheet = [self addAccountSheet];

      [self.view addSubview:self.dimmedOverlay];
      [self.view addSubview:self.addLinkSheet];

      NSLayoutConstraint *bottom = [self.addLinkSheet.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor constant:300];
      bottom.active = YES;

      [NSLayoutConstraint activateConstraints:@[
          [self.addLinkSheet.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
          [self.addLinkSheet.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
          [self.addLinkSheet.heightAnchor constraintEqualToConstant:250],
      ]];

      [self.view layoutIfNeeded];

      [UIView animateWithDuration:0.3 animations:^{
          self.dimmedOverlay.alpha = 1;
          bottom.constant = 0;
          [self.view layoutIfNeeded];
      }];
  }];
}

- (UIView *)addAccountSheet {
    UIView *sheet = [[UIView alloc] init];
    sheet.backgroundColor = UIColor.whiteColor;
    sheet.layer.cornerRadius = 24;
    sheet.layer.maskedCorners = kCALayerMinXMinYCorner | kCALayerMaxXMinYCorner;
    sheet.translatesAutoresizingMaskIntoConstraints = NO;

    UIView *header = [[UIView alloc] init];
    header.translatesAutoresizingMaskIntoConstraints = NO;
    [sheet addSubview:header];

    UILabel *title = [[UILabel alloc] init];
    title.text = @"Add Account";
    title.font = [UIFont systemFontOfSize:18 weight:UIFontWeightBold];
    title.translatesAutoresizingMaskIntoConstraints = NO;

//    UIButton *closeButton = [UIButton buttonWithType:UIButtonTypeSystem];
//    [closeButton setImage:[UIImage systemImageNamed:@"xmark"] forState:UIControlStateNormal];
//    closeButton.tintColor = UIColor.systemGrayColor;
//    [closeButton addTarget:self action:@selector(dismissAddLinkSheetButtonTapped:)
//          forControlEvents:UIControlEventTouchUpInside];
//    closeButton.translatesAutoresizingMaskIntoConstraints = NO;

    [header addSubview:title];
//    [header addSubview:closeButton];

    UILabel *subtitle = [[UILabel alloc] init];
    subtitle.text = @"Select an option to proceed.";
    subtitle.font = [UIFont systemFontOfSize:14];
    subtitle.textAlignment = NSTextAlignmentLeft;
    subtitle.numberOfLines = 0;
    subtitle.textColor = UIColor.darkGrayColor;
    subtitle.translatesAutoresizingMaskIntoConstraints = NO;
    [sheet addSubview:subtitle];
  
    UIView *spacer1 = [[UIView alloc] init];
    spacer1.translatesAutoresizingMaskIntoConstraints = NO;
    spacer1.layer.borderWidth = 0.5;
    spacer1.layer.borderColor = [UIColor lightGrayColor].CGColor;
    [sheet addSubview:spacer1];

    // --- Existing Account ---
    UIView *existingAccount = [[UIView alloc] init];
    existingAccount.translatesAutoresizingMaskIntoConstraints = NO;
    [sheet addSubview:existingAccount];

    UILabel *existingTitle = [[UILabel alloc] init];
    existingTitle.text = @"Add Existing Account";
    existingTitle.font = [UIFont systemFontOfSize:16 weight:UIFontWeightBold];
    existingTitle.translatesAutoresizingMaskIntoConstraints = NO;

    UIButton *existingButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [existingButton setImage:[UIImage systemImageNamed:@"plus"] forState:UIControlStateNormal];
    existingButton.tintColor = UIColor.systemGrayColor;
    [existingButton addTarget:self action:@selector(existingButtonTapped)
          forControlEvents:UIControlEventTouchUpInside];
    existingButton.translatesAutoresizingMaskIntoConstraints = NO;

    [existingAccount addSubview:existingTitle];
    [existingAccount addSubview:existingButton];
  
    UIView *spacer2 = [[UIView alloc] init];
    spacer2.translatesAutoresizingMaskIntoConstraints = NO;
    spacer2.layer.borderWidth = 0.5;
    spacer2.layer.borderColor = [UIColor lightGrayColor].CGColor;
    [sheet addSubview:spacer2];
  
    // --- New Account ---
    UIView *newAccount = [[UIView alloc] init];
    newAccount.translatesAutoresizingMaskIntoConstraints = NO;
    [sheet addSubview:newAccount];

    UILabel *newTitle = [[UILabel alloc] init];
    newTitle.text = @"Add New Account";
    newTitle.font = [UIFont systemFontOfSize:16 weight:UIFontWeightBold];
    newTitle.translatesAutoresizingMaskIntoConstraints = NO;

    UIButton *newButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [newButton setImage:[UIImage systemImageNamed:@"plus"] forState:UIControlStateNormal];
    newButton.tintColor = UIColor.systemGrayColor;
    [newButton addTarget:self action:@selector(newButtonTapped)
          forControlEvents:UIControlEventTouchUpInside];
    newButton.translatesAutoresizingMaskIntoConstraints = NO;

    [newAccount addSubview:newTitle];
    [newAccount addSubview:newButton];
  
    [NSLayoutConstraint activateConstraints:@[
        [header.topAnchor constraintEqualToAnchor:sheet.topAnchor constant:24],
        [header.leadingAnchor constraintEqualToAnchor:sheet.leadingAnchor constant:20],
        [header.trailingAnchor constraintEqualToAnchor:sheet.trailingAnchor constant:-20],

        [title.leadingAnchor constraintEqualToAnchor:header.leadingAnchor],
        [title.topAnchor constraintEqualToAnchor:header.topAnchor],

//        [closeButton.trailingAnchor constraintEqualToAnchor:header.trailingAnchor],
//        [closeButton.centerYAnchor constraintEqualToAnchor:title.centerYAnchor],
//        [closeButton.heightAnchor constraintEqualToConstant:24],
//        [closeButton.widthAnchor constraintEqualToConstant:24],

        [subtitle.topAnchor constraintEqualToAnchor:title.bottomAnchor constant:12],
        [subtitle.leadingAnchor constraintEqualToAnchor:sheet.leadingAnchor constant:20],
        [subtitle.trailingAnchor constraintEqualToAnchor:sheet.trailingAnchor constant:-20],
        
        [spacer1.topAnchor constraintEqualToAnchor:subtitle.bottomAnchor constant:20],
        [spacer1.leadingAnchor constraintEqualToAnchor:sheet.leadingAnchor],
        [spacer1.trailingAnchor constraintEqualToAnchor:sheet.trailingAnchor],
        [spacer1.heightAnchor constraintEqualToConstant:1],
        
        [existingAccount.topAnchor constraintEqualToAnchor:spacer1.bottomAnchor constant:20],
        [existingAccount.leadingAnchor constraintEqualToAnchor:sheet.leadingAnchor constant:16],
        [existingAccount.trailingAnchor constraintEqualToAnchor:sheet.trailingAnchor constant:-16],
        
        [existingTitle.topAnchor constraintEqualToAnchor:existingAccount.topAnchor],
        [existingTitle.leadingAnchor constraintEqualToAnchor:existingAccount.leadingAnchor],
        [existingTitle.trailingAnchor constraintEqualToAnchor:existingButton.leadingAnchor constant:-16],
        
        [existingButton.centerYAnchor constraintEqualToAnchor:existingTitle.centerYAnchor],
        [existingButton.trailingAnchor constraintEqualToAnchor:existingAccount.trailingAnchor],
        [existingButton.heightAnchor constraintEqualToConstant:24],
        [existingButton.widthAnchor constraintEqualToConstant:24],

        [spacer2.topAnchor constraintEqualToAnchor:existingButton.bottomAnchor constant:18],
        [spacer2.leadingAnchor constraintEqualToAnchor:sheet.leadingAnchor constant:16],
        [spacer2.trailingAnchor constraintEqualToAnchor:sheet.trailingAnchor constant:-16],
        [spacer2.heightAnchor constraintEqualToConstant:1],
        
        [newAccount.topAnchor constraintEqualToAnchor:spacer2.bottomAnchor constant:18],
        [newAccount.leadingAnchor constraintEqualToAnchor:sheet.leadingAnchor constant:16],
        [newAccount.trailingAnchor constraintEqualToAnchor:sheet.trailingAnchor constant:-16],
        
        [newTitle.topAnchor constraintEqualToAnchor:newAccount.topAnchor],
        [newTitle.leadingAnchor constraintEqualToAnchor:newAccount.leadingAnchor],
        [newTitle.trailingAnchor constraintEqualToAnchor:newButton.leadingAnchor constant:-16],
        
        [newButton.centerYAnchor constraintEqualToAnchor:newTitle.centerYAnchor],
        [newButton.trailingAnchor constraintEqualToAnchor:newAccount.trailingAnchor],
        [newButton.heightAnchor constraintEqualToConstant:24],
        [newButton.widthAnchor constraintEqualToConstant:24],
    ]];
    return sheet;
}

-(void)existingButtonTapped{
  NSLog(@"existing account button tapped");
}

-(void)newButtonTapped {
  NSLog(@"new account button tapped");
}

@end
