//  ThirdPartyViewController.mm
#import "ThirdPartyViewController.h"
#import "ThirdTutorialViewController.h"
#import "ThirdDetailsViewController.h"
#import "APIClient.h"

@interface ThirdPartyCell : UITableViewCell
- (void)configureWithItem:(NSDictionary *)item;
@end

@interface ThirdPartyCell ()
// Container
@property (nonatomic, strong) UIView *cardView;

// Left
@property (nonatomic, strong) UIImageView *statusIcon;

// Center
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *statusBadge;

// Right
@property (nonatomic, strong) UIImageView *arrowIcon;
@end

@implementation ThirdPartyCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style
              reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.backgroundColor = UIColor.clearColor;
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        [self setupUI];
    }
    return self;
}

- (void)setupUI {

    // Card container
    self.cardView = [[UIView alloc] init];
    self.cardView.backgroundColor = UIColor.whiteColor;
    self.cardView.layer.cornerRadius = 24;
    self.cardView.layer.masksToBounds = YES;
    self.cardView.translatesAutoresizingMaskIntoConstraints = NO;
    self.cardView.layer.borderWidth = 0.5;
    self.cardView.layer.borderColor = UIColor.lightGrayColor.CGColor;

    [self.contentView addSubview:self.cardView];

    // Status icon
    self.statusIcon = [[UIImageView alloc] init];
    self.statusIcon.contentMode = UIViewContentModeScaleAspectFit;
    self.statusIcon.translatesAutoresizingMaskIntoConstraints = NO;

    // Title
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightBold];
    self.titleLabel.textColor = [UIColor colorWithWhite:0.2 alpha:1.0];
    self.titleLabel.numberOfLines = 2;
    self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;

    // Status badge
    self.statusBadge = [[UILabel alloc] init];
    self.statusBadge.font = [UIFont systemFontOfSize:13];
    self.statusBadge.textColor = UIColor.whiteColor;
    self.statusBadge.textAlignment = NSTextAlignmentCenter;
    self.statusBadge.layer.cornerRadius = 14;
    self.statusBadge.layer.masksToBounds = YES;
    self.statusBadge.translatesAutoresizingMaskIntoConstraints = NO;

    // Arrow
    self.arrowIcon = [[UIImageView alloc] initWithImage:
        [UIImage systemImageNamed:@"chevron.right"]];
    self.arrowIcon.tintColor = [UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0];
    self.arrowIcon.translatesAutoresizingMaskIntoConstraints = NO;

    for (UIView *v in @[self.statusIcon, self.titleLabel, self.statusBadge, self.arrowIcon]) {
        [self.cardView addSubview:v];
    }

    // Constraints
    [NSLayoutConstraint activateConstraints:@[

        // Card
        [self.cardView.topAnchor constraintEqualToAnchor:self.contentView.topAnchor constant:10],
        [self.cardView.bottomAnchor constraintEqualToAnchor:self.contentView.bottomAnchor],
        [self.cardView.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],
        [self.cardView.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-16],
        [self.cardView.heightAnchor constraintEqualToConstant:98],

        // Status icon
        [self.statusIcon.leadingAnchor constraintEqualToAnchor:self.cardView.leadingAnchor constant:16],
        [self.statusIcon.topAnchor constraintEqualToAnchor:self.cardView.topAnchor constant:16],
        [self.statusIcon.widthAnchor constraintEqualToConstant:24],
        [self.statusIcon.heightAnchor constraintEqualToConstant:24],

        // Arrow
        [self.arrowIcon.trailingAnchor constraintEqualToAnchor:self.cardView.trailingAnchor constant:-16],
        [self.arrowIcon.centerYAnchor constraintEqualToAnchor:self.cardView.centerYAnchor],
        [self.arrowIcon.widthAnchor constraintEqualToConstant:24],
        [self.arrowIcon.heightAnchor constraintEqualToConstant:24],

        // Title
        [self.titleLabel.leadingAnchor constraintEqualToAnchor:self.statusIcon.trailingAnchor constant:16],
        [self.titleLabel.trailingAnchor constraintEqualToAnchor:self.arrowIcon.leadingAnchor constant:-12],
        [self.titleLabel.topAnchor constraintEqualToAnchor:self.cardView.topAnchor constant:16],

        // Status badge
        [self.statusBadge.leadingAnchor constraintEqualToAnchor:self.statusIcon.leadingAnchor],
        [self.statusBadge.topAnchor constraintEqualToAnchor:self.titleLabel.bottomAnchor constant:12],
        [self.statusBadge.widthAnchor constraintEqualToConstant:104],
        [self.statusBadge.heightAnchor constraintEqualToConstant:28],
    ]];
}

