#import "FGSettingsViewController.h"
#import "FGStore.h"
#import "FGGoogleMaps.h"
#import "FGTheme.h"
#import "FGToast.h"
#import "FGAppBridge.h"

typedef NS_ENUM(NSInteger, FGSettingsSwitchTag) {
    FGSettingsSwitchAltitude = 5001,
    FGSettingsSwitchPush,
    FGSettingsSwitchFloating
};

@implementation FGSettingsViewController

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

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"Cài đặt";
    self.tableView.backgroundColor = [FGTheme screenBackground];
    self.tableView.rowHeight = 50;

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

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

- (void)storeChanged:(NSNotification *)note {
    [self.tableView reloadData];
}

#pragma mark - Bảng dữ liệu

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0: return 2;
        case 1: return 4;
        case 2: return 1;
        case 3: return 3;
        default: return 2;
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    switch (section) {
        case 0: return @"Google Maps";
        case 1: return @"Giả lập vị trí";
        case 2: return @"Giao diện";
        case 3: return @"Dữ liệu";
        default: return @"Thông tin";
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return @"Bật Places API (New) và Geocoding API trong Google Cloud Console. Không có key, ứng dụng vẫn chạy nhưng địa chỉ do Apple cung cấp.";
        case 1:
            return @"“Đẩy cập nhật” gửi vị trí giả mỗi giây cho ứng dụng đang dùng. Tắt nếu ứng dụng bị lag. Chế độ toạ độ: WGS84 cho Việt Nam, GCJ-02 cho bản đồ Trung Quốc.";
        case 2:
            return @"Nút nổi giúp mở nhanh bảng điều khiển FakeGPS ở bất kỳ màn hình nào.";
        case 3:
            return @"Các thao tác xoá không thể hoàn tác.";
        default:
            return @"FakeGPS Reborn 2.0 — chạy trên thiết bị không jailbreak, không phụ thuộc CydiaSubstrate.";
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 && indexPath.row == 0) {
        NSString *key = [FGStore googleAPIKey];
        NSString *value = key.length > 8
            ? [NSString stringWithFormat:@"••••%@", [key substringFromIndex:key.length - 4]]
            : @"Chưa cấu hình";
        return [self valueCell:@"API key" value:value];
    }
    if (indexPath.section == 0 && indexPath.row == 1) {
        UITableViewCell *cell = [self valueCell:@"Hướng dẫn lấy API key" value:@""];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        return cell;
    }

    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            return [self switchCell:@"Giả lập độ cao"
                                 on:[FGStore isAltitudeEnabled]
                                tag:FGSettingsSwitchAltitude];
        }
        if (indexPath.row == 1) {
            NSString *value = [NSString stringWithFormat:@"%.0f m", [FGStore altitude]];
            UITableViewCell *cell = [self valueCell:@"Độ cao" value:value];
            cell.detailTextLabel.textColor = [FGStore isAltitudeEnabled] ? [FGTheme accent] : [FGTheme secondaryText];
            cell.selectionStyle = [FGStore isAltitudeEnabled]
                ? UITableViewCellSelectionStyleDefault : UITableViewCellSelectionStyleNone;
            return cell;
        }
        if (indexPath.row == 2) {
            NSString *mode = [FGStore coordMode] == 1 ? @"GCJ-02" : @"WGS84";
            UITableViewCell *cell = [self valueCell:@"Chế độ toạ độ" value:mode];
            cell.detailTextLabel.textColor = [FGTheme accent];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            return cell;
        }
        return [self switchCell:@"Đẩy cập nhật vị trí"
                             on:[FGStore pushUpdatesEnabled]
                            tag:FGSettingsSwitchPush];
    }

    if (indexPath.section == 2) {
        return [self switchCell:@"Hiện nút nổi"
                             on:[FGStore floatingButtonEnabled]
                            tag:FGSettingsSwitchFloating];
    }

    if (indexPath.section == 3) {
        if (indexPath.row == 0) {
            NSUInteger count = [FGStore historyItems].count;
            return [self destructiveCell:@"Xoá lịch sử"
                                   value:[NSString stringWithFormat:@"%lu mục", (unsigned long)count]];
        }
        if (indexPath.row == 1) {
            NSUInteger count = [FGStore savedLocations].count;
            return [self destructiveCell:@"Xoá địa điểm đã lưu"
                                   value:[NSString stringWithFormat:@"%lu mục", (unsigned long)count]];
        }
        return [self destructiveCell:@"Đặt lại toàn bộ" value:@""];
    }

    if (indexPath.row == 0) {
        return [self valueCell:@"Phiên bản" value:@"2.0 (Reborn)"];
    }
    return [self valueCell:@"Nền tảng" value:@"iOS 14+ • arm64/arm64e"];
}

