#import "ImagePickerManager.h"
#import <React/RCTConvert.h>
#import <React/RCTUtils.h>
#import <AVFoundation/AVFoundation.h>
#import <CoreLocation/CoreLocation.h>
#import <ImageIO/ImageIO.h>
#import <Photos/Photos.h>
#import <PhotosUI/PhotosUI.h>
#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>

// NOTE: This module deliberately does not use AssetsLibrary (ALAssetsLibrary). It was
// deprecated in iOS 9 and, as of iOS 27.2, crashes on first use
// (-[PLManagedObjectContext setIsBackingALAssetsLibrary:]: unrecognized selector).
//
// - Camera capture uses UIImagePickerController (still the supported system camera UI).
// - Library selection uses PHPickerViewController, which needs no photo library permission.
//   Location is read from the picked file's EXIF first, then from the PHAsset when the app
//   already has (full or limited) photo library access.

@interface ImagePickerManager () <PHPickerViewControllerDelegate>

@property (nonatomic, strong) UIImagePickerController *picker;
@property (nonatomic, strong) RCTResponseSenderBlock callback;
@property (nonatomic, strong) NSDictionary *options;
@property (nonatomic, strong) NSArray *customButtons;

@end

@implementation ImagePickerManager

RCT_EXPORT_MODULE();

+ (BOOL)requiresMainQueueSetup
{
    return NO;
}

RCT_EXPORT_METHOD(launchCamera:(NSDictionary *)options callback:(RCTResponseSenderBlock)callback)
{
    self.callback = callback;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self launchImagePicker:RNImagePickerTargetCamera options:options];
    });
}

RCT_EXPORT_METHOD(launchImageLibrary:(NSDictionary *)options callback:(RCTResponseSenderBlock)callback)
{
    self.callback = callback;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self launchImagePicker:RNImagePickerTargetLibrarySingleImage options:options];
    });
}

RCT_EXPORT_METHOD(showImagePicker:(NSDictionary *)options callback:(RCTResponseSenderBlock)callback)
{
    self.callback = callback; // Save the callback so we can use it from the delegate methods
    self.options = options;

    dispatch_async(dispatch_get_main_queue(), ^{

        NSString *title = [self stringOption:@"title"];
        if (title.length == 0) {
            title = nil; // A more visually appealing UIAlertControl is displayed with a nil title rather than title = @""
        }
        NSString *cancelTitle = [self stringOption:@"cancelButtonTitle"];
        NSString *takePhotoButtonTitle = [self stringOption:@"takePhotoButtonTitle"];
        NSString *chooseFromLibraryButtonTitle = [self stringOption:@"chooseFromLibraryButtonTitle"];

        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        alertController.view.tintColor = [RCTConvert UIColor:options[@"tintColor"]];

        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelTitle style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {
            [self sendResponse:@{@"didCancel": @YES}];
        }];
        [alertController addAction:cancelAction];

        if (takePhotoButtonTitle.length > 0) {
            UIAlertAction *takePhotoAction = [UIAlertAction actionWithTitle:takePhotoButtonTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
                [self actionHandler:action];
            }];
            [alertController addAction:takePhotoAction];
        }
        if (chooseFromLibraryButtonTitle.length > 0) {
            UIAlertAction *chooseFromLibraryAction = [UIAlertAction actionWithTitle:chooseFromLibraryButtonTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
                [self actionHandler:action];
            }];
            [alertController addAction:chooseFromLibraryAction];
        }

        // Add custom buttons to action sheet
        if ([[self.options objectForKey:@"customButtons"] isKindOfClass:[NSArray class]]) {
            self.customButtons = [self.options objectForKey:@"customButtons"];
            for (NSDictionary *button in self.customButtons) {
                NSString *buttonTitle = [button valueForKey:@"title"];
                UIAlertAction *customAction = [UIAlertAction actionWithTitle:buttonTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
                    [self actionHandler:action];
                }];
                [alertController addAction:customAction];
            }
        }

        UIViewController *root = RCTPresentedViewController();

        /* On iPad, UIAlertController presents a popover view rather than an action sheet like on iPhone. We must provide the location
        of the location to show the popover in this case. For simplicity, we'll just display it on the bottom center of the screen
        to mimic an action sheet */
        alertController.popoverPresentationController.sourceView = root.view;
        alertController.popoverPresentationController.sourceRect = CGRectMake(root.view.bounds.size.width / 2.0, root.view.bounds.size.height, 1.0, 1.0);

        if (UIDevice.currentDevice.userInterfaceIdiom == UIUserInterfaceIdiomPad) {
            alertController.popoverPresentationController.permittedArrowDirections = 0;
            for (id subview in alertController.view.subviews) {
                if ([subview isMemberOfClass:[UIView class]]) {
                    ((UIView *)subview).backgroundColor = [UIColor whiteColor];
                }
            }
        }

        [root presentViewController:alertController animated:YES completion:nil];
    });
}

