//  AddInfoViewController.mm

#import "AddInfoViewController.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h> 
#import "APIClient.h"
#import "OfflineSyncManager.h"
#import "NetworkManager.h"

@interface AddInfoViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIDocumentPickerDelegate>

@property (nonatomic, strong) UIView *navBar;
@property (nonatomic, strong) UIButton *backButton;
@property (nonatomic, strong) UILabel *titleLabel;

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIView *contentView;

@property (nonatomic, strong) UILabel *referenceLabel;
@property (nonatomic, strong) UILabel *commentLabel;
@property (nonatomic, strong) UITextView *commentTextView;

@property (nonatomic, strong) UILabel *imageUploadLabel;
@property (nonatomic, strong) UIView *imageContainer;

@property (nonatomic, strong) UILabel *mediaUploadLabel;
@property (nonatomic, strong) UIView *mediaContainer;
@property (nonatomic, strong) UILabel *mediaRules;

@property (nonatomic, strong) UIButton *submitButton;

@property (nonatomic, strong) NSMutableArray<UIButton *> *uploadButtons;
@property (nonatomic, strong) NSMutableArray<UIImage *> *uploadedImages;
@property (nonatomic, assign) NSInteger activeUploadIndex;

@property (nonatomic, strong) UIButton *mediaUploadButton;
@property (nonatomic, strong) NSURL *selectedMediaURL;
@property (nonatomic, assign) BOOL isPickingMedia;

@end

@implementation AddInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;
    self.uploadButtons = [NSMutableArray array];
    self.uploadedImages = [NSMutableArray array];
    self.activeUploadIndex = -1;

    [self setupNavBar];
    [self setupScrollView];
    [self setupContent];
    [self setupConstraints];
  
  NSLog(@"📦 Data received by Add Info:\n issueID: %@\n planID: %@\n status: %@\n unitName: %@\n reference: %@",
      self.issueID,
      self.planID,
      self.status,
      self.unitName,
      self.reference);
}

#pragma mark - UI Setup
- (void)setupNavBar {
    self.navBar = [UIView new];
    self.navBar.backgroundColor = [UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0];
    self.navBar.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.navBar];

    self.backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.backButton setImage:[UIImage systemImageNamed:@"chevron.left"] forState:UIControlStateNormal];
    self.backButton.tintColor = UIColor.whiteColor;
    self.backButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.backButton addTarget:self action:@selector(backTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.navBar addSubview:self.backButton];

    self.titleLabel = [UILabel new];
    self.titleLabel.text = @"Add Info";
    self.titleLabel.textColor = UIColor.whiteColor;
    self.titleLabel.font = [UIFont systemFontOfSize:18 weight:UIFontWeightMedium];
    self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.navBar addSubview:self.titleLabel];
}

- (void)setupScrollView {
    self.scrollView = [UIScrollView new];
    self.scrollView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.scrollView];

    self.contentView = [UIView new];
    self.contentView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.scrollView addSubview:self.contentView];
}

