#import "IssueDetailViewController.h"
#import "HistoryViewController.h"

@interface IssueDetailViewController ()

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UIImageView *issueImageView;
@property (nonatomic, strong) UILabel *refLabel;
@property (nonatomic, strong) UILabel *statusLabel;

@property (nonatomic, strong) UIView *detailsCard;
@property (nonatomic, strong) UIButton *editButton;
@property (nonatomic, strong) UIButton *deleteButton;

@end

@implementation IssueDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor systemGray6Color];
    self.title = @"Issue Details";

    NSLog(@"📦 Received Issue Data: %@", self.issueData);
    NSString *text = [NSString stringWithFormat:@"%@", self.issueData];
    NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    NSString *filePath = [docsPath stringByAppendingPathComponent:@"issueData.txt"];

    // Convert issueData to a readable string
    NSString *plainText = [NSString stringWithFormat:@"%@", self.issueData];

    // Write as plain UTF-8 text
    [plainText writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];

    // Log the path so you can find it
    NSLog(@"📁 issueData saved as plain text to: %@", filePath);

    [self setupHeader];
    [self setupScrollView];
    [self setupHeaderImage];
    [self setupDetailsCard];
    [self setupButtons];
    [self populateData];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

    UIView *headerView = [self.view viewWithTag:999];
    if (!headerView) return;

    // ✅ Use updated safe area now that it’s available
    UILayoutGuide *safe = self.view.safeAreaLayoutGuide;
    CGFloat topInset = safe.layoutFrame.origin.y;
    CGFloat headerHeight = 56.0 + topInset;
    headerView.frame = CGRectMake(0, 0, self.view.bounds.size.width, headerHeight);

    // ✅ Adjust subviews within header
    UIButton *backButton = [headerView viewWithTag:1];
    UILabel *titleLabel = [headerView viewWithTag:2];
    UIButton *historyButton = [headerView viewWithTag:3];

    backButton.frame = CGRectMake(12, topInset + 8, 44, 40);
    titleLabel.frame = CGRectMake(0, topInset + 8, self.view.bounds.size.width, 40);
    historyButton.frame = CGRectMake(self.view.bounds.size.width - 56, topInset + 8, 44, 40);

    // ✅ Shift scroll view below header
    CGFloat headerBottom = CGRectGetMaxY(headerView.frame);
    self.scrollView.frame = CGRectMake(0, headerBottom, self.view.bounds.size.width, self.view.bounds.size.height - headerBottom);
}

#pragma mark - Header Setup
- (void)setupHeader {
    UIView *headerView = [[UIView alloc] init];
    headerView.backgroundColor = [UIColor colorWithRed:0/255.0
                                                 green:109/255.0
                                                  blue:141/255.0
                                                 alpha:1.0];
    headerView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    headerView.tag = 999;
    [self.view addSubview:headerView];

    // --- Back Button ---
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    backButton.tag = 1;
    [backButton setImage:[UIImage systemImageNamed:@"chevron.left"] forState:UIControlStateNormal];
    backButton.tintColor = UIColor.whiteColor;
    [backButton addTarget:self action:@selector(handleBackTap) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:backButton];

    // --- Title ---
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.tag = 2;
    titleLabel.text = @"Issue Details";
    titleLabel.font = [UIFont boldSystemFontOfSize:18];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = UIColor.whiteColor;
    [headerView addSubview:titleLabel];

    // --- History Button ---
    UIButton *historyButton = [UIButton buttonWithType:UIButtonTypeSystem];
    historyButton.tag = 3;
    [historyButton setImage:[UIImage systemImageNamed:@"clock.arrow.circlepath"] forState:UIControlStateNormal];
    historyButton.tintColor = UIColor.whiteColor;
    [historyButton addTarget:self action:@selector(handleHistoryTap) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:historyButton];
}

#pragma mark - UI Setup

- (void)setupScrollView {
    UIView *headerView = [self.view viewWithTag:999];
    CGFloat headerBottom = CGRectGetMaxY(headerView.frame);

    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, headerBottom, self.view.bounds.size.width, self.view.bounds.size.height - headerBottom)];
    self.scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.scrollView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.scrollView];
}