#pragma mark - Cell helpers

- (UITableViewCell *)valueCell:(NSString *)title value:(NSString *)value {
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
    cell.textLabel.text = title;
    cell.textLabel.font = [FGTheme bodyFont];
    cell.textLabel.textColor = [FGTheme primaryText];
    cell.detailTextLabel.text = value;
    cell.detailTextLabel.font = [FGTheme captionFont];
    cell.detailTextLabel.textColor = [FGTheme secondaryText];
    cell.backgroundColor = [FGTheme cardBackground];
    return cell;
}

- (UITableViewCell *)switchCell:(NSString *)title on:(BOOL)on tag:(NSInteger)tag {
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    cell.textLabel.text = title;
    cell.textLabel.font = [FGTheme bodyFont];
    cell.textLabel.textColor = [FGTheme primaryText];
    cell.backgroundColor = [FGTheme cardBackground];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    UISwitch *toggle = [[UISwitch alloc] initWithFrame:CGRectZero];
    toggle.on = on;
    toggle.onTintColor = [FGTheme accent];
    toggle.tag = tag;
    [toggle addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
    cell.accessoryView = toggle;
    return cell;
}

- (UITableViewCell *)destructiveCell:(NSString *)title value:(NSString *)value {
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
    cell.textLabel.text = title;
    cell.textLabel.font = [FGTheme bodyFont];
    cell.textLabel.textColor = [FGTheme danger];
    cell.detailTextLabel.text = value;
    cell.detailTextLabel.font = [FGTheme captionFont];
    cell.detailTextLabel.textColor = [FGTheme secondaryText];
    cell.backgroundColor = [FGTheme cardBackground];
    return cell;
}

#pragma mark - Hành động

- (void)switchChanged:(UISwitch *)sender {
    if (sender.tag == FGSettingsSwitchAltitude) {
        [FGStore setAltitudeEnabled:sender.isOn];
    } else if (sender.tag == FGSettingsSwitchPush) {
        [FGStore setPushUpdatesEnabled:sender.isOn];
    } else if (sender.tag == FGSettingsSwitchFloating) {
        [FGStore setFloatingButtonEnabled:sender.isOn];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"FGFloatingButtonSettingChanged" object:nil];
    }
    [self.tableView reloadData];
}

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

    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            [self editAPIKey];
        } else {
            [FGGoogleMaps openAPIKeyPage];
        }
        return;
    }

    if (indexPath.section == 1 && indexPath.row == 1) {
        if (![FGStore isAltitudeEnabled]) {
            [FGToast show:@"Bật “Giả lập độ cao” trước." inView:self.view];
            return;
        }
        [self editAltitude];
        return;
    }

    if (indexPath.section == 1 && indexPath.row == 2) {
        [self chooseCoordMode];
        return;
    }

    if (indexPath.section == 3) {
        if (indexPath.row == 0) {
            [self confirmTitle:@"Xoá toàn bộ lịch sử?"
                       message:@"Thao tác này không thể hoàn tác."
                   actionTitle:@"Xoá lịch sử"
                       handler:^{
                [FGStore clearHistory];
                [FGToast show:@"Đã xoá lịch sử" inView:self.view];
            }];
        } else if (indexPath.row == 1) {
            [self confirmTitle:@"Xoá các địa điểm đã lưu?"
                       message:@"Thao tác này không thể hoàn tác."
                   actionTitle:@"Xoá địa điểm"
                       handler:^{
                [FGStore clearSavedLocations];
                [FGToast show:@"Đã xoá địa điểm đã lưu" inView:self.view];
            }];
        } else {
            [self confirmTitle:@"Đặt lại toàn bộ?"
                       message:@"Xoá vị trí, lịch sử, địa điểm đã lưu và cài đặt."
                   actionTitle:@"Đặt lại"
                       handler:^{
                [FGStore resetEverything];
                [FGToast show:@"Đã đặt lại toàn bộ" inView:self.view];
            }];
        }
    }
}

