// AnnouncementViewController.mm
#import "AnnounceViewController.h"
#import "APIClient.h"
#import "ImageCacheHelper.h"
#import "AnnounceDetailsViewController.h"

@interface AnnouncementCell : UITableViewCell

@property (nonatomic, strong) UIView *cardView;
@property (nonatomic, strong) UIImageView *announcementImage;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *descriptionLabel;
@property (nonatomic, strong) UILabel *dateLabel;
@property (nonatomic, strong) NSLayoutConstraint *imageAspectConstraint;

- (void)configureWithData:(NSDictionary *)data;

@end

@implementation AnnouncementCell

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

- (void)setupViews {
    // Card container
    self.cardView = [[UIView alloc] init];
    self.cardView.backgroundColor = UIColor.whiteColor;
    self.cardView.layer.cornerRadius = 8;
    self.cardView.layer.shadowColor = [UIColor blackColor].CGColor;
    self.cardView.layer.shadowOpacity = 0.1;
    self.cardView.layer.shadowOffset = CGSizeMake(0, 2);
    self.cardView.layer.shadowRadius = 4;
    self.cardView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.contentView addSubview:self.cardView];
    
    [NSLayoutConstraint activateConstraints:@[
        [self.cardView.topAnchor constraintEqualToAnchor:self.contentView.topAnchor constant:12],
        [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],
    ]];
    
    // Image
    self.announcementImage = [[UIImageView alloc] init];
    self.announcementImage.contentMode = UIViewContentModeScaleAspectFit;
    self.announcementImage.clipsToBounds = YES;
    self.announcementImage.layer.cornerRadius = 6;
    self.announcementImage.translatesAutoresizingMaskIntoConstraints = NO;
    [self.cardView addSubview:self.announcementImage];
    
    // Title
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.cardView addSubview:self.titleLabel];
    
    // Description
    self.descriptionLabel = [[UILabel alloc] init];
    self.descriptionLabel.font = [UIFont systemFontOfSize:14];
    self.descriptionLabel.numberOfLines = 4; // infinite lines
    self.descriptionLabel.textColor = [UIColor darkGrayColor];
    self.descriptionLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.cardView addSubview:self.descriptionLabel];
    
    // Date
    self.dateLabel = [[UILabel alloc] init];
    self.dateLabel.font = [UIFont italicSystemFontOfSize:12];
    self.dateLabel.textColor = [UIColor grayColor];
    self.dateLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.cardView addSubview:self.dateLabel];
    
    // Constraints
    [NSLayoutConstraint activateConstraints:@[
        // Image
        [self.announcementImage.topAnchor constraintEqualToAnchor:self.cardView.topAnchor constant:12],
        [self.announcementImage.leadingAnchor constraintEqualToAnchor:self.cardView.leadingAnchor constant:12],
        [self.announcementImage.widthAnchor constraintEqualToConstant:64],
        
        // Title
        [self.titleLabel.topAnchor constraintEqualToAnchor:self.cardView.topAnchor constant:12],
        [self.titleLabel.leadingAnchor constraintEqualToAnchor:self.announcementImage.trailingAnchor constant:12],
        [self.titleLabel.trailingAnchor constraintEqualToAnchor:self.cardView.trailingAnchor constant:-12],
        
        // Description
        [self.descriptionLabel.topAnchor constraintEqualToAnchor:self.titleLabel.bottomAnchor constant:4],
        [self.descriptionLabel.leadingAnchor constraintEqualToAnchor:self.titleLabel.leadingAnchor],
        [self.descriptionLabel.trailingAnchor constraintEqualToAnchor:self.titleLabel.trailingAnchor],
        
        // Date
        [self.dateLabel.topAnchor constraintEqualToAnchor:self.descriptionLabel.bottomAnchor constant:4],
        [self.dateLabel.leadingAnchor constraintEqualToAnchor:self.titleLabel.leadingAnchor],
        [self.dateLabel.trailingAnchor constraintEqualToAnchor:self.titleLabel.trailingAnchor],
        [self.dateLabel.bottomAnchor constraintEqualToAnchor:self.cardView.bottomAnchor constant:-12],
    ]];
    
    // Image aspect constraint placeholder
    self.imageAspectConstraint = [self.announcementImage.heightAnchor constraintEqualToConstant:64];
    self.imageAspectConstraint.active = YES;
}