- (void)configureWithItem:(NSDictionary *)item {

    NSString *title = item[@"title"] ?: @"";
    self.titleLabel.text = title;

    BOOL isActive = [item[@"status"] integerValue] == 1;

    // Status icon
    NSBundle *bundle = [NSBundle bundleForClass:[self class]];
    self.statusIcon.image = [UIImage imageNamed:
        (isActive ? @"icon_green_active" : @"icon_red_blocked")
                                   inBundle:bundle
              compatibleWithTraitCollection:nil];
  
    // Status badge
    self.statusBadge.text = isActive ? @"Active" : @"Blocked";
    self.statusBadge.backgroundColor = isActive
        ? [UIColor colorWithRed:0.2 green:0.74 blue:0.29 alpha:1.0]   // #32BC4A
        : [UIColor colorWithRed:1.0 green:0.39 blue:0.39 alpha:1.0]; // #FF6464
}

@end


@interface ThirdPartyViewController () <UITableViewDelegate, UITableViewDataSource>
// Header (existing)
@property (nonatomic, strong) UIView *headerBar;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *backButton;
@property (nonatomic, strong) UIButton *helpButton;

// Content
@property (nonatomic, strong) UIView *offlineBanner;
@property (nonatomic, strong) UITextField *searchField;
@property (nonatomic, strong) UITableView *tableView;

// Floating button
@property (nonatomic, strong) UIButton *addButton;

// Data
@property (nonatomic, strong) NSMutableArray *items;
@property (nonatomic, strong) NSMutableArray *filteredItems;

// State
@property (nonatomic, assign) BOOL isLoading;
@property (nonatomic, assign) BOOL isRefreshing;
@property (nonatomic, assign) BOOL showAddModal;
@property (nonatomic, assign) BOOL showSuccessModal;

// Add Link Bottom Sheet
@property (nonatomic, strong) UIView *dimmedOverlay;
@property (nonatomic, strong) UIView *addLinkSheet;
@property (nonatomic, strong) UITextField *linkNameField;
@property (nonatomic, strong) UIButton *createButton;

// Success Modal
@property (nonatomic, strong) UIView *successOverlay;
@property (nonatomic, strong) UIView *successModal;

@end

@implementation ThirdPartyViewController

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

    self.items = [NSMutableArray array];
    self.filteredItems = [NSMutableArray array];

    [self setupHeader];
//    [self setupOfflineBanner];
    [self setupSearchBar];
    [self setupAddButton];
    [self setupTableView];
    [self requestThirdPartyList];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    // Refresh your list every time the view appears
    [self requestThirdPartyList];
}


#pragma mark - Header
- (void)setupHeader {
  UILayoutGuide *safe = self.view.safeAreaLayoutGuide;
  
  //Header
  self.headerBar = [[UIView alloc] init];
  self.headerBar.backgroundColor = [UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0];
  [self.view addSubview:self.headerBar];
  self.headerBar.translatesAutoresizingMaskIntoConstraints = NO;
  
  [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],
  ]];
  
  // Title
  self.titleLabel = [[UILabel alloc] init];
  self.titleLabel.text = @"3rd Party Link";
  self.titleLabel.textColor = UIColor.whiteColor;
  self.titleLabel.font = [UIFont systemFontOfSize:18 weight:UIFontWeightMedium];
  self.titleLabel.textAlignment = NSTextAlignmentCenter;
  
  // Back button
  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.heightAnchor constraintEqualToConstant:24],
    [self.backButton.widthAnchor constraintEqualToConstant:24],
    
    [self.titleLabel.centerXAnchor constraintEqualToAnchor:self.headerBar.centerXAnchor],
    [self.titleLabel.centerYAnchor constraintEqualToAnchor:self.headerBar.centerYAnchor],
  ]];
  
  self.helpButton = [UIButton buttonWithType:UIButtonTypeSystem];
  self.helpButton.translatesAutoresizingMaskIntoConstraints = NO;
  [self.helpButton setImage:[UIImage systemImageNamed:@"questionmark.circle"] forState:UIControlStateNormal];
  self.helpButton.tintColor = UIColor.whiteColor;
  [self.helpButton addTarget:self
                      action:@selector(showTutorial)
            forControlEvents:UIControlEventTouchUpInside];
  [self.headerBar addSubview:self.helpButton];
  
  [NSLayoutConstraint activateConstraints:@[
    [self.helpButton.trailingAnchor constraintEqualToAnchor:self.headerBar.trailingAnchor constant:-16],
    [self.helpButton.centerYAnchor constraintEqualToAnchor:self.backButton.centerYAnchor],
    [self.helpButton.widthAnchor constraintEqualToConstant:24],
    [self.helpButton.heightAnchor constraintEqualToConstant:24],
  ]];
}