- (void)actionHandler:(UIAlertAction *)action
{
    // If button title is one of the keys in the customButtons dictionary return the value as a callback
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"title==%@", action.title];
    NSArray *results = [self.customButtons filteredArrayUsingPredicate:predicate];
    if (results.count > 0) {
        NSString *customButtonStr = [[results objectAtIndex:0] objectForKey:@"name"];
        if (customButtonStr) {
            [self sendResponse:@{@"customButton": customButtonStr}];
            return;
        }
    }

    if ([action.title isEqualToString:[self stringOption:@"takePhotoButtonTitle"]]) { // Take photo
        [self launchImagePicker:RNImagePickerTargetCamera];
    }
    else if ([action.title isEqualToString:[self stringOption:@"chooseFromLibraryButtonTitle"]]) { // Choose from library
        [self launchImagePicker:RNImagePickerTargetLibrarySingleImage];
    }
}

#pragma mark - Launching

- (void)launchImagePicker:(RNImagePickerTarget)target options:(NSDictionary *)options
{
    self.options = options;
    [self launchImagePicker:target];
}

- (void)launchImagePicker:(RNImagePickerTarget)target
{
    if (target == RNImagePickerTargetCamera) {
        [self launchCameraPicker];
    } else {
        [self launchLibraryPicker];
    }
}

- (void)launchCameraPicker
{
#if TARGET_OS_SIMULATOR
    [self sendResponse:@{@"error": @"Camera not available on simulator"}];
#else
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        [self sendResponse:@{@"error": @"Camera not available"}];
        return;
    }

    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([[self stringOption:@"cameraType"] isEqualToString:@"front"]) {
        picker.cameraDevice = UIImagePickerControllerCameraDeviceFront;
    } else {
        picker.cameraDevice = UIImagePickerControllerCameraDeviceRear;
    }

    NSString *mediaType = [self stringOption:@"mediaType"];
    if ([mediaType isEqualToString:@"video"] || [mediaType isEqualToString:@"mixed"]) {
        NSString *videoQuality = [self stringOption:@"videoQuality"];
        if ([videoQuality isEqualToString:@"high"]) {
            picker.videoQuality = UIImagePickerControllerQualityTypeHigh;
        } else if ([videoQuality isEqualToString:@"low"]) {
            picker.videoQuality = UIImagePickerControllerQualityTypeLow;
        } else {
            picker.videoQuality = UIImagePickerControllerQualityTypeMedium;
        }

        id durationLimit = [self.options objectForKey:@"durationLimit"];
        if ([durationLimit isKindOfClass:[NSNumber class]]) {
            picker.videoMaximumDuration = [durationLimit doubleValue];
        }
    }
    if ([mediaType isEqualToString:@"video"]) {
        picker.mediaTypes = @[UTTypeMovie.identifier];
    } else if ([mediaType isEqualToString:@"mixed"]) {
        picker.mediaTypes = @[UTTypeMovie.identifier, UTTypeImage.identifier];
    } else {
        picker.mediaTypes = @[UTTypeImage.identifier];
    }

    picker.allowsEditing = [[self.options objectForKey:@"allowsEditing"] boolValue];
    picker.modalPresentationStyle = UIModalPresentationFullScreen;
    picker.delegate = self;
    self.picker = picker;

    [self checkCameraPermissions:^(BOOL granted) {
        if (!granted) {
            [self sendResponse:@{@"error": @"Camera permissions not granted"}];
            return;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [RCTPresentedViewController() presentViewController:picker animated:YES completion:nil];
        });
    }];
#endif
}

- (void)launchLibraryPicker
{
    // Passing the shared library gives us assetIdentifiers on results, which lets us fall back to
    // PHAsset metadata (location, creation date, original filename) when the app has library access.
    // PHPicker itself needs no permission, so we never block selection on authorization.
    PHPickerConfiguration *configuration = [[PHPickerConfiguration alloc] initWithPhotoLibrary:[PHPhotoLibrary sharedPhotoLibrary]];
    configuration.selectionLimit = 1;
    // Hand back the asset as stored (no transcoding) so EXIF/GPS metadata and GIF frames are preserved.
    configuration.preferredAssetRepresentationMode = PHPickerConfigurationAssetRepresentationModeCurrent;

    NSString *mediaType = [self stringOption:@"mediaType"];
    if ([mediaType isEqualToString:@"video"]) {
        configuration.filter = [PHPickerFilter videosFilter];
    } else if ([mediaType isEqualToString:@"mixed"]) {
        configuration.filter = [PHPickerFilter anyFilterMatchingSubfilters:@[[PHPickerFilter imagesFilter], [PHPickerFilter videosFilter]]];
    } else {
        configuration.filter = [PHPickerFilter imagesFilter];
    }

    PHPickerViewController *pickerViewController = [[PHPickerViewController alloc] initWithConfiguration:configuration];
    pickerViewController.delegate = self;

    dispatch_async(dispatch_get_main_queue(), ^{
        [RCTPresentedViewController() presentViewController:pickerViewController animated:YES completion:nil];
    });
}