- (void)configureWithData:(NSDictionary *)data {
    self.titleLabel.text = data[@"title"];
    
    // HTML description
    NSString *descHTML = data[@"description"];
    if (descHTML.length > 0) {
        NSAttributedString *attrDesc = [[NSAttributedString alloc] initWithData:[descHTML dataUsingEncoding:NSUnicodeStringEncoding]
                                                                        options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType}
                                                             documentAttributes:nil
                                                                          error:nil];
        self.descriptionLabel.attributedText = attrDesc;
    } else {
        self.descriptionLabel.text = @"";
    }
    
    // Date formatting
    NSString *dateStr = data[@"start_date"];
    if (dateStr.length > 0) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyy-MM-dd";
        NSDate *date = [formatter dateFromString:dateStr];
        NSDateFormatter *displayFormatter = [[NSDateFormatter alloc] init];
        displayFormatter.dateFormat = @"dd MMM yyyy";
        self.dateLabel.text = [displayFormatter stringFromDate:date];
    } else {
        self.dateLabel.text = @"";
    }
    
    // Image
    NSString *imageURL = data[@"image"];
    if (imageURL.length > 0) {
        NSURL *url = [NSURL URLWithString:imageURL];
        [ImageCacheHelper loadImageWithURL:url completion:^(UIImage *image) {
            if (!image) return;
            dispatch_async(dispatch_get_main_queue(), ^{
                self.announcementImage.image = image;
                
                // Update aspect ratio
                [NSLayoutConstraint deactivateConstraints:@[self.imageAspectConstraint]];
                CGFloat ratio = image.size.height / image.size.width;
                self.imageAspectConstraint = [self.announcementImage.heightAnchor constraintEqualToAnchor:self.announcementImage.widthAnchor multiplier:ratio];
                self.imageAspectConstraint.active = YES;
            });
        }];
    } else {
        self.announcementImage.image = nil;
        [NSLayoutConstraint deactivateConstraints:@[self.imageAspectConstraint]];
        self.imageAspectConstraint = [self.announcementImage.heightAnchor constraintEqualToConstant:0];
        self.imageAspectConstraint.active = YES;
    }
}

@end


@interface AnnouncementViewController () <UITableViewDelegate, UITableViewDataSource>

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

// Table
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *announcement;
@end

@implementation AnnouncementViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = UIColor.whiteColor;
    
    // Dummy data
    self.announcement = @[
        @{@"title": @"Announcement 1", @"description": @"This is a test announcement 1.", @"date": @"2026-01-26"},
        @{@"title": @"Announcement 2", @"description": @"This is a test announcement 2.", @"date": @"2026-01-25"},
        @{@"title": @"Announcement 3", @"description": @"This is a test announcement 3.", @"date": @"2026-01-24"}
    ];
    
    [self setupHeader];
    [self setupTableView];
    [self requestAnnouncement];
}

#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.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],
    ]];
    
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.text = @"Announcement";
    self.titleLabel.textColor = UIColor.whiteColor;
    self.titleLabel.font = [UIFont systemFontOfSize:18 weight:UIFontWeightMedium];
    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.heightAnchor constraintEqualToConstant:24],
        [self.backButton.widthAnchor constraintEqualToConstant:24],
        
        [self.titleLabel.centerXAnchor constraintEqualToAnchor:self.headerBar.centerXAnchor],
        [self.titleLabel.centerYAnchor constraintEqualToAnchor:self.headerBar.centerYAnchor],
    ]];
}

#pragma mark - Table
- (void)setupTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [UIView new]; // hide empty rows
    [self.view addSubview:self.tableView];
    self.tableView.translatesAutoresizingMaskIntoConstraints = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:[AnnouncementCell class] forCellReuseIdentifier:@"AnnouncementCell"];
  
    [NSLayoutConstraint activateConstraints:@[
        [self.tableView.topAnchor constraintEqualToAnchor:self.headerBar.bottomAnchor],
        [self.tableView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.tableView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.tableView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor],
    ]];
}

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    AnnouncementCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AnnouncementCell" forIndexPath:indexPath];
    
    NSDictionary *announcement = self.announcement[indexPath.row]; // or self.announcement when API data is ready
    
    // Configure the cell
    [cell configureWithData:announcement];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100;
}

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

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *announcement = self.announcement[indexPath.row];
    NSLog(@"Selected announcement: %@", announcement[@"title"]);
    AnnouncementDetailsViewController *vc = [[AnnouncementDetailsViewController alloc] init];
    vc.data = announcement;
    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:vc animated:YES completion:nil];
}

#pragma mark - API
- (void)requestAnnouncement {
  [APIClient requestAnnouncement:^(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:@"announcement.txt"];
      [plainText writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
      NSLog(@"📁 announcement saved as plain text to: %@", filePath);

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

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

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

      NSArray *announcement = data[@"Data"];
      if (![announcement isKindOfClass:[NSArray class]]) {
          NSLog(@"❌ Invalid announcement format");
          return;
      }
      self.announcement = announcement;
      dispatch_async(dispatch_get_main_queue(), ^{
          [self.tableView reloadData];
      });
  }];
}

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

@end