#pragma mark - Offline mode
- (void)setupOfflineBanner {
    self.offlineBanner = [[UIView alloc] init];
    self.offlineBanner.backgroundColor = [UIColor colorWithRed:1.0 green:0.9 blue:0.9 alpha:1.0];
    self.offlineBanner.hidden = YES; // toggle later

    UILabel *label = [[UILabel alloc] init];
    label.text = @"Offline mode";
    label.font = [UIFont systemFontOfSize:13];
    label.textColor = UIColor.darkGrayColor;
    label.translatesAutoresizingMaskIntoConstraints = NO;

    [self.offlineBanner addSubview:label];
    [self.view addSubview:self.offlineBanner];

    self.offlineBanner.translatesAutoresizingMaskIntoConstraints = NO;

    [NSLayoutConstraint activateConstraints:@[
        [self.offlineBanner.topAnchor constraintEqualToAnchor:self.headerBar.bottomAnchor],
        [self.offlineBanner.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.offlineBanner.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.offlineBanner.heightAnchor constraintEqualToConstant:32],

        [label.centerXAnchor constraintEqualToAnchor:self.offlineBanner.centerXAnchor],
        [label.centerYAnchor constraintEqualToAnchor:self.offlineBanner.centerYAnchor],
    ]];
}

#pragma mark - Search Bar
- (void)setupSearchBar {
    UIView *container = [[UIView alloc] init];
    container.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1.0];
    container.layer.cornerRadius = 16;

    self.searchField = [[UITextField alloc] init];
    self.searchField.placeholder = @"Search Name or Unit Number";
    self.searchField.font = [UIFont systemFontOfSize:14];
    self.searchField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self.searchField addTarget:self
                         action:@selector(searchChanged:)
               forControlEvents:UIControlEventEditingChanged];

    [container addSubview:self.searchField];
    [self.view addSubview:container];

    container.translatesAutoresizingMaskIntoConstraints = NO;
    self.searchField.translatesAutoresizingMaskIntoConstraints = NO;

    [NSLayoutConstraint activateConstraints:@[
        [container.topAnchor constraintEqualToAnchor:self.headerBar.bottomAnchor constant:8],
        [container.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:16],
        [container.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:-16],
        [container.heightAnchor constraintEqualToConstant:40],

        [self.searchField.leadingAnchor constraintEqualToAnchor:container.leadingAnchor constant:16],
        [self.searchField.trailingAnchor constraintEqualToAnchor:container.trailingAnchor constant:-16],
        [self.searchField.centerYAnchor constraintEqualToAnchor:container.centerYAnchor],
    ]];
}

- (void)searchChanged:(UITextField *)textField {
    [self filterWithText:textField.text];
}

#pragma mark - Table View
- (void)setupTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.tableFooterView = [UIView new];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 98;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor colorWithWhite:0.85 alpha:1];

    [self.view addSubview:self.tableView];
    self.tableView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.tableView registerClass:ThirdPartyCell.class forCellReuseIdentifier:@"ThirdPartyCell"];

    [NSLayoutConstraint activateConstraints:@[
        [self.tableView.topAnchor constraintEqualToAnchor:self.searchField.superview.bottomAnchor constant:8],
        [self.tableView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.tableView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.tableView.bottomAnchor constraintEqualToAnchor:self.addButton.topAnchor constant:-16],
    ]];
}

#pragma mark - UITableViewDataSource
- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {

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

    NSDictionary *item = self.filteredItems[indexPath.row];
    [cell configureWithItem:item];

    return cell;
}

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

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

#pragma mark - UITableViewDelegate

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

    NSDictionary *item = self.filteredItems[indexPath.row];

    NSLog(@"Tapped item: %@", item[@"title"]);
  
    ThirdPartyDetailsViewController *vc = [[ThirdPartyDetailsViewController alloc] init];
    vc.item = item;
    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:vc animated:YES completion:nil];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 50; // no extra spacing for other sections
}