#pragma mark - PHPickerViewControllerDelegate (library)

- (void)picker:(PHPickerViewController *)picker didFinishPicking:(NSArray<PHPickerResult *> *)results
{
    NSDictionary *options = self.options;
    [picker dismissViewControllerAnimated:YES completion:^{
        PHPickerResult *result = results.firstObject;
        if (!result) {
            [self sendResponse:@{@"didCancel": @YES}];
            return;
        }
        [self handlePickerResult:result options:options];
    }];
}

- (void)handlePickerResult:(PHPickerResult *)result options:(NSDictionary *)options
{
    NSItemProvider *provider = result.itemProvider;
    NSString *mediaType = [ImagePickerManager stringValue:options[@"mediaType"]];

    BOOL isImage = [provider hasItemConformingToTypeIdentifier:UTTypeImage.identifier];
    BOOL isMovie = [provider hasItemConformingToTypeIdentifier:UTTypeMovie.identifier];
    BOOL treatAsVideo = isMovie && (!isImage || [mediaType isEqualToString:@"video"]);

    if (!isImage && !isMovie) {
        [self sendResponse:@{@"error": @"Unsupported media type"}];
        return;
    }

    if (treatAsVideo) {
        [provider loadFileRepresentationForTypeIdentifier:UTTypeMovie.identifier completionHandler:^(NSURL * _Nullable url, NSError * _Nullable error) {
            // The file at `url` is deleted once this handler returns, so copy it out synchronously.
            [self handleLibraryVideoAtURL:url error:error assetIdentifier:result.assetIdentifier suggestedName:provider.suggestedName options:options];
        }];
        return;
    }

    BOOL isGIF = [provider hasItemConformingToTypeIdentifier:UTTypeGIF.identifier];
    NSString *typeIdentifier = isGIF ? UTTypeGIF.identifier : UTTypeImage.identifier;
    [provider loadFileRepresentationForTypeIdentifier:typeIdentifier completionHandler:^(NSURL * _Nullable url, NSError * _Nullable error) {
        NSData *data = url ? [NSData dataWithContentsOfURL:url] : nil;
        if (!data) {
            [self sendResponse:@{@"error": error.localizedDescription ?: @"Could not read photo"}];
            return;
        }
        NSString *fileName = [self fileNameFromSuggestedName:provider.suggestedName extension:url.pathExtension];
        [self handleLibraryImageData:data isGIF:isGIF assetIdentifier:result.assetIdentifier fileName:fileName options:options];
    }];
}

- (void)handleLibraryImageData:(NSData *)data
                         isGIF:(BOOL)isGIF
               assetIdentifier:(NSString *)assetIdentifier
                      fileName:(NSString *)fileName
                       options:(NSDictionary *)options
{
    UIImage *image = [UIImage imageWithData:data];
    if (!image) {
        [self sendResponse:@{@"error": @"Could not read photo"}];
        return;
    }

    NSDictionary *properties = [ImagePickerManager imagePropertiesFromData:data];
    PHAsset *asset = [ImagePickerManager fetchAssetWithIdentifier:assetIdentifier];

    NSString *error = nil;
    NSMutableDictionary *response;
    if (isGIF) {
        // GIFs break when resized, so pass the original bytes through untouched.
        response = [self writeGIFData:data image:image options:options error:&error];
    } else {
        response = [self writeImage:image options:options error:&error];
    }
    if (!response) {
        [self sendResponse:@{@"error": error ?: @"Could not save photo"}];
        return;
    }

    // Location: prefer the file's own EXIF GPS, then fall back to the PHAsset.
    CLLocation *location = [ImagePickerManager locationFromImageProperties:properties] ?: asset.location;
    [ImagePickerManager applyLocation:location toResponse:response];

    NSDate *creationDate = [ImagePickerManager dateFromImageProperties:properties] ?: asset.creationDate;
    if (creationDate) {
        response[@"timestamp"] = [[ImagePickerManager ISO8601DateFormatter] stringFromDate:creationDate];
    }

    // fileName being present signals "picked from the library" (vs. a fresh camera capture) to callers.
    NSString *originalFilename = [self originalFilenameForAsset:asset assetType:PHAssetResourceTypePhoto] ?: fileName;
    response[@"fileName"] = originalFilename ?: [NSNull null];
    if (asset) {
        response[@"origURL"] = [@"ph://" stringByAppendingString:asset.localIdentifier];
    } else if (assetIdentifier) {
        response[@"origURL"] = [@"ph://" stringByAppendingString:assetIdentifier];
    }

    [self sendResponse:response];
}

