#import "FGSavedViewController.h"
#import "FGStore.h"
#import "FGSpoofer.h"
#import "FGTheme.h"
#import "FGToast.h"

@interface FGSavedViewController ()
@property (nonatomic, copy) NSArray<NSDictionary *> *items;
@end

@implementation FGSavedViewController

- (instancetype)init {
    self = [super initWithStyle:UITableViewStyleInsetGrouped];
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"Đã lưu";
    self.tableView.backgroundColor = [FGTheme screenBackground];
    self.tableView.rowHeight = 66;

    self.navigationItem.rightBarButtonItem =
        [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
                                                      target:self
                                                      action:@selector(addCurrentTapped)];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(storeChanged:)
                                                 name:FGStoreDidChangeNotification
                                               object:nil];
    [self reloadItems];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)reloadItems {
    self.items = [FGStore savedLocations];
    self.tableView.backgroundView = self.items.count ? nil : [self emptyView];
    [self.tableView reloadData];
}

- (void)storeChanged:(NSNotification *)note {
    [self reloadItems];
}

- (UIView *)emptyView {
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
    label.text = @"Chưa có địa điểm nào.\nChọn một vị trí trên bản đồ rồi bấm “Lưu”.";
    label.numberOfLines = 0;
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [FGTheme bodyFont];
    label.textColor = [FGTheme secondaryText];
    label.frame = CGRectInset(self.tableView.bounds, 32, 0);
    return label;
}

#pragma mark - Thêm nhanh

- (void)addCurrentTapped {
    if (![FGStore hasCoordinate]) {
        [FGToast show:@"Chưa có vị trí giả lập. Hãy chọn trên bản đồ trước." inView:self.view];
        return;
    }

    CLLocationCoordinate2D coordinate = [FGStore coordinate];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Lưu vị trí hiện tại"
                                                                   message:FGCoordString(coordinate)
                                                            preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.placeholder = @"Tên địa điểm";
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    }];
    [alert addAction:[UIAlertAction actionWithTitle:@"Huỷ" style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:@"Lưu" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        NSString *name = alert.textFields.firstObject.text;
        if (!name.length) name = FGCoordString(coordinate);

        [FGStore addSavedLocation:@{
            FGItemName: name,
            FGItemAddress: name,
            FGItemLatitude: @(coordinate.latitude),
            FGItemLongitude: @(coordinate.longitude),
            FGItemAltitude: @([FGStore altitude]),
            FGItemDate: [NSDate date]
        }];
        [FGToast show:@"Đã lưu địa điểm" inView:self.view];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - Bảng

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; }

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return (NSInteger)self.items.count;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return self.items.count ? @"Chạm để áp dụng • Vuốt để sửa hoặc xoá" : nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"FGSavedCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }

    NSDictionary *item = self.items[indexPath.row];
    CLLocationCoordinate2D coordinate = FGCoordinateMake([item[FGItemLatitude] doubleValue],
                                                         [item[FGItemLongitude] doubleValue]);

    cell.textLabel.text = item[FGItemName] ?: @"Địa điểm";
    cell.textLabel.font = [FGTheme bodyBoldFont];
    cell.textLabel.textColor = [FGTheme primaryText];

    NSString *address = item[FGItemAddress];
    cell.detailTextLabel.text = address.length ? address : FGCoordString(coordinate);
    cell.detailTextLabel.font = [FGTheme captionFont];
    cell.detailTextLabel.textColor = [FGTheme secondaryText];

    cell.imageView.image = [FGTheme symbolNamed:@"mappin.circle.fill" size:24 weight:UIFontWeightRegular];
    cell.imageView.tintColor = [FGTheme accent];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.backgroundColor = [FGTheme cardBackground];
    return cell;
}

- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView
    trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath {

    __weak typeof(self) weakSelf = self;

    UIContextualAction *deleteAction =
        [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive
                                                title:@"Xoá"
                                              handler:^(UIContextualAction *action, UIView *sourceView, void (^completionHandler)(BOOL)) {
        [FGStore removeSavedLocationAtIndex:indexPath.row];
        [weakSelf reloadItems];
        completionHandler(YES);
    }];
    deleteAction.image = [FGTheme symbolNamed:@"trash" size:18 weight:UIFontWeightSemibold];

    UIContextualAction *renameAction =
        [UIContextualAction contextualActionWithStyle:UIContextualActionStyleNormal
                                                title:@"Đổi tên"
                                              handler:^(UIContextualAction *action, UIView *sourceView, void (^completionHandler)(BOOL)) {
        [weakSelf promptRenameAtIndex:indexPath.row];
        completionHandler(YES);
    }];
    renameAction.image = [FGTheme symbolNamed:@"pencil" size:18 weight:UIFontWeightSemibold];
    renameAction.backgroundColor = [FGTheme accent];

    return [UISwipeActionsConfiguration configurationWithActions:@[deleteAction, renameAction]];
}

- (void)promptRenameAtIndex:(NSUInteger)index {
    if (index >= self.items.count) return;
    NSDictionary *item = self.items[index];

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Đổi tên địa điểm"
                                                                   message:nil
                                                            preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.text = item[FGItemName];
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    }];
    [alert addAction:[UIAlertAction actionWithTitle:@"Huỷ" style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:@"Lưu" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        NSString *name = alert.textFields.firstObject.text;
        if (name.length) {
            [FGStore updateSavedLocationAtIndex:index name:name];
            [self reloadItems];
        }
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row >= (NSInteger)self.items.count) return;

    NSDictionary *item = self.items[indexPath.row];
    CLLocationCoordinate2D coordinate = FGCoordinateMake([item[FGItemLatitude] doubleValue],
                                                         [item[FGItemLongitude] doubleValue]);
    if (!FGCoordinateValid(coordinate)) {
        [FGToast show:@"Địa điểm này không còn toạ độ hợp lệ." inView:self.view];
        return;
    }

    [[FGSpoofer shared] applyCoordinate:coordinate];
    [FGStore addHistoryItem:@{
        FGItemName: item[FGItemName] ?: @"Địa điểm đã lưu",
        FGItemAddress: item[FGItemAddress] ?: @"",
        FGItemLatitude: @(coordinate.latitude),
        FGItemLongitude: @(coordinate.longitude),
        FGItemAltitude: @([FGStore altitude]),
        FGItemDate: [NSDate date]
    }];
    [[NSNotificationCenter defaultCenter] postNotificationName:FGRequestApplyLocationNotification
                                                        object:nil
                                                      userInfo:@{@"item": item}];
    [FGToast show:[NSString stringWithFormat:@"Đã áp dụng: %@", item[FGItemName] ?: @"địa điểm"]
           inView:self.view];
}

@end