- (void)setupContent {
    self.referenceLabel = [UILabel new];
    self.referenceLabel.text = self.reference ?: @"";
    self.referenceLabel.font = [UIFont boldSystemFontOfSize:20];
    self.referenceLabel.translatesAutoresizingMaskIntoConstraints = NO;

    self.commentLabel = [UILabel new];
    self.commentLabel.text = @"* Comment";
    self.commentLabel.font = [UIFont boldSystemFontOfSize:16];
    self.commentLabel.translatesAutoresizingMaskIntoConstraints = NO;

    self.commentTextView = [UITextView new];
    self.commentTextView.layer.borderWidth = 1.0;
    self.commentTextView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.commentTextView.layer.cornerRadius = 12;
    self.commentTextView.font = [UIFont systemFontOfSize:15];
    self.commentTextView.translatesAutoresizingMaskIntoConstraints = NO;

    self.imageUploadLabel = [UILabel new];
    self.imageUploadLabel.text = @"Image Upload";
    self.imageUploadLabel.font = [UIFont boldSystemFontOfSize:16];
    self.imageUploadLabel.translatesAutoresizingMaskIntoConstraints = NO;

    self.imageContainer = [UIView new];
    self.imageContainer.layer.borderWidth = 1.0;
    self.imageContainer.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.imageContainer.layer.cornerRadius = 12;
    self.imageContainer.translatesAutoresizingMaskIntoConstraints = NO;
    
    UIStackView *uploadImageStack = [[UIStackView alloc] init];
    uploadImageStack.axis = UILayoutConstraintAxisHorizontal;
    uploadImageStack.spacing = 12;
    uploadImageStack.distribution = UIStackViewDistributionFillEqually;
    uploadImageStack.translatesAutoresizingMaskIntoConstraints = NO;

    for (NSInteger i = 0; i < 2; i++) {
        UIButton *box = [self makeUploadBox];
        box.tag = 1000 + i;
        [self.uploadButtons addObject:box];
        [uploadImageStack addArrangedSubview:box];
    }

    [self.imageContainer addSubview:uploadImageStack];

    [NSLayoutConstraint activateConstraints:@[
        [uploadImageStack.topAnchor constraintEqualToAnchor:self.imageContainer.topAnchor constant:12],
        [uploadImageStack.leadingAnchor constraintEqualToAnchor:self.imageContainer.leadingAnchor constant:12],
        [uploadImageStack.trailingAnchor constraintEqualToAnchor:self.imageContainer.trailingAnchor constant:-12],
        [uploadImageStack.bottomAnchor constraintEqualToAnchor:self.imageContainer.bottomAnchor constant:-12],
    ]];

    self.mediaUploadLabel = [UILabel new];
    self.mediaUploadLabel.text = @"Media Upload";
    self.mediaUploadLabel.font = [UIFont boldSystemFontOfSize:16];
    self.mediaUploadLabel.translatesAutoresizingMaskIntoConstraints = NO;

    self.mediaContainer = [UIView new];
    self.mediaContainer.layer.borderWidth = 1.0;
    self.mediaContainer.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.mediaContainer.layer.cornerRadius = 12;
    self.mediaContainer.translatesAutoresizingMaskIntoConstraints = NO;
  
    self.mediaUploadButton = [self makeUploadBox];
    self.mediaUploadButton.tag = 2000; // distinct namespace
    [self.mediaUploadButton setTitle:@"Choose Media" forState:UIControlStateNormal];

    [self.mediaContainer addSubview:self.mediaUploadButton];

    [NSLayoutConstraint activateConstraints:@[
        [self.mediaUploadButton.topAnchor constraintEqualToAnchor:self.mediaContainer.topAnchor constant:12],
        [self.mediaUploadButton.leadingAnchor constraintEqualToAnchor:self.mediaContainer.leadingAnchor constant:12],
        [self.mediaUploadButton.trailingAnchor constraintEqualToAnchor:self.mediaContainer.trailingAnchor constant:-12],
        [self.mediaUploadButton.bottomAnchor constraintEqualToAnchor:self.mediaContainer.bottomAnchor constant:-12],
    ]];

    self.mediaRules = [UILabel new];
    self.mediaRules.text = @"- Video duration should be 5 seconds or less.\n- Video file size should be nor more than 15MB.\n- Supported document format are .pdf, .docx, .xlsx, .csv.\n-Document file size should not be more than 15MB.";
    self.mediaRules.font = [UIFont boldSystemFontOfSize:12];
    self.mediaRules.translatesAutoresizingMaskIntoConstraints = NO;
  
    self.submitButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.submitButton setTitle:@"SUBMIT" forState:UIControlStateNormal];
    self.submitButton.backgroundColor = [UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0];
    [self.submitButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    self.submitButton.layer.cornerRadius = 8;
    self.submitButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.submitButton addTarget:self action:@selector(submitTapped) forControlEvents:UIControlEventTouchUpInside];

    [self.contentView addSubview:self.referenceLabel];
    [self.contentView addSubview:self.commentLabel];
    [self.contentView addSubview:self.commentTextView];
    [self.contentView addSubview:self.imageUploadLabel];
    [self.contentView addSubview:self.imageContainer];
    [self.contentView addSubview:self.mediaUploadLabel];
    [self.contentView addSubview:self.mediaContainer];
    [self.contentView addSubview:self.mediaRules];
    [self.contentView addSubview:self.submitButton];
}