- (void)handleLibraryVideoAtURL:(NSURL *)url
                          error:(NSError *)loadError
                assetIdentifier:(NSString *)assetIdentifier
                  suggestedName:(NSString *)suggestedName
                        options:(NSDictionary *)options
{
    if (!url) {
        [self sendResponse:@{@"error": loadError.localizedDescription ?: @"Could not read video"}];
        return;
    }

    NSString *error = nil;
    NSString *extension = url.pathExtension.length > 0 ? url.pathExtension : @"mov";
    NSString *path = [self destinationPathWithExtension:extension options:options error:&error];
    if (!path) {
        [self sendResponse:@{@"error": error}];
        return;
    }

    NSURL *destinationURL = [NSURL fileURLWithPath:path];
    NSError *copyError = nil;
    [[NSFileManager defaultManager] removeItemAtURL:destinationURL error:nil];
    if (![[NSFileManager defaultManager] copyItemAtURL:url toURL:destinationURL error:&copyError]) {
        [self sendResponse:@{@"error": copyError.localizedDescription ?: @"Could not save video"}];
        return;
    }
    [self applySkipBackupIfNeeded:path options:options];

    NSMutableDictionary *response = [NSMutableDictionary dictionary];
    response[@"uri"] = destinationURL.absoluteString;

    PHAsset *asset = [ImagePickerManager fetchAssetWithIdentifier:assetIdentifier];
    [ImagePickerManager applyLocation:asset.location toResponse:response];
    if (asset.creationDate) {
        response[@"timestamp"] = [[ImagePickerManager ISO8601DateFormatter] stringFromDate:asset.creationDate];
    }
    NSString *originalFilename = [self originalFilenameForAsset:asset assetType:PHAssetResourceTypeVideo]
        ?: [self fileNameFromSuggestedName:suggestedName extension:url.pathExtension];
    response[@"fileName"] = originalFilename ?: [NSNull null];
    if (assetIdentifier) {
        response[@"origURL"] = [@"ph://" stringByAppendingString:assetIdentifier];
    }

    [self sendResponse:response];
}

#pragma mark - UIImagePickerControllerDelegate (camera)

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey, id> *)info
{
    NSDictionary *options = self.options;
    [picker dismissViewControllerAnimated:YES completion:^{
        // Encoding a full-resolution capture is slow; keep it off the main thread.
        dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
            NSString *mediaType = info[UIImagePickerControllerMediaType];
            if ([mediaType isEqualToString:UTTypeMovie.identifier]) {
                [self handleCapturedVideoWithInfo:info options:options];
            } else {
                [self handleCapturedImageWithInfo:info options:options];
            }
        });
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:^{
        [self sendResponse:@{@"didCancel": @YES}];
    }];
}

- (void)handleCapturedImageWithInfo:(NSDictionary<UIImagePickerControllerInfoKey, id> *)info options:(NSDictionary *)options
{
    UIImage *originalImage = info[UIImagePickerControllerOriginalImage];
    UIImage *image = originalImage;
    if ([options[@"allowsEditing"] boolValue] && info[UIImagePickerControllerEditedImage]) {
        image = info[UIImagePickerControllerEditedImage];
    }
    if (!image) {
        [self sendResponse:@{@"error": @"Could not read photo"}];
        return;
    }

    NSString *error = nil;
    NSMutableDictionary *response = [self writeImage:image options:options error:&error];
    if (!response) {
        [self sendResponse:@{@"error": error ?: @"Could not save photo"}];
        return;
    }

    // The camera's metadata normally has no GPS (UIImagePickerController doesn't geotag), in which
    // case callers fall back to the device's current location. fileName is intentionally left unset
    // for captures so callers can tell them apart from library picks.
    NSDictionary *metadata = info[UIImagePickerControllerMediaMetadata];
    [ImagePickerManager applyLocation:[ImagePickerManager locationFromImageProperties:metadata] toResponse:response];
    NSDate *captureDate = [ImagePickerManager dateFromImageProperties:metadata];
    if (captureDate) {
        response[@"timestamp"] = [[ImagePickerManager ISO8601DateFormatter] stringFromDate:captureDate];
    }

    NSDictionary *storageOptions = [ImagePickerManager storageOptionsFrom:options];
    if (![storageOptions[@"cameraRoll"] boolValue]) {
        [self sendResponse:response];
        return;
    }

    NSData *photoData = [ImagePickerManager JPEGDataForImage:originalImage metadata:metadata];
    BOOL waitUntilSaved = [storageOptions[@"waitUntilSaved"] boolValue];
    [self saveToCameraRollPhotoData:photoData videoURL:nil completion:^(PHAsset *asset, NSError *saveError) {
        if (saveError) {
            NSLog(@"ImagePickerManager: error saving photo to camera roll: %@", saveError);
        }
        if (waitUntilSaved) {
            [self applySavedAsset:asset assetType:PHAssetResourceTypePhoto toResponse:response];
            [self sendResponse:response];
        }
    }];
    if (!waitUntilSaved) {
        [self sendResponse:response];
    }
}

