//  NotificationViewController.mm

#import "NotificationViewController.h"
#import "APIClient.h"
#import "ImageCacheHelper.h"
#import <objc/runtime.h>
#import "APIConfig.h"
#import "AppointmentDetailsViewController.h"
#import "DashboardViewController.h"

static char kNotificationKey;

@interface NotificationViewController ()
// Header (existing)
@property (nonatomic, strong) UIView *headerBar;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *backButton;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UIView *footerView;
@property (nonatomic, strong) UIStackView *stackView;
@property (nonatomic, strong) NSArray *notifications;
@property (nonatomic, strong) NSArray *projectList;
@property (nonatomic, strong) NSString *oldUnitId;
@end

@implementation NotificationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;
    if (self.oldUnitId) {
      [APIConfig setDrawingPlanId:self.oldUnitId];
    }
    
    [self requestProjectList];
    [self setupHeader];
    [self setupScrollView];
    [self setupFooterButton];
    [self setupNotificationList];
    [self requestNotification];
}

#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 = @"Notification";
  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],
  ]];
}

#pragma mark - Scroll View
- (void)setupScrollView {
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.alwaysBounceVertical = YES;
    [self.view addSubview:self.scrollView];
    self.scrollView.translatesAutoresizingMaskIntoConstraints = NO;
    self.scrollView.contentInset = UIEdgeInsetsMake(0, 0, 64, 0);
    self.scrollView.scrollIndicatorInsets = self.scrollView.contentInset;

    [NSLayoutConstraint activateConstraints:@[
        [self.scrollView.topAnchor constraintEqualToAnchor:self.headerBar.bottomAnchor],
        [self.scrollView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.scrollView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.scrollView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor],
    ]];

    self.contentView = [[UIView alloc] init];
    [self.scrollView addSubview:self.contentView];
    self.contentView.translatesAutoresizingMaskIntoConstraints = NO;

    [NSLayoutConstraint activateConstraints:@[
        [self.contentView.topAnchor constraintEqualToAnchor:self.scrollView.topAnchor],
        [self.contentView.leadingAnchor constraintEqualToAnchor:self.scrollView.leadingAnchor],
        [self.contentView.trailingAnchor constraintEqualToAnchor:self.scrollView.trailingAnchor],
        [self.contentView.bottomAnchor constraintEqualToAnchor:self.scrollView.bottomAnchor],
        [self.contentView.widthAnchor constraintEqualToAnchor:self.scrollView.widthAnchor],
    ]];
  
    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],
    ]];
}

#pragma mark - Stack View
- (void)setupNotificationList {
    self.stackView = [[UIStackView alloc] init];
    self.stackView.axis = UILayoutConstraintAxisVertical;
    self.stackView.spacing = 12;
    self.stackView.alignment = UIStackViewAlignmentFill;
    self.stackView.distribution = UIStackViewDistributionFill;

    [self.contentView addSubview:self.stackView];
    self.stackView.translatesAutoresizingMaskIntoConstraints = NO;

    [NSLayoutConstraint activateConstraints:@[
        [self.stackView.topAnchor constraintEqualToAnchor:self.contentView.topAnchor constant:16],
        [self.stackView.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],
        [self.stackView.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-16],
        [self.stackView.bottomAnchor constraintEqualToAnchor:self.contentView.bottomAnchor constant:-16],
    ]];
}