- (void)setupHeaderImage {
    CGFloat imageHeight = 230;
    self.issueImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, imageHeight)];
    self.issueImageView.contentMode = UIViewContentModeScaleAspectFill;
    self.issueImageView.clipsToBounds = YES;
    self.issueImageView.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];
    [self.scrollView addSubview:self.issueImageView];
}

- (void)setupDetailsCard {
    CGFloat topOffset = 220;
    CGFloat padding = 20;

    self.detailsCard = [[UIView alloc] initWithFrame:CGRectMake(0, topOffset, self.view.bounds.size.width, 420)];
    self.detailsCard.backgroundColor = UIColor.whiteColor;
    self.detailsCard.layer.cornerRadius = 20;
    self.detailsCard.layer.maskedCorners = kCALayerMinXMinYCorner | kCALayerMaxXMinYCorner;
    [self.scrollView addSubview:self.detailsCard];

    CGFloat y = 20;

    // --- Reference ID ---
    self.refLabel = [[UILabel alloc] initWithFrame:CGRectMake(padding, y, self.view.bounds.size.width - 2*padding, 24)];
    self.refLabel.font = [UIFont boldSystemFontOfSize:20];
    [self.detailsCard addSubview:self.refLabel];
    y += 36;

    // --- Status Capsule ---
    self.statusLabel = [[UILabel alloc] initWithFrame:CGRectMake(padding, y, 90, 28)];
    self.statusLabel.font = [UIFont boldSystemFontOfSize:14];
    self.statusLabel.textColor = UIColor.whiteColor;
    self.statusLabel.textAlignment = NSTextAlignmentCenter;
    self.statusLabel.layer.cornerRadius = 14;
    self.statusLabel.layer.masksToBounds = YES;
    [self.detailsCard addSubview:self.statusLabel];
    y += 50;

    // --- Info Labels ---
    NSArray *titles = @[@"Created Date", @"Location", @"Category", @"Type", @"Issue", @"Created By", @"Comment"];
    for (NSString *title in titles) {
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(padding, y, 120, 22)];
        titleLabel.text = [NSString stringWithFormat:@"%@ :", title];
        titleLabel.textColor = UIColor.darkGrayColor;
        titleLabel.font = [UIFont systemFontOfSize:15];
        [self.detailsCard addSubview:titleLabel];

        UILabel *valueLabel = [[UILabel alloc] initWithFrame:CGRectMake(padding + 130, y, self.view.bounds.size.width - 150, 22)];
        valueLabel.tag = [titles indexOfObject:title] + 100; // tag for later update
        valueLabel.textColor = UIColor.blackColor;
        valueLabel.font = [UIFont systemFontOfSize:15 weight:UIFontWeightMedium];
        [self.detailsCard addSubview:valueLabel];
        y += 28;
    }
}