#pragma mark - Footer Button
- (void)setupAddButton {
    self.addButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.addButton.backgroundColor = [UIColor colorWithRed:0.05 green:0.45 blue:0.57 alpha:1.0];
    self.addButton.layer.cornerRadius = 20;

    [self.addButton setTitle:@"Add" forState:UIControlStateNormal];
    [self.addButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    self.addButton.titleLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightMedium];

    [self.addButton addTarget:self
                       action:@selector(onAddLink)
             forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:self.addButton];
    self.addButton.translatesAutoresizingMaskIntoConstraints = NO;

    UILayoutGuide *safe = self.view.safeAreaLayoutGuide;

    [NSLayoutConstraint activateConstraints:@[
        [self.addButton.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor],
        [self.addButton.bottomAnchor constraintEqualToAnchor:safe.bottomAnchor constant:-16],
        [self.addButton.heightAnchor constraintEqualToConstant:48],
        [self.addButton.widthAnchor constraintEqualToConstant:245],
    ]];
}

#pragma mark - Add Link
- (UIView *)buildDimmedOverlay {
    UIView *overlay = [[UIView alloc] initWithFrame:self.view.bounds];
    overlay.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
    overlay.alpha = 0;

    UITapGestureRecognizer *tap =
        [[UITapGestureRecognizer alloc] initWithTarget:self
                                                action:@selector(dismissAddLinkSheet)];
    [overlay addGestureRecognizer:tap];

    return overlay;
}

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

    UILabel *title = [[UILabel alloc] init];
    title.text = @"Add 3rd Party Link";
    title.font = [UIFont systemFontOfSize:18 weight:UIFontWeightBold];
    title.textAlignment = NSTextAlignmentCenter;
    title.translatesAutoresizingMaskIntoConstraints = NO;
    [sheet addSubview:title];

    UILabel *subtitle = [[UILabel alloc] init];
    subtitle.text = @"Enter name to allow temporary access via weblink to handle ongoing defects.";
    subtitle.font = [UIFont systemFontOfSize:14];
    subtitle.textAlignment = NSTextAlignmentCenter;
    subtitle.textColor = UIColor.darkGrayColor;
    subtitle.numberOfLines = 0;
    subtitle.lineBreakMode = NSLineBreakByWordWrapping;
    subtitle.translatesAutoresizingMaskIntoConstraints = NO;
    [sheet addSubview:subtitle];

  
    self.linkNameField = [[UITextField alloc] init];
    self.linkNameField.placeholder = @"Enter Link Name";
    self.linkNameField.borderStyle = UITextBorderStyleRoundedRect;
    [self.linkNameField addTarget:self
                           action:@selector(onTextChanged:)
                 forControlEvents:UIControlEventEditingChanged];
    self.linkNameField.translatesAutoresizingMaskIntoConstraints = NO;
    [sheet addSubview:self.linkNameField];
  
    UIButton *cancel = [UIButton buttonWithType:UIButtonTypeSystem];
    [cancel setTitle:@"Cancel" forState:UIControlStateNormal];
    [cancel addTarget:self
               action:@selector(dismissAddLinkSheet)
     forControlEvents:UIControlEventTouchUpInside];
    [cancel setTitleColor:[UIColor colorWithRed:255.0/255.0
                                        green:100.0/255.0
                                         blue:100.0/255.0
                                        alpha:1.0]
                 forState:UIControlStateNormal];
    cancel.layer.cornerRadius = 10;
    cancel.layer.borderWidth = 0.5;
    cancel.layer.borderColor = [UIColor colorWithRed:255.0/255.0
                                               green:100.0/255.0
                                                blue:100.0/255.0
                                               alpha:1.0].CGColor;
    cancel.translatesAutoresizingMaskIntoConstraints = NO;
    [sheet addSubview:cancel];


    self.createButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.createButton setTitle:@"Create" forState:UIControlStateNormal];
    self.createButton.enabled = NO;
    self.createButton.backgroundColor = [UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0];
    self.createButton.layer.cornerRadius = 10;
    [self.createButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [self.createButton addTarget:self
                          action:@selector(onCreateLink)
                forControlEvents:UIControlEventTouchUpInside];
    self.createButton.translatesAutoresizingMaskIntoConstraints = NO;
    [sheet addSubview:self.createButton];


    [NSLayoutConstraint activateConstraints:@[
      [title.centerXAnchor constraintEqualToAnchor:sheet.centerXAnchor],
      [title.topAnchor constraintEqualToAnchor:sheet.topAnchor constant:28],
      
      [subtitle.topAnchor constraintEqualToAnchor:title.bottomAnchor constant:12],
      [subtitle.leadingAnchor constraintEqualToAnchor:sheet.leadingAnchor constant:16],
      [subtitle.trailingAnchor constraintEqualToAnchor:sheet.trailingAnchor constant:-16],
      
      [self.linkNameField.topAnchor constraintEqualToAnchor:subtitle.bottomAnchor constant:24],
      [self.linkNameField.leadingAnchor constraintEqualToAnchor:sheet.leadingAnchor constant:20],
      [self.linkNameField.trailingAnchor constraintEqualToAnchor:sheet.trailingAnchor constant:-20],
      [self.linkNameField.heightAnchor constraintEqualToConstant:48],
      
      [cancel.topAnchor constraintEqualToAnchor:self.linkNameField.bottomAnchor constant:32],
      [cancel.leadingAnchor constraintEqualToAnchor:subtitle.leadingAnchor],
      [cancel.trailingAnchor constraintEqualToAnchor:sheet.centerXAnchor constant:-6],
      [cancel.heightAnchor constraintEqualToConstant:48],
      
      [self.createButton.topAnchor constraintEqualToAnchor:self.linkNameField.bottomAnchor constant:32],
      [self.createButton.leadingAnchor constraintEqualToAnchor:sheet.centerXAnchor constant:6],
      [self.createButton.trailingAnchor constraintEqualToAnchor:subtitle.trailingAnchor],
      [self.createButton.heightAnchor constraintEqualToConstant:48],
      [self.createButton.bottomAnchor constraintEqualToAnchor:sheet.safeAreaLayoutGuide.bottomAnchor constant:-24],

    ]];
    return sheet;
}