- (UIView *)createNotificationCard:(NSDictionary *)item {
    UIView *card = [[UIView alloc] init];
    card.layer.cornerRadius = 12;
    card.translatesAutoresizingMaskIntoConstraints = NO;
    card.backgroundColor = UIColor.whiteColor;
    card.layer.shadowColor = UIColor.blackColor.CGColor;
    card.layer.shadowOpacity = 0.05;
    card.layer.shadowRadius = 6;
    card.layer.shadowOffset = CGSizeMake(0, 2);
    card.layer.borderColor = UIColor.systemGray5Color.CGColor;
    card.layer.borderWidth = 0.5;
    UITapGestureRecognizer *tap =
        [[UITapGestureRecognizer alloc] initWithTarget:self
                                                action:@selector(onNotificationTap:)];

    [card addGestureRecognizer:tap];
    card.userInteractionEnabled = YES;

    UIImageView *icon = [[UIImageView alloc] init];
    icon.translatesAutoresizingMaskIntoConstraints = NO;
    icon.contentMode = UIViewContentModeScaleAspectFit;
    icon.clipsToBounds = YES;
    icon.layer.cornerRadius = 12;
    NSString *logoURL = item[@"project_logo"];
    if (logoURL.length > 0) {
        NSURL *url = [NSURL URLWithString:logoURL];
        [ImageCacheHelper loadImageWithURL:url completion:^(UIImage *image) {
            if (image) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    icon.image = image;
                    UIImage *img = image;
                    icon.image = img;
                    for (NSLayoutConstraint *c in icon.constraints) {
                        if (c.firstAttribute == NSLayoutAttributeHeight &&
                            c.secondAttribute == NSLayoutAttributeWidth) {
                            [icon removeConstraint:c];
                        }
                    }
                    CGFloat ratio = img.size.height / img.size.width;

                    NSLayoutConstraint *aspect =
                        [icon.heightAnchor constraintEqualToAnchor:icon.widthAnchor multiplier:ratio];
                    aspect.active = YES;
                });
            }
        }];
    }

    UILabel *projectLabel = [[UILabel alloc] init];
    projectLabel.text = item[@"project_name"];
    projectLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightBold];
    projectLabel.textColor = UIColor.labelColor;
    projectLabel.numberOfLines = 1;
    projectLabel.translatesAutoresizingMaskIntoConstraints = NO;

    UILabel *messageLabel = [[UILabel alloc] init];
    messageLabel.text = item[@"message"];
    messageLabel.numberOfLines = 0;
    messageLabel.font = [UIFont systemFontOfSize:15];
    messageLabel.translatesAutoresizingMaskIntoConstraints = NO;

    UILabel *dateLabel = [[UILabel alloc] init];
    dateLabel.text = item[@"date_time"];
    dateLabel.font = [UIFont systemFontOfSize:12];
    dateLabel.textColor = UIColor.secondaryLabelColor;
    dateLabel.translatesAutoresizingMaskIntoConstraints = NO;
  
    UIView *unreadDot = [[UIView alloc] init];
    unreadDot.backgroundColor = [UIColor systemOrangeColor];
    unreadDot.layer.cornerRadius = 4;
    unreadDot.translatesAutoresizingMaskIntoConstraints = NO;
    CGFloat dotSize = 8;

    UIView *textContainer = [[UIView alloc] init];
    textContainer.translatesAutoresizingMaskIntoConstraints = NO;

    [card addSubview:icon];
    [card addSubview:textContainer];

    [textContainer addSubview:projectLabel];
    [textContainer addSubview:messageLabel];
    [textContainer addSubview:dateLabel];
    [textContainer addSubview:unreadDot];

    [NSLayoutConstraint activateConstraints:@[
      // Logo
      [icon.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:12],
      [icon.topAnchor constraintEqualToAnchor:card.topAnchor constant:12],
      [icon.widthAnchor constraintEqualToConstant:64],
      [icon.heightAnchor constraintLessThanOrEqualToConstant:64],

      // Text container
      [textContainer.leadingAnchor constraintEqualToAnchor:icon.trailingAnchor constant:12],
      [textContainer.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-16],
      [textContainer.topAnchor constraintEqualToAnchor:card.topAnchor constant:12],
      [textContainer.bottomAnchor constraintEqualToAnchor:card.bottomAnchor constant:-12],

      // Project name
      [projectLabel.topAnchor constraintEqualToAnchor:textContainer.topAnchor],
      [projectLabel.leadingAnchor constraintEqualToAnchor:textContainer.leadingAnchor],
      [projectLabel.trailingAnchor constraintEqualToAnchor:textContainer.trailingAnchor],

      // Message
      [messageLabel.topAnchor constraintEqualToAnchor:projectLabel.bottomAnchor constant:4],
      [messageLabel.leadingAnchor constraintEqualToAnchor:textContainer.leadingAnchor],
      [messageLabel.trailingAnchor constraintEqualToAnchor:textContainer.trailingAnchor],

      // Date
      [dateLabel.topAnchor constraintEqualToAnchor:messageLabel.bottomAnchor constant:6],
      [dateLabel.leadingAnchor constraintEqualToAnchor:textContainer.leadingAnchor],
      [dateLabel.bottomAnchor constraintEqualToAnchor:textContainer.bottomAnchor],
      [dateLabel.trailingAnchor constraintEqualToAnchor:unreadDot.leadingAnchor constant:-8],
      
      // Unread Dot
      [unreadDot.widthAnchor constraintEqualToConstant:dotSize],
      [unreadDot.heightAnchor constraintEqualToConstant:dotSize],
      [unreadDot.centerYAnchor constraintEqualToAnchor:dateLabel.centerYAnchor],
      [unreadDot.trailingAnchor constraintEqualToAnchor:textContainer.trailingAnchor],
    ]];
  
    BOOL unread = [item[@"read_status"] isEqualToString:@"0"];
    unreadDot.hidden = !unread;
  
    objc_setAssociatedObject(card,
                             &kNotificationKey,
                             item,
                             OBJC_ASSOCIATION_RETAIN_NONATOMIC);

    return card;
}