- (void)editAPIKey {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Google Maps API key"
                                                                   message:@"Dán key từ Google Cloud Console (bắt đầu bằng AIza…)."
                                                            preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.text = [FGStore googleAPIKey];
        textField.placeholder = @"AIzaSy…";
        textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
        textField.autocorrectionType = UITextAutocorrectionTypeNo;
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    }];
    [alert addAction:[UIAlertAction actionWithTitle:@"Huỷ" style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:@"Xoá" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
        [FGStore setGoogleAPIKey:@""];
        [self.tableView reloadData];
        [FGToast show:@"Đã xoá API key" inView:self.view];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"Lưu" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        NSString *key = [alert.textFields.firstObject.text stringByTrimmingCharactersInSet:
                         [NSCharacterSet whitespaceAndNewlineCharacterSet]];
        [FGStore setGoogleAPIKey:key ?: @""];
        [self.tableView reloadData];
        [FGToast show:key.length ? @"Đã lưu API key" : @"Đã xoá API key" inView:self.view];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)chooseCoordMode {
    UIAlertController *sheet = [UIAlertController
        alertControllerWithTitle:@"Chế độ toạ độ"
                         message:@"WGS84 đúng cho Việt Nam. Chỉ chọn GCJ-02 khi bản đồ Trung Quốc hiển thị lệch."
                  preferredStyle:UIAlertControllerStyleActionSheet];

    [sheet addAction:[UIAlertAction actionWithTitle:@"WGS84 (khuyến nghị)"
                                             style:UIAlertActionStyleDefault
                                           handler:^(UIAlertAction *action) {
        [FGStore setCoordMode:0];
        [self.tableView reloadData];
        [FGToast show:@"Đang xuất toạ độ WGS84" inView:self.view];
    }]];

    [sheet addAction:[UIAlertAction actionWithTitle:@"GCJ-02 (Trung Quốc)"
                                             style:UIAlertActionStyleDefault
                                           handler:^(UIAlertAction *action) {
        [FGStore setCoordMode:1];
        [self.tableView reloadData];
        [FGToast show:@"Đang xuất toạ độ GCJ-02" inView:self.view];
    }]];

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

    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:1]];
    sheet.popoverPresentationController.sourceView = cell ?: self.view;
    sheet.popoverPresentationController.sourceRect = cell ? cell.bounds : self.view.bounds;
    [self presentViewController:sheet animated:YES completion:nil];
}

- (void)editAltitude {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Độ cao giả lập"
                                                                   message:@"Nhập độ cao theo mét (có thể âm)."
                                                            preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.text = [NSString stringWithFormat:@"%.0f", [FGStore altitude]];
        textField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    }];
    [alert addAction:[UIAlertAction actionWithTitle:@"Huỷ" style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:@"Lưu" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        double value = 25.0;
        NSString *text = [alert.textFields.firstObject.text stringByReplacingOccurrencesOfString:@"," withString:@"."];
        NSScanner *scanner = [NSScanner scannerWithString:text];
        if ([scanner scanDouble:&value] && scanner.isAtEnd && !isnan(value) && !isinf(value)) {
            [FGStore setAltitude:value];
            [self.tableView reloadData];
            [FGToast show:[NSString stringWithFormat:@"Độ cao: %.0f m", [FGStore altitude]] inView:self.view];
        } else {
            [FGToast show:@"Giá trị không hợp lệ." inView:self.view];
        }
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)confirmTitle:(NSString *)title
             message:(NSString *)message
         actionTitle:(NSString *)actionTitle
             handler:(void (^)(void))handler {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title
                                                                   message:message
                                                            preferredStyle:UIAlertControllerStyleActionSheet];
    [alert addAction:[UIAlertAction actionWithTitle:@"Huỷ" style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:actionTitle
                                             style:UIAlertActionStyleDestructive
                                           handler:^(UIAlertAction *action) {
        if (handler) handler();
        [self.tableView reloadData];
    }]];
    alert.popoverPresentationController.sourceView = self.view;
    alert.popoverPresentationController.sourceRect = self.view.bounds;
    [self presentViewController:alert animated:YES completion:nil];
}

@end
