//  AnnounceDetailsViewController.mm

#import "AnnounceDetailsViewController.h"
#import "APIClient.h"
#import "ImageCacheHelper.h"

@interface AnnouncementDetailsViewController () <UITextViewDelegate>
// 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) UIImageView *announcementImage;
@property (nonatomic, strong) UILabel *announcementTitleLabel;
@property (nonatomic, strong) UILabel *dateLabel;
@property (nonatomic, strong) UITextView *descriptionTextView;

@property (nonatomic, assign) CGFloat imageHeight;

@end

@implementation AnnouncementDetailsViewController

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

    [self setupHeader];
    [self setupContentView];
  
    if (self.data) {
        [self configureWithData:self.data];
    }
}

#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
  //need to make it detect which screen its navigating from then set differently (Project Update Details if from client announce else Announcement Details from announce)
  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;
  
  // 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 - Content View
- (void)setupContentView {
    // Scroll view
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.scrollView];

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

    // Content view inside scroll
    self.contentView = [[UIView alloc] init];
    self.contentView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.scrollView addSubview:self.contentView];

    [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], // Important!
    ]];

    // Image
    self.announcementImage = [[UIImageView alloc] init];
    self.announcementImage.contentMode = UIViewContentModeScaleAspectFit;
    self.announcementImage.translatesAutoresizingMaskIntoConstraints = NO;
    self.announcementImage.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewImageFullScreen)];
    [self.announcementImage addGestureRecognizer:tapGesture];
    [self.contentView addSubview:self.announcementImage];

    self.imageHeight = 375; // default
    [NSLayoutConstraint activateConstraints:@[
        [self.announcementImage.topAnchor constraintEqualToAnchor:self.contentView.topAnchor],
        [self.announcementImage.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor],
        [self.announcementImage.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor],
        [self.announcementImage.heightAnchor constraintEqualToConstant:self.imageHeight]
    ]];

    // Title
    self.announcementTitleLabel = [[UILabel alloc] init];
    self.announcementTitleLabel.font = [UIFont boldSystemFontOfSize:20];
    self.announcementTitleLabel.numberOfLines = 0;
    self.announcementTitleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.contentView addSubview:self.announcementTitleLabel];

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

    // Date
    self.dateLabel = [[UILabel alloc] init];
    self.dateLabel.font = [UIFont italicSystemFontOfSize:14];
    self.dateLabel.textColor = [UIColor grayColor];
    self.dateLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.contentView addSubview:self.dateLabel];

    [NSLayoutConstraint activateConstraints:@[
        [self.dateLabel.topAnchor constraintEqualToAnchor:self.announcementTitleLabel.bottomAnchor constant:8],
        [self.dateLabel.leadingAnchor constraintEqualToAnchor:self.announcementTitleLabel.leadingAnchor],
        [self.dateLabel.trailingAnchor constraintEqualToAnchor:self.announcementTitleLabel.trailingAnchor],
    ]];

    // Description (UITextView for selectable text + HTML rendering)
    self.descriptionTextView = [[UITextView alloc] init];
    self.descriptionTextView.font = [UIFont systemFontOfSize:16];
    self.descriptionTextView.editable = NO;
    self.descriptionTextView.scrollEnabled = NO; // Let scrollView handle it
    self.descriptionTextView.dataDetectorTypes = UIDataDetectorTypeLink;
    self.descriptionTextView.translatesAutoresizingMaskIntoConstraints = NO;
    self.descriptionTextView.linkTextAttributes = @{NSForegroundColorAttributeName: UIColor.systemBlueColor};
    self.descriptionTextView.delegate = self;
    [self.contentView addSubview:self.descriptionTextView];

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

- (void)configureWithData:(NSDictionary *)data {
    self.announcementTitleLabel.text = data[@"title"];

    NSString *descHTML = data[@"description"];
    NSAttributedString *attrDesc = [[NSAttributedString alloc] initWithData:[descHTML dataUsingEncoding:NSUnicodeStringEncoding]
                                                                    options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType}
                                                         documentAttributes:nil
                                                                      error:nil];
    self.descriptionTextView.attributedText = attrDesc;

    NSString *dateStr = data[@"start_date"];
    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];

    NSString *imageURL = data[@"image"];
    if (imageURL.length > 0) {
        NSURL *url = [NSURL URLWithString:imageURL];
          dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [ImageCacheHelper loadImageWithURL:url completion:^(UIImage *image) {
              if (!image) return;
              UIImage *img = image;
              dispatch_async(dispatch_get_main_queue(), ^{
                self.announcementImage.image = img;
                for (NSLayoutConstraint *c in self.announcementImage.constraints) {
                  if (c.firstAttribute == NSLayoutAttributeHeight) {
                    [self.announcementImage removeConstraint:c];
                  }
                }
                CGFloat ratio = img.size.height / img.size.width;
                [self.announcementImage.heightAnchor constraintEqualToAnchor:self.announcementImage.widthAnchor multiplier:ratio].active = YES;
              });
            }];
          }
       );
    }
}

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

- (void)viewImageFullScreen {
    if (!self.announcementImage.image) return;

    UIViewController *vc = [[UIViewController alloc] init];
    vc.view.backgroundColor = UIColor.blackColor;

    UIImageView *imgView = [[UIImageView alloc] initWithImage:self.announcementImage.image];
    imgView.contentMode = UIViewContentModeScaleAspectFit;
    imgView.frame = vc.view.bounds;
    imgView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [vc.view addSubview:imgView];

    // Tap to dismiss
    UITapGestureRecognizer *dismissTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissFullScreenImage:)];
    [vc.view addGestureRecognizer:dismissTap];

    [self presentViewController:vc animated:YES completion:nil];
}

- (void)dismissFullScreenImage:(UITapGestureRecognizer *)tap {
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end