#pragma mark - Footer
- (void) setupFooterButton {
    UIButton *clearButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [clearButton setTitle:@"Clear All Notification" forState:UIControlStateNormal];
    clearButton.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    clearButton.backgroundColor = [UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0];
    clearButton.tintColor = UIColor.whiteColor;
    clearButton.layer.cornerRadius = 12;

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

    [NSLayoutConstraint activateConstraints:@[
        [clearButton.bottomAnchor constraintEqualToAnchor:self.footerView.safeAreaLayoutGuide.bottomAnchor],
        [clearButton.centerXAnchor constraintEqualToAnchor:self.footerView.centerXAnchor],
        [clearButton.heightAnchor constraintEqualToConstant:48],
        [clearButton.widthAnchor constraintEqualToConstant:245],
    ]];
}

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

- (void)requestNotification {
  [APIClient requestNotification:^(BOOL success, NSDictionary *data, NSError *error) {
      // Save debug file
      NSString *plainText = [NSString stringWithFormat:@"%@", data];
      NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
      NSString *filePath = [docsPath stringByAppendingPathComponent:@"notification.txt"];
      [plainText writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
      NSLog(@"📁 notification saved as plain text to: %@", filePath);

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

      if (data[@"status_code"]) {
          NSLog(@"❌ notification status error: %@", data[@"message"]);
          return;
      }

      NSDictionary *appData = data[@"AppData"];
      if (![appData[@"status"] isEqualToString:@"success"]) {
          NSLog(@"❌ notification failure: %@", appData[@"message"]);
          return;
      }

      NSArray *notif = data[@"Data"];
      if (![notif isKindOfClass:[NSArray class]]) {
          NSLog(@"❌ Invalid notification format");
          return;
      }
      self.notifications = notif;
      dispatch_async(dispatch_get_main_queue(), ^{
          // Clear existing cards
          for (UIView *v in self.stackView.arrangedSubviews) {
              [v removeFromSuperview];
          }

          for (NSDictionary *item in self.notifications) {
              UIView *card = [self createNotificationCard:item];
              [self.stackView addArrangedSubview:card];
          }

          [self.stackView addArrangedSubview:[self createEndOfListView]];
      });
  }];
}

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

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

        self.projectList = projects;
    }];
}

- (UIView *)createEndOfListView {
    UILabel *label = [[UILabel alloc] init];
    label.text = @"All items displayed";
    label.font = [UIFont systemFontOfSize:13];
    label.textColor = UIColor.secondaryLabelColor;
    label.textAlignment = NSTextAlignmentCenter;
    label.numberOfLines = 0;

    UIView *container = [[UIView alloc] init];
    [container addSubview:label];
    label.translatesAutoresizingMaskIntoConstraints = NO;

    [NSLayoutConstraint activateConstraints:@[
        [label.topAnchor constraintEqualToAnchor:container.topAnchor],
        [label.bottomAnchor constraintEqualToAnchor:container.bottomAnchor],
        [label.centerXAnchor constraintEqualToAnchor:container.centerXAnchor],
    ]];

    return container;
}

- (void)onNotificationTap:(UITapGestureRecognizer *)tap {
    UIView *card = tap.view;
    NSDictionary *item =
        objc_getAssociatedObject(card, &kNotificationKey);
    if (!item) return;

    NSString *notificationType = item[@"type"];
    NSDictionary *strData = item;
    self.oldUnitId = [APIConfig drawingPlanId];

    NSString *unitID = @"";
    if (strData[@"draw_plan_id"]) {
        unitID = strData[@"draw_plan_id"];
        [APIConfig setDrawingPlanId:unitID];
    }

    // ---- PAYMENT REMINDER ----
    if ([notificationType isEqualToString:@"payment_reminder"]) {
        NSLog(@"➡️ payment_reminder tapped");
        return;
    }

    // ---- APPOINTMENT ----
    if ([notificationType isEqualToString:@"appointment_reminder"] ||
        [notificationType isEqualToString:@"unattend_appt_reminder"]) {

        NSString *appointmentID = @"";
        if (strData[@"appointment_id"]) {
            appointmentID = strData[@"appointment_id"];
        }

        [self openAppointmentWithUnit:unitID appointmentID:appointmentID];
        return;
    }

    // ---- CLEARANCE LETTER ----
    if ([notificationType isEqualToString:@"clearance_letter"]) {
        NSString *projectID = @"";
        if (strData[@"project_id"]) {
            projectID = strData[@"project_id"];
        }

        [self openClearanceWithProject:projectID unitID:unitID];
        return;
    }

    // ---- DEFAULT: ISSUE FLOW ----
    NSString *issueID = @"";
    if (strData[@"issue_id"]) {
        issueID = strData[@"issue_id"];
    }

    [self openIssueWithUnit:unitID issueID:issueID];
}


