#import "DetailsViewController.h"

@interface AddIssueDetailsViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate>
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UITextField *locationField;
@property (nonatomic, strong) UITextView *commentField;
@property (nonatomic, strong) UIButton *submitButton;
@property (nonatomic, strong) UIButton *resetButton;
@end

@implementation AddIssueDetailsViewController

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

    // Create all views (don’t position them yet)
    [self createHeader];
    [self createForm];
    // Set location if passed from previous screen
    if (self.selectedLocationName && self.selectedLocationName.length > 0) {
        self.locationField.text = self.selectedLocationName;
    }
    self.uploadedImages = [NSMutableArray arrayWithObjects:[NSNull null], [NSNull null], [NSNull null], nil];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

    CGFloat topInset = self.view.safeAreaInsets.top;
    CGFloat headerHeight = 48.0;

    // Header layout
    self.headerView.frame = CGRectMake(0, topInset, self.view.bounds.size.width, headerHeight);
  
    // Title Label
    UILabel *title = [self.headerView viewWithTag:101];
     if (title) {
         title.frame = CGRectMake(0, 8, self.headerView.bounds.size.width, 32);
     }

    // Scroll view layout (below header)
    CGFloat scrollY = topInset + headerHeight;
    self.scrollView.frame = CGRectMake(0, scrollY, self.view.bounds.size.width, self.view.bounds.size.height - scrollY);
}

#pragma mark - Setup