- (void)handleCapturedVideoWithInfo:(NSDictionary<UIImagePickerControllerInfoKey, id> *)info options:(NSDictionary *)options
{
    NSURL *videoURL = info[UIImagePickerControllerMediaURL];
    if (!videoURL) {
        [self sendResponse:@{@"error": @"Could not read video"}];
        return;
    }

    NSString *error = nil;
    NSString *extension = videoURL.pathExtension.length > 0 ? videoURL.pathExtension : @"mov";
    NSString *path = [self destinationPathWithExtension:extension options:options error:&error];
    if (!path) {
        [self sendResponse:@{@"error": error}];
        return;
    }
    NSURL *destinationURL = [NSURL fileURLWithPath:path];

    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager removeItemAtURL:destinationURL error:nil];
    NSError *moveError = nil;
    BOOL moved;
    if ([fileManager isWritableFileAtPath:videoURL.path]) {
        moved = [fileManager moveItemAtURL:videoURL toURL:destinationURL error:&moveError];
    } else {
        moved = [fileManager copyItemAtURL:videoURL toURL:destinationURL error:&moveError];
    }
    if (!moved) {
        [self sendResponse:@{@"error": moveError.localizedDescription ?: @"Could not save video"}];
        return;
    }
    [self applySkipBackupIfNeeded:path options:options];

    NSMutableDictionary *response = [NSMutableDictionary dictionary];
    response[@"uri"] = destinationURL.absoluteString;

    NSDictionary *storageOptions = [ImagePickerManager storageOptionsFrom:options];
    if (![storageOptions[@"cameraRoll"] boolValue]) {
        [self sendResponse:response];
        return;
    }

    BOOL waitUntilSaved = [storageOptions[@"waitUntilSaved"] boolValue];
    [self saveToCameraRollPhotoData:nil videoURL:destinationURL completion:^(PHAsset *asset, NSError *saveError) {
        if (saveError) {
            NSLog(@"ImagePickerManager: error saving video to camera roll: %@", saveError);
        }
        if (waitUntilSaved) {
            [self applySavedAsset:asset assetType:PHAssetResourceTypeVideo toResponse:response];
            [self sendResponse:response];
        }
    }];
    if (!waitUntilSaved) {
        [self sendResponse:response];
    }
}

#pragma mark - Camera roll

- (void)saveToCameraRollPhotoData:(NSData *)photoData
                         videoURL:(NSURL *)videoURL
                       completion:(void (^)(PHAsset *asset, NSError *error))completion
{
    __block NSString *localIdentifier = nil;
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        PHAssetCreationRequest *request = [PHAssetCreationRequest creationRequestForAsset];
        if (photoData) {
            [request addResourceWithType:PHAssetResourceTypePhoto data:photoData options:nil];
        } else {
            [request addResourceWithType:PHAssetResourceTypeVideo fileURL:videoURL options:nil];
        }
        localIdentifier = request.placeholderForCreatedAsset.localIdentifier;
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        // Fetching back requires read access; with add-only access this is simply nil.
        PHAsset *asset = success ? [ImagePickerManager fetchAssetWithIdentifier:localIdentifier] : nil;
        completion(asset, error);
    }];
}

- (void)applySavedAsset:(PHAsset *)asset assetType:(PHAssetResourceType)type toResponse:(NSMutableDictionary *)response
{
    if (!asset) {
        return;
    }
    NSString *originalFilename = [self originalFilenameForAsset:asset assetType:type];
    response[@"fileName"] = originalFilename ?: [NSNull null];
    if (asset.creationDate) {
        response[@"timestamp"] = [[ImagePickerManager ISO8601DateFormatter] stringFromDate:asset.creationDate];
    }
    response[@"origURL"] = [@"ph://" stringByAppendingString:asset.localIdentifier];
}

#pragma mark - Writing images