#pragma mark - Navigation (ported from RN)
- (void)openAppointmentWithUnit:(NSString *)unitID appointmentID:(NSString *)appointmentID {
    NSLog(@"➡️ Open Appointment | unit=%@ appt=%@", unitID, appointmentID);
    [APIClient requestDashboardInfo:^(BOOL success, NSDictionary * _Nullable data, NSError * _Nonnull error) {
      if (!success || !data) {
          return;
      }
      
      id appointment = data[@"Data"][@"appointment"];
    
      if (!appointment ||
          appointment == [NSNull null] ||
          ![appointment isKindOfClass:[NSArray class]] ||
          appointmentID.length == 0) {
          return;
      }

      NSDictionary *matchedAppointment = nil;

      for (NSDictionary *appt in appointment) {
          if (![appt isKindOfClass:[NSDictionary class]]) {
              continue;
          }

      NSString *apptID = appt[@"id"];

      if ([apptID isKindOfClass:[NSString class]] &&
          [apptID isEqualToString:appointmentID]) {

          matchedAppointment = appt;
          break;
          }
      }

      if (!matchedAppointment) {
          // No match found
          return;
      }

      // 👉 Navigate to Appointment Details
      dispatch_async(dispatch_get_main_queue(), ^{
        AppointmentDetailsViewController *vc = [[AppointmentDetailsViewController alloc] init];
        vc.modalPresentationStyle = UIModalPresentationFullScreen;
        vc.appointmentData = matchedAppointment;
        [self presentViewController:vc animated:YES completion:nil];
      });
  }];
}

- (void)openClearanceWithProject:(NSString *)projectID unitID:(NSString *)unitID {
    NSLog(@"➡️ Open Clearance | project=%@ unit=%@", projectID, unitID);

    NSArray *projects = self.projectList;
    if (!projects || projects.count == 0) {
        NSLog(@"❌ Project list empty");
        return;
    }

    for (NSDictionary *project in projects) {
        if (![project isKindOfClass:[NSDictionary class]]) continue;

        NSString *projID = [NSString stringWithFormat:@"%@", project[@"id"]];
        if (![projID isEqualToString:projectID]) continue;

        NSArray *units = project[@"unit"];
        if (![units isKindOfClass:[NSArray class]]) break;

        for (NSDictionary *unit in units) {
            if (![unit isKindOfClass:[NSDictionary class]]) continue;

            NSString *uID = [NSString stringWithFormat:@"%@", unit[@"id"]];
            if (![uID isEqualToString:unitID]) continue;

            NSLog(@"✅ Found project %@ and unit %@", projectID, unitID);

            dispatch_async(dispatch_get_main_queue(), ^{
                DashboardViewController *vc = [[DashboardViewController alloc] init];
                vc.projectCode = unit[@"name"] ?: @"";
                vc.projectName = project[@"project_name"] ?: @"";
                vc.projectId = projectID ?: @"";
                vc.drawingPlanId = unitID ?: @"";
                vc.projectLogo = project[@"logo"] ?: @"";
                vc.lotId = unit[@"lot_id"] ?: @"";
                vc.drawerController = self.drawerController;
                vc.modalPresentationStyle = UIModalPresentationFullScreen;
                [self.navigationController pushViewController:vc animated:YES];
            });
            return;
        }
    }
    NSLog(@"❌ No matching project/unit found");
}


- (void)openIssueWithUnit:(NSString *)unitID issueID:(NSString *)issueID {
    NSLog(@"➡️ Open Issue | unit=%@ issue=%@", unitID, issueID);
    // TODO: push IssueDetailViewController
}

@end