- (void)showAddLinkSheet {
    self.dimmedOverlay = [self buildDimmedOverlay];
    self.addLinkSheet = [self buildAddLinkSheet];

    [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:320],
    ]];

    [self.view layoutIfNeeded];

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

- (void)dismissAddLinkSheet {
    [UIView animateWithDuration:0.25 animations:^{
        self.dimmedOverlay.alpha = 0;
        self.addLinkSheet.transform = CGAffineTransformMakeTranslation(0, 300);
    } completion:^(BOOL finished) {
        [self.addLinkSheet removeFromSuperview];
        [self.dimmedOverlay removeFromSuperview];
        self.linkNameField.text = @"";
    }];
}

- (void)onTextChanged:(UITextField *)textField {
    BOOL hasText = textField.text.length > 0;
    self.createButton.enabled = hasText;
    self.createButton.backgroundColor =
        hasText ? [UIColor colorWithRed:0.05 green:0.45 blue:0.57 alpha:1.0]
                : UIColor.systemGray5Color;
}

- (void)onCreateLink {

    // TODO: call API here
    [APIClient createThirdPartyLink:self.linkNameField.text lotId:self.lotId completion:^(BOOL success, NSDictionary * _Nullable data, NSError * _Nullable error) {
      
      if (!success) {
          NSLog(@"❌ API returned success = NO");
          return;
      }

      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;
      }
    
      if (!error) {
        NSLog(@"Successfully created ThirdPartyLink");
        [self dismissAddLinkSheet];
        [self presentSuccessModal];
        [self requestThirdPartyList];
      }
    }];
}