#pragma mark - Constraints

- (void)setupConstraints {
    UILayoutGuide *safe = self.view.safeAreaLayoutGuide;

    // Nav bar
    [NSLayoutConstraint activateConstraints:@[
        [self.navBar.topAnchor constraintEqualToAnchor:safe.topAnchor],
        [self.navBar.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.navBar.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.navBar.heightAnchor constraintEqualToConstant:48],

        [self.backButton.leadingAnchor constraintEqualToAnchor:self.navBar.leadingAnchor constant:12],
        [self.backButton.centerYAnchor constraintEqualToAnchor:self.navBar.centerYAnchor],

        [self.titleLabel.centerXAnchor constraintEqualToAnchor:self.navBar.centerXAnchor],
        [self.titleLabel.centerYAnchor constraintEqualToAnchor:self.navBar.centerYAnchor],
    ]];

    // Scroll view
    [NSLayoutConstraint activateConstraints:@[
        [self.scrollView.topAnchor constraintEqualToAnchor:self.navBar.bottomAnchor],
        [self.scrollView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.scrollView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.scrollView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor],

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

    // Content
    [NSLayoutConstraint activateConstraints:@[
        [self.referenceLabel.topAnchor constraintEqualToAnchor:self.contentView.topAnchor constant:16],
        [self.referenceLabel.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],
        [self.referenceLabel.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-16],

        [self.commentLabel.topAnchor constraintEqualToAnchor:self.referenceLabel.bottomAnchor constant:16],
        [self.commentLabel.leadingAnchor constraintEqualToAnchor:self.referenceLabel.leadingAnchor],

        [self.commentTextView.topAnchor constraintEqualToAnchor:self.commentLabel.bottomAnchor constant:12],
        [self.commentTextView.leadingAnchor constraintEqualToAnchor:self.referenceLabel.leadingAnchor],
        [self.commentTextView.trailingAnchor constraintEqualToAnchor:self.referenceLabel.trailingAnchor],
        [self.commentTextView.heightAnchor constraintEqualToConstant:220],

        [self.imageUploadLabel.topAnchor constraintEqualToAnchor:self.commentTextView.bottomAnchor constant:24],
        [self.imageUploadLabel.leadingAnchor constraintEqualToAnchor:self.referenceLabel.leadingAnchor],

        [self.imageContainer.topAnchor constraintEqualToAnchor:self.imageUploadLabel.bottomAnchor constant:12],
        [self.imageContainer.leadingAnchor constraintEqualToAnchor:self.referenceLabel.leadingAnchor],
        [self.imageContainer.trailingAnchor constraintEqualToAnchor:self.referenceLabel.trailingAnchor],
        [self.imageContainer.heightAnchor constraintEqualToConstant:96],
        
        [self.mediaUploadLabel.topAnchor constraintEqualToAnchor:self.imageContainer.bottomAnchor constant:24],
        [self.mediaUploadLabel.leadingAnchor constraintEqualToAnchor:self.referenceLabel.leadingAnchor],

        [self.mediaContainer.topAnchor constraintEqualToAnchor:self.mediaUploadLabel.bottomAnchor constant:12],
        [self.mediaContainer.leadingAnchor constraintEqualToAnchor:self.referenceLabel.leadingAnchor],
        [self.mediaContainer.trailingAnchor constraintEqualToAnchor:self.referenceLabel.trailingAnchor],
        [self.mediaContainer.heightAnchor constraintEqualToConstant:96],
        
        [self.mediaRules.topAnchor constraintEqualToAnchor:self.mediaContainer.bottomAnchor constant:12],
        [self.mediaRules.leadingAnchor constraintEqualToAnchor:self.referenceLabel.leadingAnchor],

        [self.submitButton.topAnchor constraintEqualToAnchor:self.mediaRules.bottomAnchor constant:40],
        [self.submitButton.leadingAnchor constraintEqualToAnchor:self.referenceLabel.leadingAnchor],
        [self.submitButton.trailingAnchor constraintEqualToAnchor:self.referenceLabel.trailingAnchor],
        [self.submitButton.heightAnchor constraintEqualToConstant:48],
        [self.submitButton.bottomAnchor constraintEqualToAnchor:self.contentView.bottomAnchor constant:-24],
    ]];
}

#pragma mark - Upload Buttons
- (UIButton *)makeUploadBox {
    UIButton *upload = [UIButton buttonWithType:UIButtonTypeCustom]; // ✅ not System
    upload.translatesAutoresizingMaskIntoConstraints = NO;
    upload.layer.borderWidth = 1.0;
    upload.layer.cornerRadius = 8;
    upload.layer.borderColor = [UIColor lightGrayColor].CGColor;
    [upload setTitle:@"Upload" forState:UIControlStateNormal];
    [upload setTitleColor:[UIColor colorWithRed:0/255.0 green:109/255.0 blue:141/255.0 alpha:1] forState:UIControlStateNormal];
    [upload setImage:[UIImage systemImageNamed:@"camera"] forState:UIControlStateNormal];
    upload.tintColor = [UIColor colorWithRed:0/255.0 green:109/255.0 blue:141/255.0 alpha:1];
    upload.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 8);
    upload.titleLabel.font = [UIFont boldSystemFontOfSize:14];
    [upload addTarget:self action:@selector(handleUploadTap:) forControlEvents:UIControlEventTouchUpInside];
    return upload;
}

- (void)handleUploadTap:(UIButton *)sender {
    // MEDIA UPLOAD
    if (sender.tag == 2000) {
        [self presentMediaPickerSheet];
        return;
    }
  
    NSInteger index = sender.tag - 1000;
    self.activeUploadIndex = index;
    UIAlertController *sheet = [UIAlertController alertControllerWithTitle:@"Upload Image"
                                                                   message:nil
                                                            preferredStyle:UIAlertControllerStyleActionSheet];

    [sheet addAction:[UIAlertAction actionWithTitle:@"Camera"
                                              style:UIAlertActionStyleDefault
                                            handler:^(UIAlertAction * _Nonnull action) {
        [self openImagePickerForIndex:index source:UIImagePickerControllerSourceTypeCamera];
    }]];

    [sheet addAction:[UIAlertAction actionWithTitle:@"Gallery"
                                              style:UIAlertActionStyleDefault
                                            handler:^(UIAlertAction * _Nonnull action) {
        [self openImagePickerForIndex:index source:UIImagePickerControllerSourceTypePhotoLibrary];
    }]];

    [sheet addAction:[UIAlertAction actionWithTitle:@"Cancel"
                                              style:UIAlertActionStyleCancel
                                            handler:nil]];

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

- (void)openImagePickerForIndex:(NSInteger)index source:(UIImagePickerControllerSourceType)source {
    if (![UIImagePickerController isSourceTypeAvailable:source]) return;

    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.sourceType = source;
    [self presentViewController:picker animated:YES completion:nil];
}

- (void)presentMediaPickerSheet {
    UIAlertController *sheet =
    [UIAlertController alertControllerWithTitle:@"Upload Media"
                                        message:nil
                                 preferredStyle:UIAlertControllerStyleActionSheet];

    [sheet addAction:[UIAlertAction actionWithTitle:@"Video"
                                              style:UIAlertActionStyleDefault
                                            handler:^(UIAlertAction * _Nonnull action) {
        [self openVideoPicker];
    }]];

    [sheet addAction:[UIAlertAction actionWithTitle:@"Document"
                                              style:UIAlertActionStyleDefault
                                            handler:^(UIAlertAction * _Nonnull action) {
        [self openDocumentPicker];
    }]];

    [sheet addAction:[UIAlertAction actionWithTitle:@"Cancel"
                                              style:UIAlertActionStyleCancel
                                            handler:nil]];

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

- (void)openVideoPicker {
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) return;

    UIImagePickerController *picker = [UIImagePickerController new];
    picker.delegate = self;
    picker.videoMaximumDuration = 5.0;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

    // Support both iOS 14+ and older
    if (@available(iOS 14.0, *)) {
        picker.mediaTypes = @[(NSString *)UTTypeMovie.identifier];
    } else {
        picker.mediaTypes = @[(NSString *)kUTTypeMovie];
    }

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

- (void)openDocumentPicker {
    NSArray *types = @[
        @"com.adobe.pdf",
        @"org.openxmlformats.wordprocessingml.document",
        @"org.openxmlformats.spreadsheetml.sheet",
        @"public.comma-separated-values-text"
    ];

    UIDocumentPickerViewController *picker =
    [[UIDocumentPickerViewController alloc] initWithDocumentTypes:types
                                                           inMode:UIDocumentPickerModeImport];
    picker.delegate = self;
    [self presentViewController:picker animated:YES completion:nil];
}

- (void)handleSelectedMediaURL:(NSURL *)url {
    if (![self isFileSizeValid:url]) {
//        [self showAlert:@"File too large (max 15MB)"];
        NSLog(@"File size too big");
        return;
      
    }

    self.selectedMediaURL = url;

    [self.mediaUploadButton setTitle:url.lastPathComponent
                            forState:UIControlStateNormal];
    [self.mediaUploadButton setImage:[UIImage systemImageNamed:@"doc.fill"]
                            forState:UIControlStateNormal];
}

#pragma mark - UIDocumentPickerDelegate

- (void)documentPicker:(UIDocumentPickerViewController *)controller
didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls {

    NSURL *url = urls.firstObject;
    if (!url) return;

    [self handleSelectedMediaURL:url];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {

    NSString *mediaType = info[UIImagePickerControllerMediaType];

    // Check video
    BOOL isVideo = NO;
    if (@available(iOS 14.0, *)) {
        isVideo = [mediaType isEqualToString:UTTypeMovie.identifier];
    } else {
        isVideo = [mediaType isEqualToString:(NSString *)kUTTypeMovie];
    }

    if (isVideo) {
        NSURL *videoURL = info[UIImagePickerControllerMediaURL];
        [self handleSelectedMediaURL:videoURL];
        [picker dismissViewControllerAnimated:YES completion:nil];
        return;
    }

    // Otherwise treat as image
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    image = [self resizedImage:image maxDimension:1280];
    NSInteger index = self.activeUploadIndex;

    if (index < self.uploadedImages.count) {
        self.uploadedImages[index] = image;
    } else {
        [self.uploadedImages addObject:image];
    }

    UIButton *button = self.uploadButtons[index];
    if ([button isKindOfClass:[UIButton class]]) {
        [button setTitle:nil forState:UIControlStateNormal];
        [button setImage:image forState:UIControlStateNormal];
        button.imageView.contentMode = UIViewContentModeScaleAspectFill;
        button.imageView.clipsToBounds = YES;
        button.layer.masksToBounds = YES;
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
        button.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;
        button.imageEdgeInsets = UIEdgeInsetsZero;

        [self addRemoveButtonToUpload:button atIndex:index];
    }

    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)addRemoveButtonToUpload:(UIButton *)uploadBtn atIndex:(NSInteger)index {
    // Remove existing remove button if any (avoid duplicates)
    for (UIView *sub in uploadBtn.subviews) {
        if (sub.tag == 9000) {
            [sub removeFromSuperview];
        }
    }

    // Create small X button
    UIButton *removeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    removeBtn.tag = 9000;
    removeBtn.translatesAutoresizingMaskIntoConstraints = NO;
    [removeBtn setImage:[UIImage systemImageNamed:@"xmark.circle.fill"] forState:UIControlStateNormal];
    removeBtn.tintColor = [UIColor whiteColor];
    removeBtn.backgroundColor = [UIColor colorWithWhite:0 alpha:0.4];
    removeBtn.layer.cornerRadius = 10;
    removeBtn.clipsToBounds = YES;
    removeBtn.contentEdgeInsets = UIEdgeInsetsMake(4, 4, 4, 4);
    removeBtn.accessibilityIdentifier = [NSString stringWithFormat:@"remove_%ld", (long)index];
    [removeBtn addTarget:self action:@selector(handleRemoveImage:) forControlEvents:UIControlEventTouchUpInside];

    [uploadBtn addSubview:removeBtn];

    // Position in top-right corner
    [NSLayoutConstraint activateConstraints:@[
        [removeBtn.topAnchor constraintEqualToAnchor:uploadBtn.topAnchor constant:4],
        [removeBtn.trailingAnchor constraintEqualToAnchor:uploadBtn.trailingAnchor constant:-4],
        [removeBtn.widthAnchor constraintEqualToConstant:20],
        [removeBtn.heightAnchor constraintEqualToConstant:20],
    ]];
}

- (void)handleRemoveImage:(UIButton *)sender {
    UIView *uploadBtn = sender.superview;
    if (![uploadBtn isKindOfClass:[UIButton class]]) return;

    NSInteger index = ((UIButton *)uploadBtn).tag - 1000;
    if (index < self.uploadedImages.count) {
        self.uploadedImages[index] = (id)[NSNull null];
    }

    // Reset upload button
    UIButton *button = (UIButton *)uploadBtn;
    [button setImage:[UIImage systemImageNamed:@"camera"] forState:UIControlStateNormal];
    [button setTitle:@"Upload" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor colorWithRed:0/255.0 green:109/255.0 blue:141/255.0 alpha:1] forState:UIControlStateNormal];
    button.tintColor = [UIColor colorWithRed:0/255.0 green:109/255.0 blue:141/255.0 alpha:1];
    button.imageView.contentMode = UIViewContentModeCenter;
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    button.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    button.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 8);

    // Remove the small "x" button
    [sender removeFromSuperview];
}

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

- (void)submitTapped {
    if (self.commentTextView.text.length == 0) {
        [self showAlertWithTitle:@"Missing Comment"
                         message:@"Please enter a comment."];
        return;
    }
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Confirm Submission"
                                                                   message:@"Are you sure you want to submit this issue?"
                                                            preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"Submit"
                                                            style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * _Nonnull action) {
        [self performSubmit];
    }];

    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel"
                                                           style:UIAlertActionStyleCancel
                                                         handler:nil];

    [alert addAction:cancelAction];
    [alert addAction:confirmAction];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)performSubmit {

    NSArray<UIImage *> *images = [self validImages];
    BOOL hasImages = images.count > 0;
    BOOL hasMedia = (self.selectedMediaURL != nil);

    NSLog(@"📤 Submitting AddInfo | images=%lu | media=%@",
          (unsigned long)images.count,
          self.selectedMediaURL.lastPathComponent);
  
    NSString *mediaType = nil;
    if (hasMedia) {
        NSString *ext = self.selectedMediaURL.pathExtension.lowercaseString;
        if ([@[@"mp4", @"mov"] containsObject:ext]) {
            mediaType = @"Video";
        } else {
            mediaType = @"Document";
        }
    }

    if (![NetworkManager.sharedManager isConnected]) {
        NSDictionary *displayData = @{
            @"projectName": self.projectName ?: @"Unknown Project",
            @"unitName": self.projectCode ?: @"-",
            @"createdBy": @"Athirah Zaidi",
            @"createdAt": [self todayDateString],
            @"issueDisplay": @"Add Info",
        };
      
      NSLog(@"add info displayData %@", displayData);
      
        [[OfflineSyncManager shared] queueAddInfo:self.issueID
                                          remarks:self.commentTextView.text
                                      displayInfo:displayData
                                           images:images
                                          mediaURL:self.selectedMediaURL
                                         mediaType:mediaType];
        [self showAlertWithTitle:@"Saved Offline"
                         message:@"This will be synced when you're back online."];
        UIViewController *presenter = self.presentingViewController;
        if (presenter.presentingViewController) {
            [presenter.presentingViewController dismissViewControllerAnimated:YES completion:nil];
            return;
        } else {
            [self dismissViewControllerAnimated:YES completion:nil];
            return;
        }
    }

    if (!hasImages && !hasMedia) {
        // ✅ JSON ONLY
        [APIClient submitAddInfo:self.issueID
                         remarks:self.commentTextView.text
                       completion:^(BOOL success, NSDictionary *response, NSError *error) {
            [self handleSubmitResponse:response error:error];
        }];
        return;
    }
    [APIClient uploadAddInfo:self.issueID
                     remarks:self.commentTextView.text
                      images:images
                    mediaURL:self.selectedMediaURL
                   mediaType:mediaType
                  completion:^(BOOL success, NSDictionary *response, NSError *error) {
        [self handleSubmitResponse:response error:error];
    }];
}