- (void)createHeader {
    // Header container
    self.headerView = [[UIView alloc] init];
    self.headerView.backgroundColor = [UIColor colorWithRed:0/255.0 green:109/255.0 blue:141/255.0 alpha:1];
    self.headerView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.headerView];
    
    // Back button (SF Symbol)
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    backButton.translatesAutoresizingMaskIntoConstraints = NO;

    UIImage *backImage = [UIImage systemImageNamed:@"chevron.left"];
    backImage = [backImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    [backButton setImage:backImage forState:UIControlStateNormal];
    backButton.tintColor = [UIColor whiteColor];
    backButton.backgroundColor = [UIColor clearColor];
    [backButton addTarget:self action:@selector(dismissSelf)
         forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:backButton];
    
    // Title label
    UILabel *title = [[UILabel alloc] init];
    title.translatesAutoresizingMaskIntoConstraints = NO;
    title.text = @"Add Issue Details";
    title.textColor = UIColor.whiteColor;
    title.font = [UIFont systemFontOfSize:18 weight:UIFontWeightMedium];
    title.textAlignment = NSTextAlignmentCenter;
    [self.headerView addSubview:title];
    
    // ✅ Reset button (refresh icon)
    self.resetButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.resetButton.translatesAutoresizingMaskIntoConstraints = NO;

    UIImage *refreshImage = [UIImage systemImageNamed:@"arrow.clockwise"];
    refreshImage = [refreshImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    [self.resetButton setImage:refreshImage forState:UIControlStateNormal];
    self.resetButton.tintColor = [UIColor whiteColor];
    self.resetButton.backgroundColor = [UIColor clearColor];
    [self.resetButton addTarget:self
                         action:@selector(handleReset)
               forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:self.resetButton];
    
    // Status bar background (same color as header)
    UIView *statusBarBackground = [[UIView alloc] init];
    statusBarBackground.backgroundColor = self.headerView.backgroundColor;
    statusBarBackground.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:statusBarBackground];

    // Auto Layout
    UILayoutGuide *safe = self.view.safeAreaLayoutGuide;
    [NSLayoutConstraint activateConstraints:@[
        // Header
        [self.headerView.topAnchor constraintEqualToAnchor:safe.topAnchor],
        [self.headerView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.headerView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.headerView.heightAnchor constraintEqualToConstant:48],

        // Back button
        [backButton.leadingAnchor constraintEqualToAnchor:self.headerView.leadingAnchor constant:8],
        [backButton.centerYAnchor constraintEqualToAnchor:self.headerView.centerYAnchor],
        [backButton.widthAnchor constraintEqualToConstant:44],
        [backButton.heightAnchor constraintEqualToConstant:44],

        // Title centered
        [title.centerXAnchor constraintEqualToAnchor:self.headerView.centerXAnchor],
        [title.centerYAnchor constraintEqualToAnchor:self.headerView.centerYAnchor],

        // ✅ Reset button (right)
        [self.resetButton.trailingAnchor constraintEqualToAnchor:self.headerView.trailingAnchor constant:-8],
        [self.resetButton.centerYAnchor constraintEqualToAnchor:self.headerView.centerYAnchor],
        [self.resetButton.widthAnchor constraintEqualToConstant:44],
        [self.resetButton.heightAnchor constraintEqualToConstant:44],

        // Status bar color fill
        [statusBarBackground.topAnchor constraintEqualToAnchor:self.view.topAnchor],
        [statusBarBackground.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [statusBarBackground.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [statusBarBackground.bottomAnchor constraintEqualToAnchor:safe.topAnchor],
    ]];
}

- (void)createForm {
    UIScrollView *scroll = [[UIScrollView alloc] init];
    scroll.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:scroll];
    self.scrollView = scroll;
    
    UILayoutGuide *safe = self.view.safeAreaLayoutGuide;
    [NSLayoutConstraint activateConstraints:@[
        [scroll.topAnchor constraintEqualToAnchor:self.headerView.bottomAnchor],
        [scroll.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [scroll.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [scroll.bottomAnchor constraintEqualToAnchor:safe.bottomAnchor],
    ]];
    
    UIView *content = [[UIView alloc] init];
    content.translatesAutoresizingMaskIntoConstraints = NO;
    [scroll addSubview:content];
    [NSLayoutConstraint activateConstraints:@[
        [content.topAnchor constraintEqualToAnchor:scroll.topAnchor],
        [content.leadingAnchor constraintEqualToAnchor:scroll.leadingAnchor],
        [content.trailingAnchor constraintEqualToAnchor:scroll.trailingAnchor],
        [content.bottomAnchor constraintEqualToAnchor:scroll.bottomAnchor],
        [content.widthAnchor constraintEqualToAnchor:scroll.widthAnchor],
    ]];

    CGFloat spacing = 16;
    UIView *lastView = nil;

    // “For” label
    UILabel *forLabel = [self makeLabelWithText:@"For" bold:NO size:14];
    [content addSubview:forLabel];
    [forLabel.topAnchor constraintEqualToAnchor:content.topAnchor constant:spacing].active = YES;
    [forLabel.leadingAnchor constraintEqualToAnchor:content.leadingAnchor constant:20].active = YES;

    UILabel *unitLabel = [self makeLabelWithText:@"Ara E Residence Dev, C-L(2)" bold:YES size:16];
    [content addSubview:unitLabel];
    [unitLabel.topAnchor constraintEqualToAnchor:forLabel.bottomAnchor constant:4].active = YES;
    [unitLabel.leadingAnchor constraintEqualToAnchor:forLabel.leadingAnchor].active = YES;
    lastView = unitLabel;

    // Location section
    UILabel *locationTitle = [self makeLabelWithText:@"*Location" bold:YES size:15];
    [content addSubview:locationTitle];
    [locationTitle.topAnchor constraintEqualToAnchor:lastView.bottomAnchor constant:spacing].active = YES;
    [locationTitle.leadingAnchor constraintEqualToAnchor:forLabel.leadingAnchor].active = YES;

    UIView *locationContainer = [self makeRoundedBox];
    [content addSubview:locationContainer];
    [NSLayoutConstraint activateConstraints:@[
        [locationContainer.topAnchor constraintEqualToAnchor:locationTitle.bottomAnchor constant:8],
        [locationContainer.leadingAnchor constraintEqualToAnchor:content.leadingAnchor constant:20],
        [locationContainer.trailingAnchor constraintEqualToAnchor:content.trailingAnchor constant:-20],
        [locationContainer.heightAnchor constraintEqualToConstant:44],
    ]];

    UITextField *locationField = [[UITextField alloc] init];
    locationField.translatesAutoresizingMaskIntoConstraints = NO;
    locationField.text = self.selectedLocationName ?: @"Select location";
    locationField.font = [UIFont systemFontOfSize:15];
    locationField.enabled = NO;
    [locationContainer addSubview:locationField];
    self.locationField = locationField;

    UIButton *reselectBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    reselectBtn.translatesAutoresizingMaskIntoConstraints = NO;
    [reselectBtn setTitle:@"Reselect" forState:UIControlStateNormal];
    [reselectBtn setTitleColor:[UIColor colorWithRed:0/255.0 green:109/255.0 blue:141/255.0 alpha:1] forState:UIControlStateNormal];
    reselectBtn.titleLabel.font = [UIFont boldSystemFontOfSize:14];
    [reselectBtn addTarget:self action:@selector(dismissSelf) forControlEvents:UIControlEventTouchUpInside];
    [locationContainer addSubview:reselectBtn];

    [NSLayoutConstraint activateConstraints:@[
        [locationField.leadingAnchor constraintEqualToAnchor:locationContainer.leadingAnchor constant:8],
        [locationField.centerYAnchor constraintEqualToAnchor:locationContainer.centerYAnchor],
        [reselectBtn.trailingAnchor constraintEqualToAnchor:locationContainer.trailingAnchor constant:-4],
        [reselectBtn.centerYAnchor constraintEqualToAnchor:locationContainer.centerYAnchor],
        [locationField.trailingAnchor constraintEqualToAnchor:reselectBtn.leadingAnchor constant:-12],
    ]];
    lastView = locationContainer;

    // Category, Type, Issue — dropdown style
    NSArray *titles = @[@"*Category", @"*Type", @"*Issue"];
    NSMutableArray *dropdowns = [NSMutableArray array];
    for (NSString *t in titles) {
        UILabel *lbl = [self makeLabelWithText:t bold:YES size:15];
        [content addSubview:lbl];
        [lbl.topAnchor constraintEqualToAnchor:lastView.bottomAnchor constant:spacing].active = YES;
        [lbl.leadingAnchor constraintEqualToAnchor:forLabel.leadingAnchor].active = YES;

        UIButton *dropdown = [self makeDropdownWithPlaceholder:[NSString stringWithFormat:@"- Select %@ -", [t componentsSeparatedByString:@" "].lastObject]];
        [content addSubview:dropdown];
        [NSLayoutConstraint activateConstraints:@[
            [dropdown.topAnchor constraintEqualToAnchor:lbl.bottomAnchor constant:8],
            [dropdown.leadingAnchor constraintEqualToAnchor:content.leadingAnchor constant:20],
            [dropdown.trailingAnchor constraintEqualToAnchor:content.trailingAnchor constant:-20],
            [dropdown.heightAnchor constraintEqualToConstant:44],
        ]];
        [dropdowns addObject:dropdown];
        lastView = dropdown;
    }

    // Comment box
    UILabel *commentLabel = [self makeLabelWithText:@"Comment" bold:YES size:15];
    [content addSubview:commentLabel];
    [commentLabel.topAnchor constraintEqualToAnchor:lastView.bottomAnchor constant:spacing].active = YES;
    [commentLabel.leadingAnchor constraintEqualToAnchor:forLabel.leadingAnchor].active = YES;

    UITextView *comment = [[UITextView alloc] init];
    comment.translatesAutoresizingMaskIntoConstraints = NO;
    comment.layer.borderWidth = 1.0;
    comment.layer.cornerRadius = 8;
    comment.layer.borderColor = [UIColor lightGrayColor].CGColor;
    comment.font = [UIFont systemFontOfSize:15];
    [content addSubview:comment];
    [NSLayoutConstraint activateConstraints:@[
        [comment.topAnchor constraintEqualToAnchor:commentLabel.bottomAnchor constant:8],
        [comment.leadingAnchor constraintEqualToAnchor:content.leadingAnchor constant:20],
        [comment.trailingAnchor constraintEqualToAnchor:content.trailingAnchor constant:-20],
        [comment.heightAnchor constraintEqualToConstant:100],
    ]];
    self.commentField = comment;
    lastView = comment;

    // Image upload section
    UILabel *uploadLabel = [self makeLabelWithText:@"*Image Upload" bold:YES size:15];
    [content addSubview:uploadLabel];
    [uploadLabel.topAnchor constraintEqualToAnchor:lastView.bottomAnchor constant:spacing].active = YES;
    [uploadLabel.leadingAnchor constraintEqualToAnchor:forLabel.leadingAnchor].active = YES;

    UIStackView *uploadRow = [[UIStackView alloc] init];
    uploadRow.axis = UILayoutConstraintAxisHorizontal;
    uploadRow.spacing = 12;
    uploadRow.distribution = UIStackViewDistributionFillEqually;
    uploadRow.translatesAutoresizingMaskIntoConstraints = NO;
    [content addSubview:uploadRow];
    [NSLayoutConstraint activateConstraints:@[
        [uploadRow.topAnchor constraintEqualToAnchor:uploadLabel.bottomAnchor constant:8],
        [uploadRow.leadingAnchor constraintEqualToAnchor:content.leadingAnchor constant:20],
        [uploadRow.trailingAnchor constraintEqualToAnchor:content.trailingAnchor constant:-20],
        [uploadRow.heightAnchor constraintEqualToConstant:90],
    ]];

    for (int i = 0; i < 3; i++) {
        UIButton *uploadBtn = [self makeUploadBox];
        uploadBtn.tag = 1000 + i; // unique ID for each button
        [uploadRow addArrangedSubview:uploadBtn];
    }
    lastView = uploadRow;

    // Submit button
    UIButton *submit = [UIButton buttonWithType:UIButtonTypeSystem];
    submit.translatesAutoresizingMaskIntoConstraints = NO;
    submit.backgroundColor = [UIColor colorWithRed:0/255.0 green:109/255.0 blue:141/255.0 alpha:1];
    [submit setTitle:@"Submit" forState:UIControlStateNormal];
    [submit setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    submit.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    submit.layer.cornerRadius = 8;
    [submit addTarget:self action:@selector(handleSubmit) forControlEvents:UIControlEventTouchUpInside];
    [content addSubview:submit];
    [NSLayoutConstraint activateConstraints:@[
        [submit.topAnchor constraintEqualToAnchor:lastView.bottomAnchor constant:spacing],
        [submit.leadingAnchor constraintEqualToAnchor:content.leadingAnchor constant:20],
        [submit.trailingAnchor constraintEqualToAnchor:content.trailingAnchor constant:-20],
        [submit.heightAnchor constraintEqualToConstant:48],
    ]];
    lastView = submit;
    [content.bottomAnchor constraintEqualToAnchor:lastView.bottomAnchor constant:spacing].active = YES;

}

- (UILabel *)makeLabelWithText:(NSString *)text bold:(BOOL)bold size:(CGFloat)size {
    UILabel *lbl = [[UILabel alloc] init];
    lbl.translatesAutoresizingMaskIntoConstraints = NO;
    lbl.text = text;
    lbl.font = bold ? [UIFont boldSystemFontOfSize:size] : [UIFont systemFontOfSize:size];
    lbl.textColor = [UIColor darkTextColor];
    return lbl;
}

- (UIView *)makeRoundedBox {
    UIView *box = [[UIView alloc] init];
    box.translatesAutoresizingMaskIntoConstraints = NO;
    box.layer.borderWidth = 1.0;
    box.layer.borderColor = [UIColor lightGrayColor].CGColor;
    box.layer.cornerRadius = 8;
    return box;
}

- (UIButton *)makeDropdownWithPlaceholder:(NSString *)placeholder {
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
    btn.translatesAutoresizingMaskIntoConstraints = NO;
    btn.layer.borderWidth = 1.0;
    btn.layer.cornerRadius = 8;
    btn.layer.borderColor = [UIColor lightGrayColor].CGColor;
    btn.backgroundColor = [UIColor colorWithWhite:0.97 alpha:1];
    
    // Title setup
    [btn setTitle:placeholder forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:15];
    
    // Align text on the left
    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    btn.contentEdgeInsets = UIEdgeInsetsMake(0, 12, 0, 0);
    
    // Add a dropdown chevron (SF Symbol)
    UIImage *chevron = [UIImage systemImageNamed:@"chevron.down"];
    UIImageView *arrow = [[UIImageView alloc] initWithImage:chevron];
    arrow.translatesAutoresizingMaskIntoConstraints = NO;
    arrow.tintColor = [UIColor grayColor];
    [btn addSubview:arrow];
    
    // Position arrow on right side
    [NSLayoutConstraint activateConstraints:@[
        [arrow.centerYAnchor constraintEqualToAnchor:btn.centerYAnchor],
        [arrow.trailingAnchor constraintEqualToAnchor:btn.trailingAnchor constant:-12],
        [arrow.widthAnchor constraintEqualToConstant:12],
        [arrow.heightAnchor constraintEqualToConstant:8]
    ]];
    
    // Bring title above arrow
    btn.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 20);
    
    // Add tap handler (for menu)
    [btn addTarget:self action:@selector(handleDropdownTap:) forControlEvents:UIControlEventTouchUpInside];
    
    return btn;
}

- (void)handleDropdownTap:(UIButton *)sender {
    NSString *title = sender.titleLabel.text ?: @"Select";
    
    UIAlertController *menu = [UIAlertController alertControllerWithTitle:title
                                                                  message:@"Pick an option"
                                                           preferredStyle:UIAlertControllerStyleActionSheet];
    
    NSArray *options = @[@"Option 1", @"Option 2", @"Option 3"];
    
    for (NSString *opt in options) {
        [menu addAction:[UIAlertAction actionWithTitle:opt
                                                 style:UIAlertActionStyleDefault
                                               handler:^(UIAlertAction * _Nonnull action) {
            [sender setTitle:opt forState:UIControlStateNormal];
            [sender setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }]];
    }
    
    [menu addAction:[UIAlertAction actionWithTitle:@"Cancel"
                                             style:UIAlertActionStyleCancel
                                           handler:nil]];
    
    [self presentViewController:menu animated:YES completion:nil];
}

- (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 {
    NSInteger index = sender.tag - 1000;
    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;
    picker.view.tag = index; // store which slot this is for
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate

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

    UIImage *image = info[UIImagePickerControllerOriginalImage];
    NSInteger index = picker.view.tag; // will be 0–2 after fix

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

    // Update UI
    UIButton *button = [self.view viewWithTag:1000 + 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 removeObjectAtIndex:index];
    }

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

- (void)handleReset {
    NSLog(@"🔄 Reset button tapped");
    self.locationField.text = @"";
    self.commentField.text = @"";

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Fields Cleared"
                                                                   message:@"All inputs have been reset."
                                                            preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"OK"
                                              style:UIAlertActionStyleDefault
                                            handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
    [self.uploadedImages removeAllObjects];
}


#pragma mark - Actions

- (void)dismissSelf {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)handleSubmit {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Submitted"
                                                                   message:@"Issue has been added (mock)."
                                                            preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}

@end