- (void)presentSuccessModal {
    self.successOverlay = [[UIView alloc] initWithFrame:self.view.bounds];
    self.successOverlay.backgroundColor =
        [[UIColor blackColor] colorWithAlphaComponent:0.6];

    self.successModal = [[UIView alloc] init];
    self.successModal.backgroundColor = UIColor.whiteColor;
    self.successModal.layer.cornerRadius = 24;
    self.successModal.translatesAutoresizingMaskIntoConstraints = NO;

    UILabel *title = [[UILabel alloc] init];
    title.text = @"Success";
    title.font = [UIFont systemFontOfSize:18 weight:UIFontWeightBold];
    title.textAlignment = NSTextAlignmentCenter;
    title.translatesAutoresizingMaskIntoConstraints = NO;
  
    UILabel *subtitle = [[UILabel alloc] init];
    subtitle.text = @"3rd party link has been successfully created.";
    subtitle.font = [UIFont systemFontOfSize:14];
    subtitle.textAlignment = NSTextAlignmentCenter;
    subtitle.textColor = UIColor.darkGrayColor;
    subtitle.numberOfLines = 0;
    subtitle.lineBreakMode = NSLineBreakByWordWrapping;
    subtitle.translatesAutoresizingMaskIntoConstraints = NO;

    UIButton *ok = [UIButton buttonWithType:UIButtonTypeSystem];
    [ok setTitle:@"OK" forState:UIControlStateNormal];
    [ok addTarget:self action:@selector(dismissSuccessModal) forControlEvents:UIControlEventTouchUpInside];
    [ok setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];

    ok.layer.cornerRadius = 10;
    ok.layer.backgroundColor = [UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0].CGColor;
    ok.translatesAutoresizingMaskIntoConstraints = NO;

    [self.view addSubview:self.successOverlay];
    [self.successOverlay addSubview:self.successModal];
    [self.successOverlay addSubview:title];
    [self.successOverlay addSubview:subtitle];
    [self.successOverlay addSubview:ok];

    [NSLayoutConstraint activateConstraints:@[
        [self.successModal.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor],
        [self.successModal.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor],
        [self.successModal.widthAnchor constraintEqualToConstant:312],
        [self.successModal.heightAnchor constraintEqualToConstant:309],
        
        [title.topAnchor constraintEqualToAnchor:self.successModal.topAnchor constant:18],
        [title.centerXAnchor constraintEqualToAnchor:self.successModal.centerXAnchor],
        
        [subtitle.topAnchor constraintEqualToAnchor:title.bottomAnchor constant:12],
        [subtitle.leadingAnchor constraintEqualToAnchor:self.successModal.leadingAnchor constant:20],
        [subtitle.trailingAnchor constraintEqualToAnchor:self.successModal.trailingAnchor constant:-20],
        
        [ok.topAnchor constraintEqualToAnchor:subtitle.bottomAnchor constant:32],
        [ok.centerXAnchor constraintEqualToAnchor:self.successModal.centerXAnchor],
        [ok.widthAnchor constraintEqualToConstant:166],
        [ok.heightAnchor constraintEqualToConstant:48],
        [ok.bottomAnchor constraintEqualToAnchor:self.successModal.bottomAnchor constant:44],
    ]];

    self.successOverlay.alpha = 0;
    [UIView animateWithDuration:0.25 animations:^{
        self.successOverlay.alpha = 1;
    }];
}

- (void)dismissSuccessModal {
    [UIView animateWithDuration:0.2 animations:^{
        self.successOverlay.alpha = 0;
    } completion:^(BOOL finished) {
        [self.successOverlay removeFromSuperview];
    }];
}

#pragma mark - API
-(void)requestThirdPartyList {
  [APIClient requestThirdPartyList:^(BOOL success, NSDictionary * _Nullable data, NSError * _Nullable error) {
    
    if (!success || ![data[@"Data"] isKindOfClass:[NSArray class]]) {
        return;
    }
    
    NSLog(@"📦 Received thirdPartyList: %@", data);
    // 1️⃣ Write to file for debugging (your existing logic)
    NSString *plainText = [NSString stringWithFormat:@"%@", data];
    NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    NSString *filePath = [docsPath stringByAppendingPathComponent:@"thirdPartyList.txt"];
    [plainText writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"📁 thirdPartyList saved as plain text to: %@", filePath);
    
    NSArray *list = data[@"Data"];

    dispatch_async(dispatch_get_main_queue(), ^{
        [self.items removeAllObjects];
        [self.filteredItems removeAllObjects];

        [self.items addObjectsFromArray:list];
        [self.filteredItems addObjectsFromArray:list];
      
        NSLog(@"Items count: %lu", (unsigned long)self.items.count);
        NSLog(@"Filtered count: %lu", (unsigned long)self.filteredItems.count);

        [self.tableView reloadData];
    });
  }];
}

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

- (void)showTutorial {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Help"
                                                                   message:@"This would show the tutorial (e.g. step1/step2/step3)."
                                                            preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];
    ThirdPartyTutorialViewController *vc = [[ThirdPartyTutorialViewController alloc] init];
    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:vc animated:YES completion:nil];
}

- (void)onAddLink {
    [self showAddLinkSheet];
}

- (void)filterWithText:(NSString *)text {
    [self.filteredItems removeAllObjects];

    if (text.length == 0) {
        [self.filteredItems addObjectsFromArray:self.items];
    } else {
        for (NSDictionary *item in self.items) {
            NSString *title = item[@"title"] ?: @"";
            if ([[title lowercaseString] containsString:[text lowercaseString]]) {
                [self.filteredItems addObject:item];
            }
        }
    }

    [self.tableView reloadData];
}

@end