- (void)handleSubmitResponse:(NSDictionary *)response error:(NSError *)error {

    dispatch_async(dispatch_get_main_queue(), ^{
        if (error) {
            [self showAlertWithTitle:@"Submission Failed"
                             message:error.localizedDescription ?: @"Unknown error"];
            return;
        }

        NSDictionary *appData = response[@"AppData"];
        if ([appData[@"status"] isEqualToString:@"success"]) {

            UIAlertController *success =
            [UIAlertController alertControllerWithTitle:@"Success"
                                                message:@"Info submitted successfully."
                                         preferredStyle:UIAlertControllerStyleAlert];

            [success addAction:[UIAlertAction actionWithTitle:@"OK"
                                                        style:UIAlertActionStyleDefault
                                                      handler:^(UIAlertAction * _Nonnull action) {
                UIViewController *presenter = self.presentingViewController;
                if (presenter.presentingViewController) {
                    [presenter.presentingViewController dismissViewControllerAnimated:YES completion:nil];
                } else {
                    [self dismissViewControllerAnimated:YES completion:nil];
                }
            }]];

            [self presentViewController:success animated:YES completion:nil];
        } else {
            NSString *msg = appData[@"message"] ?: @"Server error";
            [self showAlertWithTitle:@"Submission Error" message:msg];
        }
    });
}