- (void)setupButtons {
    CGFloat y = CGRectGetMaxY(self.detailsCard.frame) + 4;
    CGFloat buttonWidth = (self.view.bounds.size.width - 60) / 2;

    // --- Edit Button ---
    self.editButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.editButton.frame = CGRectMake(20, y, buttonWidth, 44);
    [self.editButton setTitle:@"Edit Issue" forState:UIControlStateNormal];
    [self.editButton setTitleColor:[UIColor colorWithRed:0/255.0 green:115/255.0 blue:130/255.0 alpha:1] forState:UIControlStateNormal];
    [self.editButton addTarget:self action:@selector(editIssueTapped) forControlEvents:UIControlEventTouchUpInside];
    self.editButton.layer.cornerRadius = 8;
    self.editButton.layer.borderWidth = 1;
    self.editButton.layer.borderColor = [UIColor colorWithRed:0/255.0 green:115/255.0 blue:130/255.0 alpha:1].CGColor;
    [self.scrollView addSubview:self.editButton];

    // --- Delete Button ---
    self.deleteButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.deleteButton.frame = CGRectMake(CGRectGetMaxX(self.editButton.frame) + 20, y, buttonWidth, 44);
    [self.deleteButton setTitle:@"Delete Issue" forState:UIControlStateNormal];
    [self.deleteButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [self.deleteButton addTarget:self action:@selector(deleteIssueTapped) forControlEvents:UIControlEventTouchUpInside];
    self.deleteButton.backgroundColor = [UIColor systemRedColor];
    self.deleteButton.layer.cornerRadius = 8;
    [self.scrollView addSubview:self.deleteButton];

    CGFloat totalHeight = CGRectGetMaxY(self.deleteButton.frame) + 30;
    self.scrollView.contentSize = CGSizeMake(self.view.bounds.size.width, totalHeight);
}

- (void)editIssueTapped {
    NSLog(@"✏️ Edit Issue tapped");
    // You can later navigate to an edit screen or present a modal here
}

- (void)deleteIssueTapped {
    NSLog(@"🗑️ Delete Issue tapped");
    // need to fill up later
}

#pragma mark - Data

- (void)populateData {
    if (!self.issueData) return;

    NSString *ref = self.issueData[@"issue_reference"] ?: self.issueData[@"reference"] ?: @"Unknown Reference";
    NSString *status = self.issueData[@"status_external"] ?: @"No Status";
    NSString *statusColor = self.issueData[@"status_ex_color"] ?: @"#999999";
    NSString *imageURL = self.issueData[@"image"];
    // it is the correct spelling for self.issueData[@"creted_by"]
    NSDictionary *createdBy = self.issueData[@"creted_by"];
    NSArray *values = @[
        self.issueData[@"created_at"] ?: @"–",
        self.issueData[@"location_name"] ?: @"–",
        self.issueData[@"category"] ?: @"–",
        self.issueData[@"type"] ?: @"–",
        self.issueData[@"issue"] ?: @"–",
        createdBy[@"name"] ?: @"-",
        self.issueData[@"remarks"] ?: @"–"
    ];

    self.refLabel.text = ref;
    self.statusLabel.text = status;
    self.statusLabel.backgroundColor = [self colorFromHex:statusColor];

    // Fill info rows
    for (int i = 0; i < values.count; i++) {
        UILabel *label = [self.detailsCard viewWithTag:100 + i];
        if ([label isKindOfClass:[UILabel class]]) {
            label.text = values[i];
        }
    }

    // Load image
    if (imageURL.length > 0) {
        NSURL *url = [NSURL URLWithString:imageURL];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSData *data = [NSData dataWithContentsOfURL:url];
            if (data) {
                UIImage *img = [UIImage imageWithData:data];
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.issueImageView.image = img;
                });
            }
        });
    }
}

#pragma mark - Helper
- (UIColor *)colorFromHex:(NSString *)hexString {
    if (!hexString || hexString.length < 6) return [UIColor grayColor];
    unsigned int rgbValue = 0;
    NSScanner *scanner = [NSScanner scannerWithString:hexString];
    if ([hexString hasPrefix:@"#"]) scanner.scanLocation = 1;
    [scanner scanHexInt:&rgbValue];
    return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16)/255.0
                           green:((rgbValue & 0x00FF00) >> 8)/255.0
                            blue:(rgbValue & 0x0000FF)/255.0
                           alpha:1.0];
}

#pragma mark - Button Actions
- (void)handleBackTap {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)handleHistoryTap {
  NSLog(@"🕓 Navigating to History");
  
  HistoryViewController *nextVC = [[HistoryViewController alloc] init];
  nextVC.modalPresentationStyle = UIModalPresentationFullScreen;
  
  nextVC.issueID = self.issueData[@"issue_reference_id"];
  nextVC.planID = self.issueData[@"plan_id"];
  nextVC.status = self.issueData[@"status_external"];
  nextVC.unitName = self.issueData[@"plan_unit"];
  nextVC.reference = self.issueData[@"reference"] ?: self.issueData[@"issue_reference"];
  
  NSLog(@"📦 Data being sent to History:\n issueID: %@\n planID: %@\n status: %@\n unitName: %@\n reference: %@",
        nextVC.issueID,
        nextVC.planID,
        nextVC.status,
        nextVC.unitName,
        nextVC.reference);
  [self presentViewController:nextVC animated:YES completion:nil];
}

@end