- (NSMutableDictionary *)writeImage:(UIImage *)image options:(NSDictionary *)options error:(NSString **)error
{
    BOOL png = [[ImagePickerManager stringValue:options[@"imageFileType"]] isEqualToString:@"png"];
    NSString *path = [self destinationPathWithExtension:(png ? @"png" : @"jpg") options:options error:error];
    if (!path) {
        return nil;
    }

    UIImage *editedImage = [self fixOrientation:image];  // Rotate the image for upload to web

    // If needed, downscale image
    CGFloat maxWidth = editedImage.size.width;
    CGFloat maxHeight = editedImage.size.height;
    if ([options[@"maxWidth"] isKindOfClass:[NSNumber class]]) {
        maxWidth = [options[@"maxWidth"] floatValue];
    }
    if ([options[@"maxHeight"] isKindOfClass:[NSNumber class]]) {
        maxHeight = [options[@"maxHeight"] floatValue];
    }
    editedImage = [self downscaleImageIfNecessary:editedImage maxWidth:maxWidth maxHeight:maxHeight];

    NSData *data;
    NSString *mimeType;
    if (png) {
        data = UIImagePNGRepresentation(editedImage);
        mimeType = @"image/png";
    } else {
        CGFloat quality = [options[@"quality"] isKindOfClass:[NSNumber class]] ? [options[@"quality"] floatValue] : 1.0;
        data = UIImageJPEGRepresentation(editedImage, quality);
        mimeType = @"image/jpeg";
    }
    if (!data || ![data writeToFile:path atomically:YES]) {
        if (error) { *error = @"Could not save photo"; }
        return nil;
    }
    [self applySkipBackupIfNeeded:path options:options];

    NSMutableDictionary *response = [NSMutableDictionary dictionary];
    response[@"type"] = mimeType;
    if (![options[@"noData"] boolValue]) {
        response[@"data"] = [data base64EncodedStringWithOptions:0];
    }
    response[@"isVertical"] = @(editedImage.size.width < editedImage.size.height);
    response[@"width"] = @(editedImage.size.width);
    response[@"height"] = @(editedImage.size.height);
    [self applyFileURL:[NSURL fileURLWithPath:path] toResponse:response];
    return response;
}

- (NSMutableDictionary *)writeGIFData:(NSData *)data image:(UIImage *)image options:(NSDictionary *)options error:(NSString **)error
{
    NSString *path = [self destinationPathWithExtension:@"gif" options:options error:error];
    if (!path) {
        return nil;
    }
    if (![data writeToFile:path atomically:YES]) {
        if (error) { *error = @"Could not save photo"; }
        return nil;
    }
    [self applySkipBackupIfNeeded:path options:options];

    NSMutableDictionary *response = [NSMutableDictionary dictionary];
    response[@"type"] = @"image/gif";
    if (![options[@"noData"] boolValue]) {
        response[@"data"] = [data base64EncodedStringWithOptions:0];
    }
    response[@"isVertical"] = @(image.size.width < image.size.height);
    response[@"width"] = @(image.size.width);
    response[@"height"] = @(image.size.height);
    [self applyFileURL:[NSURL fileURLWithPath:path] toResponse:response];
    return response;
}

- (void)applyFileURL:(NSURL *)fileURL toResponse:(NSMutableDictionary *)response
{
    response[@"uri"] = fileURL.absoluteString;
    NSNumber *fileSizeValue = nil;
    [fileURL getResourceValue:&fileSizeValue forKey:NSURLFileSizeKey error:nil];
    if (fileSizeValue) {
        response[@"fileSize"] = fileSizeValue;
    }
}

// Temporary directory by default; the (persisted) documents directory when storageOptions are given.
- (NSString *)destinationPathWithExtension:(NSString *)extension options:(NSDictionary *)options error:(NSString **)error
{
    NSString *fileName = [[[NSUUID UUID] UUIDString] stringByAppendingPathExtension:extension];
    NSString *directory = [NSTemporaryDirectory() stringByStandardizingPath];

    NSDictionary *storageOptions = [ImagePickerManager storageOptionsFrom:options];
    if (storageOptions) {
        directory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
        NSString *subpath = [ImagePickerManager stringValue:storageOptions[@"path"]];
        if (subpath.length > 0) {
            directory = [directory stringByAppendingPathComponent:subpath];
            NSError *createError = nil;
            if (![[NSFileManager defaultManager] createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:&createError]) {
                NSLog(@"Error creating documents subdirectory: %@", createError);
                if (error) { *error = createError.localizedDescription ?: @"Could not create directory"; }
                return nil;
            }
        }
    }
    return [directory stringByAppendingPathComponent:fileName];
}

- (void)applySkipBackupIfNeeded:(NSString *)path options:(NSDictionary *)options
{
    if ([[ImagePickerManager storageOptionsFrom:options][@"skipBackup"] boolValue]) {
        [self addSkipBackupAttributeToItemAtPath:path]; // Don't back up the file to iCloud
    }
}

#pragma mark - Responses

// RCTResponseSenderBlock may only be invoked once; drop the callback as soon as it's used.
- (void)sendResponse:(NSDictionary *)response
{
    dispatch_async(dispatch_get_main_queue(), ^{
        RCTResponseSenderBlock callback = self.callback;
        self.callback = nil;
        if (callback) {
            callback(@[response]);
        }
    });
}

- (NSString *)stringOption:(NSString *)key
{
    return [ImagePickerManager stringValue:self.options[key]];
}

- (NSString *)fileNameFromSuggestedName:(NSString *)suggestedName extension:(NSString *)extension
{
    if (suggestedName.length == 0) {
        return nil;
    }
    if (extension.length == 0 || suggestedName.pathExtension.length > 0) {
        return suggestedName;
    }
    return [suggestedName stringByAppendingPathExtension:extension];
}

