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

@interface FGHistoryViewController ()
@property (nonatomic, strong) NSArray<NSDictionary *> *sections;
@property (nonatomic, strong) NSDateFormatter *dayFormatter;
@property (nonatomic, strong) NSDateFormatter *timeFormatter;
@end

@implementation FGHistoryViewController

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

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"Lịch sử";
    self.tableView.backgroundColor = [FGTheme screenBackground];
    self.tableView.rowHeight = 66;

    self.dayFormatter = [[NSDateFormatter alloc] init];
    self.dayFormatter.dateFormat = @"dd/MM/yyyy";
    self.dayFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"vi_VN"];

    self.timeFormatter = [[NSDateFormatter alloc] init];
    self.timeFormatter.dateFormat = @"HH:mm";
    self.timeFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"vi_VN"];

    self.navigationItem.rightBarButtonItem =
        [[UIBarButtonItem alloc] initWithImage:[FGTheme symbolNamed:@"trash" size:18 weight:UIFontWeightSemibold]
                                          style:UIBarButtonItemStylePlain
                                         target:self
                                         action:@selector(clearTapped)];

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

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

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

- (void)rebuildSections {
    NSArray<NSDictionary *> *history = [FGStore historyItems];
    NSMutableArray *sections = [NSMutableArray array];
    NSMutableDictionary *buckets = [NSMutableDictionary dictionary];

    NSInteger index = 0;
    for (NSDictionary *item in history) {
        NSDate *date = [item[FGItemDate] isKindOfClass:[NSDate class]] ? item[FGItemDate] : [NSDate date];
        NSString *key = [self.dayFormatter stringFromDate:date];

        NSMutableDictionary *bucket = buckets[key];
        if (!bucket) {
            bucket = [NSMutableDictionary dictionaryWithDictionary:@{@"title": [self titleForDate:date],
                                                                     @"items": [NSMutableArray array]}];
            buckets[key] = bucket;
            [sections addObject:bucket];
        }

        NSMutableDictionary *entry = [item mutableCopy];
        entry[@"_index"] = @(index);
        [(NSMutableArray *)bucket[@"items"] addObject:entry];
        index++;
    }

    self.sections = sections;
    self.tableView.backgroundView = history.count ? nil : [self emptyView];
    [self.tableView reloadData];
}

- (NSString *)titleForDate:(NSDate *)date {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    if ([calendar isDateInToday:date]) return @"Hôm nay";
    if ([calendar isDateInYesterday:date]) return @"Hôm qua";
    return [self.dayFormatter stringFromDate:date];
}

- (UIView *)emptyView {
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
    label.text = @"Chưa có lịch sử.\nMỗi lần đặt vị trí sẽ được ghi lại ở đây.";
    label.numberOfLines = 0;
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [FGTheme bodyFont];
    label.textColor = [FGTheme secondaryText];
    label.frame = CGRectInset(self.tableView.bounds, 32, 0);
    return label;
}

- (void)clearTapped {
    if (!self.sections.count) return;

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Xoá toàn bộ lịch sử?"
                                                                   message:@"Thao tác này không thể hoàn tác."
                                                            preferredStyle:UIAlertControllerStyleActionSheet];
    [alert addAction:[UIAlertAction actionWithTitle:@"Huỷ" style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:@"Xoá tất cả" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
        [FGStore clearHistory];
        [FGToast show:@"Đã xoá lịch sử" inView:self.view];
    }]];

    alert.popoverPresentationController.barButtonItem = self.navigationItem.rightBarButtonItem;
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - Bảng

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return (NSInteger)self.sections.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [(NSArray *)self.sections[section][@"items"] count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return self.sections[section][@"title"];
}

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

    NSDictionary *item = [self itemAtIndexPath:indexPath];
    CLLocationCoordinate2D coordinate = FGCoordinateMake([item[FGItemLatitude] doubleValue],
                                                         [item[FGItemLongitude] doubleValue]);

    NSDate *date = [item[FGItemDate] isKindOfClass:[NSDate class]] ? item[FGItemDate] : [NSDate date];
    NSString *time = [self.timeFormatter stringFromDate:date];
    NSString *address = item[FGItemAddress];
    if (!address.length) address = FGCoordString(coordinate);

    cell.textLabel.text = item[FGItemName] ?: @"Vị trí";
    cell.textLabel.font = [FGTheme bodyBoldFont];
    cell.textLabel.textColor = [FGTheme primaryText];

    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ • %@", time, address];
    cell.detailTextLabel.font = [FGTheme captionFont];
    cell.detailTextLabel.textColor = [FGTheme secondaryText];

    cell.imageView.image = [FGTheme symbolNamed:@"clock.arrow.circlepath" size:22 weight:UIFontWeightRegular];
    cell.imageView.tintColor = [FGTheme secondaryText];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.backgroundColor = [FGTheme cardBackground];
    return cell;
}

- (NSDictionary *)itemAtIndexPath:(NSIndexPath *)indexPath {
    NSArray *items = self.sections[indexPath.section][@"items"];
    return items[indexPath.row];
}

- (NSInteger)flatIndexForIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *item = [self itemAtIndexPath:indexPath];
    return [item[@"_index"] integerValue];
}

- (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)) {
        NSInteger index = [weakSelf flatIndexForIndexPath:indexPath];
        [FGStore removeHistoryItemAtIndex:(NSUInteger)index];
        [weakSelf rebuildSections];
        completionHandler(YES);
    }];
    deleteAction.image = [FGTheme symbolNamed:@"trash" size:18 weight:UIFontWeightSemibold];

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

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

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

    [[FGSpoofer shared] applyCoordinate:coordinate];
    [[NSNotificationCenter defaultCenter] postNotificationName:FGRequestApplyLocationNotification
                                                        object:nil
                                                      userInfo:@{@"item": item}];
    [FGToast show:@"Đã áp dụng vị trí từ lịch sử" inView:self.view];
}

@end