#pragma mark - Helpers
- (UIImage *)resizedImage:(UIImage *)image maxDimension:(CGFloat)maxDim {
    CGSize size = image.size;
    CGFloat scale = MIN(maxDim / size.width, maxDim / size.height);
    if (scale >= 1) return image;

    CGSize newSize = CGSizeMake(size.width * scale, size.height * scale);
    UIGraphicsBeginImageContextWithOptions(newSize, YES, 1.0);
    [image drawInRect:(CGRect){CGPointZero, newSize}];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

- (BOOL)isFileSizeValid:(NSURL *)url {
    NSNumber *size;
    [url getResourceValue:&size forKey:NSURLFileSizeKey error:nil];
    return size.longLongValue <= (15 * 1024 * 1024);
}

- (void)showAlertWithTitle:(NSString *)title message:(NSString *)message {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title
                                                                   message:message
                                                            preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:ok];
    [self presentViewController:alert animated:YES completion:nil];
}

- (NSArray<UIImage *> *)validImages {
    NSMutableArray *valid = [NSMutableArray array];
    for (id obj in self.uploadedImages) {
        if ([obj isKindOfClass:[UIImage class]]) {
            [valid addObject:obj];
        }
    }
    return valid;
}

- (NSString *)todayDateString {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
    formatter.dateFormat = @"yyyy-MM-dd";
    return [formatter stringFromDate:[NSDate date]];
}

@end