- (NSString * _Nullable)originalFilenameForAsset:(PHAsset * _Nullable)asset assetType:(PHAssetResourceType)type {
    if (!asset) { return nil; }

    PHAssetResource *originalResource;
    // Get the underlying resources for the PHAsset (PhotoKit)
    NSArray<PHAssetResource *> *pickedAssetResources = [PHAssetResource assetResourcesForAsset:asset];

    // Find the original resource (underlying image) for the asset, which has the desired filename
    for (PHAssetResource *resource in pickedAssetResources) {
        if (resource.type == type) {
            originalResource = resource;
        }
    }

    return originalResource.originalFilename;
}

#pragma mark - Permissions

- (void)checkCameraPermissions:(void(^)(BOOL granted))callback
{
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (status == AVAuthorizationStatusAuthorized) {
        callback(YES);
    } else if (status == AVAuthorizationStatusNotDetermined) {
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            callback(granted);
        }];
    } else {
        callback(NO);
    }
}

#pragma mark - Image helpers

- (UIImage*)downscaleImageIfNecessary:(UIImage*)image maxWidth:(CGFloat)maxWidth maxHeight:(CGFloat)maxHeight
{
    // Nothing to do here
    if (image.size.width <= maxWidth && image.size.height <= maxHeight) {
        return image;
    }

    CGSize scaledSize = CGSizeMake(image.size.width, image.size.height);
    if (maxWidth < scaledSize.width) {
        scaledSize = CGSizeMake(maxWidth, (maxWidth / scaledSize.width) * scaledSize.height);
    }
    if (maxHeight < scaledSize.height) {
        scaledSize = CGSizeMake((maxHeight / scaledSize.height) * scaledSize.width, maxHeight);
    }

    // If the pixels are floats, it causes a white line
    scaledSize.width = (int)scaledSize.width;
    scaledSize.height = (int)scaledSize.height;

    // fixOrientation produces a scale-1 image, so points == pixels; render at scale 1 to match.
    UIGraphicsImageRendererFormat *format = [UIGraphicsImageRendererFormat preferredFormat];
    format.scale = 1;
    UIGraphicsImageRenderer *renderer = [[UIGraphicsImageRenderer alloc] initWithSize:scaledSize format:format];
    UIImage *newImage = [renderer imageWithActions:^(UIGraphicsImageRendererContext * _Nonnull context) {
        [image drawInRect:CGRectMake(0, 0, scaledSize.width, scaledSize.height)];
    }];
    if (newImage == nil) {
        NSLog(@"could not scale image");
        return image;
    }
    return newImage;
}

- (UIImage *)fixOrientation:(UIImage *)srcImg {
    if (srcImg.imageOrientation == UIImageOrientationUp) {
        return srcImg;
    }

    CGAffineTransform transform = CGAffineTransformIdentity;
    switch (srcImg.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, srcImg.size.width, srcImg.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;

        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, srcImg.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;

        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, srcImg.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        case UIImageOrientationUp:
        case UIImageOrientationUpMirrored:
            break;
    }

    switch (srcImg.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, srcImg.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;

        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, srcImg.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        case UIImageOrientationUp:
        case UIImageOrientationDown:
        case UIImageOrientationLeft:
        case UIImageOrientationRight:
            break;
    }

    CGContextRef ctx = CGBitmapContextCreate(NULL, srcImg.size.width, srcImg.size.height, CGImageGetBitsPerComponent(srcImg.CGImage), 0, CGImageGetColorSpace(srcImg.CGImage), CGImageGetBitmapInfo(srcImg.CGImage));
    if (!ctx) {
        return srcImg;
    }
    CGContextConcatCTM(ctx, transform);
    switch (srcImg.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            CGContextDrawImage(ctx, CGRectMake(0,0,srcImg.size.height,srcImg.size.width), srcImg.CGImage);
            break;

        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,srcImg.size.width,srcImg.size.height), srcImg.CGImage);
            break;
    }

    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

- (BOOL)addSkipBackupAttributeToItemAtPath:(NSString *) filePathString
{
    NSURL* URL= [NSURL fileURLWithPath: filePathString];
    if ([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]) {
        NSError *error = nil;
        BOOL success = [URL setResourceValue: [NSNumber numberWithBool: YES]
                                      forKey: NSURLIsExcludedFromBackupKey error: &error];

        if(!success){
            NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error);
        }
        return success;
    }
    else {
        NSLog(@"Error setting skip backup attribute: file not found");
        return NO;
    }
}

#pragma mark - Class Methods

+ (NSString *)stringValue:(id)value
{
    return [value isKindOfClass:[NSString class]] ? value : nil;
}

+ (NSDictionary *)storageOptionsFrom:(NSDictionary *)options
{
    id storageOptions = options[@"storageOptions"];
    return [storageOptions isKindOfClass:[NSDictionary class]] ? storageOptions : nil;
}

// Only touches PhotoKit when the app already has read access, so this never triggers a permission prompt.
+ (PHAsset *)fetchAssetWithIdentifier:(NSString *)identifier
{
    if (identifier.length == 0) {
        return nil;
    }
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatusForAccessLevel:PHAccessLevelReadWrite];
    if (status != PHAuthorizationStatusAuthorized && status != PHAuthorizationStatusLimited) {
        return nil;
    }
    return [PHAsset fetchAssetsWithLocalIdentifiers:@[identifier] options:nil].firstObject;
}

+ (NSDictionary *)imagePropertiesFromData:(NSData *)data
{
    CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
    if (!source) {
        return nil;
    }
    NSDictionary *properties = (__bridge_transfer NSDictionary *)CGImageSourceCopyPropertiesAtIndex(source, 0, NULL);
    CFRelease(source);
    return properties;
}

+ (CLLocation *)locationFromImageProperties:(NSDictionary *)properties
{
    NSDictionary *gps = properties[(NSString *)kCGImagePropertyGPSDictionary];
    if (![gps isKindOfClass:[NSDictionary class]]) {
        return nil;
    }
    NSNumber *latitude = gps[(NSString *)kCGImagePropertyGPSLatitude];
    NSNumber *longitude = gps[(NSString *)kCGImagePropertyGPSLongitude];
    if (![latitude isKindOfClass:[NSNumber class]] || ![longitude isKindOfClass:[NSNumber class]]) {
        return nil;
    }
    double lat = latitude.doubleValue;
    double lon = longitude.doubleValue;
    if ([gps[(NSString *)kCGImagePropertyGPSLatitudeRef] isEqual:@"S"]) { lat = -lat; }
    if ([gps[(NSString *)kCGImagePropertyGPSLongitudeRef] isEqual:@"W"]) { lon = -lon; }
    if (lat == 0 && lon == 0) {
        return nil;
    }
    return [[CLLocation alloc] initWithLatitude:lat longitude:lon];
}

+ (void)applyLocation:(CLLocation *)location toResponse:(NSMutableDictionary *)response
{
    if (!location) {
        return;
    }
    response[@"latitude"] = @(location.coordinate.latitude);
    response[@"longitude"] = @(location.coordinate.longitude);
}

+ (NSDate *)dateFromImageProperties:(NSDictionary *)properties
{
    NSDictionary *exif = properties[(NSString *)kCGImagePropertyExifDictionary];
    if (![exif isKindOfClass:[NSDictionary class]]) {
        return nil;
    }
    NSString *dateString = [self stringValue:exif[(NSString *)kCGImagePropertyExifDateTimeOriginal]];
    if (dateString.length == 0) {
        return nil;
    }
    NSString *offset = [self stringValue:exif[(NSString *)kCGImagePropertyExifOffsetTimeOriginal]];

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
    if (offset.length > 0) {
        formatter.dateFormat = @"yyyy:MM:dd HH:mm:ssxxx";
        return [formatter dateFromString:[dateString stringByAppendingString:offset]];
    }
    // No offset recorded: EXIF times are local to where the photo was taken; assume the device's zone.
    formatter.dateFormat = @"yyyy:MM:dd HH:mm:ss";
    formatter.timeZone = [NSTimeZone localTimeZone];
    return [formatter dateFromString:dateString];
}

+ (NSData *)JPEGDataForImage:(UIImage *)image metadata:(NSDictionary *)metadata
{
    if (!image.CGImage) {
        return UIImageJPEGRepresentation(image, 0.9);
    }
    NSMutableData *data = [NSMutableData data];
    CGImageDestinationRef destination = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)data, (__bridge CFStringRef)UTTypeJPEG.identifier, 1, NULL);
    if (!destination) {
        return UIImageJPEGRepresentation(image, 0.9);
    }
    NSMutableDictionary *properties = [metadata mutableCopy] ?: [NSMutableDictionary dictionary];
    properties[(NSString *)kCGImageDestinationLossyCompressionQuality] = @0.9;
    CGImageDestinationAddImage(destination, image.CGImage, (__bridge CFDictionaryRef)properties);
    BOOL ok = CGImageDestinationFinalize(destination);
    CFRelease(destination);
    return ok ? data : UIImageJPEGRepresentation(image, 0.9);
}

+ (NSDateFormatter * _Nonnull)ISO8601DateFormatter {
    static NSDateFormatter *ISO8601DateFormatter;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        ISO8601DateFormatter = [[NSDateFormatter alloc] init];
        NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
        ISO8601DateFormatter.locale = enUSPOSIXLocale;
        ISO8601DateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
        ISO8601DateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ssZZZZZ";
    });
    return ISO8601DateFormatter;
}

@end
