//  SyncPendingViewController.mm

#import "SyncPendingViewController.h"
#import "PendingDetailsViewController.h"
#import "OfflineSyncManager.h"
#import "SyncPendingShareHelper.h"

typedef NS_ENUM(NSInteger, SyncPendingViewMode) {
    SyncPendingViewModeList,
    SyncPendingViewModeDetails,
    SyncPendingViewModeImage
};

@interface SyncPendingCardCell : UITableViewCell
- (void)configureWithItem:(NSDictionary *)item;
@end

@interface SyncPendingCardCell ()
@property (nonatomic, strong) UIView *cardView;
@property (nonatomic, strong) UILabel *unitLabel;
@property (nonatomic, strong) UILabel *createdByLabel;
@property (nonatomic, strong) UILabel *createdOnLabel;
@property (nonatomic, strong) UILabel *actionLabel;
@end

@implementation SyncPendingCardCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style
              reuseIdentifier:(NSString *)reuseIdentifier {

    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {

        self.backgroundColor = UIColor.clearColor;
        self.selectionStyle = UITableViewCellSelectionStyleGray;

        self.cardView = [[UIView alloc] init];
        self.cardView.backgroundColor = UIColor.whiteColor;
        self.cardView.layer.cornerRadius = 10;
        self.cardView.layer.shadowColor = UIColor.blackColor.CGColor;
        self.cardView.layer.shadowOpacity = 0.1;
        self.cardView.layer.shadowRadius = 4;
        self.cardView.layer.shadowOffset = CGSizeMake(0, 2);
        self.cardView.translatesAutoresizingMaskIntoConstraints = NO;
        self.cardView.userInteractionEnabled = YES;

        [self.contentView addSubview:self.cardView];

        self.unitLabel = [self makeLabel:16 bold:YES];
        self.createdByLabel = [self makeLabel:14 bold:NO];
        self.createdOnLabel = [self makeLabel:14 bold:NO];
        self.actionLabel = [self makeLabel:14 bold:NO];

        UIStackView *stack = [[UIStackView alloc] initWithArrangedSubviews:@[
            self.unitLabel,
            self.createdByLabel,
            self.createdOnLabel,
            self.actionLabel
        ]];

        stack.axis = UILayoutConstraintAxisVertical;
        stack.spacing = 12;
        stack.translatesAutoresizingMaskIntoConstraints = NO;

        [self.cardView addSubview:stack];

        [NSLayoutConstraint activateConstraints:@[
            [self.cardView.topAnchor constraintEqualToAnchor:self.contentView.topAnchor constant:12],
            [self.cardView.bottomAnchor constraintEqualToAnchor:self.contentView.bottomAnchor constant:-12],
            [self.cardView.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],
            [self.cardView.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-16],
            [self.cardView.heightAnchor constraintEqualToConstant:150],

            [stack.topAnchor constraintEqualToAnchor:self.cardView.topAnchor constant:12],
            [stack.bottomAnchor constraintEqualToAnchor:self.cardView.bottomAnchor constant:-12],
            [stack.leadingAnchor constraintEqualToAnchor:self.cardView.leadingAnchor constant:12],
        ]];
    }
    return self;
}

- (UILabel *)makeLabel:(CGFloat)size bold:(BOOL)bold {
    UILabel *label = [[UILabel alloc] init];
    label.font = bold ? [UIFont boldSystemFontOfSize:size]
                      : [UIFont systemFontOfSize:size];
    label.textColor = UIColor.blackColor;
    label.numberOfLines = 0;
    return label;
}

- (void)configureWithItem:(NSDictionary *)item {
    self.unitLabel.text = item[@"unitName"];
    self.createdByLabel.text =
        [NSString stringWithFormat:@"Created By: %@", item[@"createdBy"]];
    self.createdOnLabel.text =
        [NSString stringWithFormat:@"Created On: %@", item[@"createdOn"]];
    self.actionLabel.text =
        [NSString stringWithFormat:@"Action made: %@", item[@"type"]];
}

@end


@interface SyncPendingViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIButton *backButton;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *shareButton;

@property (nonatomic, strong) UITableView *tableView;

// Placeholder data
@property (nonatomic, strong) NSArray *sections;

@property (nonatomic, assign) SyncPendingViewMode viewMode;
@property (nonatomic, strong) NSDictionary *selectedItem;

@property (nonatomic, assign) BOOL isLoading;

@property (nonatomic, strong) NSArray<NSDictionary *> *arrayPendingItems;

@end

@interface ProjectSectionHeaderView : UIView
@property (nonatomic, strong) UILabel *titleLabel;
@end

@implementation ProjectSectionHeaderView

- (instancetype)init {
    self = [super init];
    if (self) {
        self.backgroundColor = UIColor.blackColor;

        self.titleLabel = [[UILabel alloc] init];
        self.titleLabel.textColor = UIColor.whiteColor;
        self.titleLabel.font = [UIFont boldSystemFontOfSize:14];
        self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;

        [self addSubview:self.titleLabel];

        [NSLayoutConstraint activateConstraints:@[
            [self.titleLabel.leadingAnchor constraintEqualToAnchor:self.leadingAnchor constant:16],
            [self.titleLabel.trailingAnchor constraintEqualToAnchor:self.trailingAnchor constant:-16],
            [self.titleLabel.centerYAnchor constraintEqualToAnchor:self.centerYAnchor],
        ]];
    }
    return self;
}

@end


@implementation SyncPendingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.viewMode = SyncPendingViewModeList;
    self.view.backgroundColor = [UIColor systemGroupedBackgroundColor];
  
    [[NSNotificationCenter defaultCenter]
        addObserver:self
           selector:@selector(loadPendingData)
               name:@"OfflineSyncUpdated"
             object:nil];

    [self setupHeader];
    [self setupTableView];
    [self setupDummyData];
    [self loadPendingData];
}

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

#pragma mark - Header
- (void)setupHeader {
    self.headerView = [[UIView alloc] init];
    self.headerView.backgroundColor = [UIColor colorWithRed:0.0 green:0.5 blue:0.6 alpha:1.0];
    self.headerView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.headerView];

    self.backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.backButton setImage:[UIImage systemImageNamed:@"chevron.backward"]
                     forState:UIControlStateNormal];
    self.backButton.tintColor = UIColor.whiteColor;
    [self.backButton addTarget:self
                        action:@selector(onBack)
              forControlEvents:UIControlEventTouchUpInside];
    self.backButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.headerView addSubview:self.backButton];

    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.text = @"Pending Items";
    self.titleLabel.textColor = UIColor.whiteColor;
    self.titleLabel.font = [UIFont boldSystemFontOfSize:18];
    self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.headerView addSubview:self.titleLabel];

    self.shareButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.shareButton setTitle:@"Share to Email" forState:UIControlStateNormal];
    [self.shareButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    self.shareButton.layer.borderColor = UIColor.whiteColor.CGColor;
    self.shareButton.layer.borderWidth = 0.5;
    self.shareButton.layer.cornerRadius = 14;
    [self.shareButton addTarget:self
                        action:@selector(onShare)
              forControlEvents:UIControlEventTouchUpInside];
    self.shareButton.titleLabel.font = [UIFont systemFontOfSize:14];
    self.shareButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.headerView addSubview:self.shareButton];

    [NSLayoutConstraint activateConstraints:@[
        [self.headerView.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor],
        [self.headerView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.headerView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.headerView.heightAnchor constraintEqualToConstant:44],

        [self.backButton.leadingAnchor constraintEqualToAnchor:self.headerView.leadingAnchor constant:16],
        [self.backButton.centerYAnchor constraintEqualToAnchor:self.headerView.centerYAnchor],
        [self.backButton.widthAnchor constraintEqualToConstant:24],
        [self.backButton.heightAnchor constraintEqualToConstant:24],

        [self.titleLabel.centerXAnchor constraintEqualToAnchor:self.headerView.centerXAnchor],
        [self.titleLabel.centerYAnchor constraintEqualToAnchor:self.headerView.centerYAnchor],

        [self.shareButton.trailingAnchor constraintEqualToAnchor:self.headerView.trailingAnchor constant:-8],
        [self.shareButton.centerYAnchor constraintEqualToAnchor:self.headerView.centerYAnchor],
        [self.shareButton.heightAnchor constraintEqualToConstant:28],
        [self.shareButton.widthAnchor constraintEqualToConstant:120],
    ]];
}

#pragma mark - Table View
- (void)setupTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero
                                                  style:UITableViewStyleGrouped];
    self.tableView.translatesAutoresizingMaskIntoConstraints = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = UIColor.clearColor;
    self.tableView.estimatedRowHeight = 120;
    self.tableView.allowsSelection = YES;
  
    [self.tableView registerClass:SyncPendingCardCell.class
           forCellReuseIdentifier:@"CardCell"];

    [self.view addSubview:self.tableView];

    [NSLayoutConstraint activateConstraints:@[
        [self.tableView.topAnchor constraintEqualToAnchor:self.headerView.bottomAnchor],
        [self.tableView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.tableView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.tableView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor],
    ]];
}

#pragma mark - Data
- (void)loadPendingData {
    NSArray *pending = [[OfflineSyncManager shared] pendingItemsForUI];
    NSLog(@"🖥 [SyncPendingVC] Pending sections: %@", pending);

    if (pending.count > 0) {
        self.sections = pending;

        // Flatten all items into arrayPendingItems for sharing
        NSMutableArray *allItems = [NSMutableArray array];
        for (NSDictionary *section in pending) {
            [allItems addObjectsFromArray:section[@"items"]];
        }
        self.arrayPendingItems = allItems;

    } else {
        [self setupDummyData];

        // Flatten dummy items too
        NSMutableArray *allItems = [NSMutableArray array];
        for (NSDictionary *section in self.sections) {
            [allItems addObjectsFromArray:section[@"items"]];
        }
        self.arrayPendingItems = allItems;
    }

    [self reloadUI];
}

- (void)setupDummyData {
    self.sections = @[
        @{
            @"project": @"Project Alpha",
            @"items": @[
                @{
                    @"unitName": @"Unit A-01",
                    @"createdBy": @"John",
                    @"createdOn": @"2024-12-01",
                    @"type": @"Inspection"
                },
                @{
                    @"unitName": @"Unit A-02",
                    @"createdBy": @"Sarah",
                    @"createdOn": @"2024-12-02",
                    @"type": @"Checklist"
                }
            ]
        },
        @{
            @"project": @"Project Beta",
            @"items": @[
                @{
                    @"unitName": @"Unit B-01",
                    @"createdBy": @"Mike",
                    @"createdOn": @"2024-11-20",
                    @"type": @"Maintenance"
                }
            ]
        }
    ];
}

#pragma mark - Table View
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.sections.count;
}

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

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    SyncPendingCardCell *cell =
        [tableView dequeueReusableCellWithIdentifier:@"CardCell"
                                        forIndexPath:indexPath];

    NSDictionary *item =
        self.sections[indexPath.section][@"items"][indexPath.row];

    [cell configureWithItem:item];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"Tapped section %ld row %ld", (long)indexPath.section, (long)indexPath.row);

    NSDictionary *item =
        self.sections[indexPath.section][@"items"][indexPath.row];

    NSDictionary *raw = item[@"raw"] ?: item;
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self showDetailsForItem:raw];
}

- (CGFloat)tableView:(UITableView *)tableView
heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}

- (UIView *)tableView:(UITableView *)tableView
viewForHeaderInSection:(NSInteger)section {

    ProjectSectionHeaderView *header =
        [[ProjectSectionHeaderView alloc] init];

    header.titleLabel.text =
        self.sections[section][@"project"];

    return header;
}

- (CGFloat)tableView:(UITableView *)tableView
heightForHeaderInSection:(NSInteger)section {
    return 36; // matches OG nicely
}

#pragma mark - Helpers
- (void)onBack {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)showDetailsForItem:(NSDictionary *)item {
    PendingDetailsViewController *vc = [PendingDetailsViewController new];
    vc.itemData = item;
    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:vc animated:YES completion:nil];
}

- (void)onShare {
    [SyncPendingShareHelper sharePendingItems:self.arrayPendingItems
                                fromController:self];
}

- (UIView *)emptyStateView {
    UILabel *label = [[UILabel alloc] init];
    label.text = @"No pending items";
    label.textColor = UIColor.secondaryLabelColor;
    label.textAlignment = NSTextAlignmentCenter;
    return label;
}

- (void)reloadUI {
    if (self.sections.count == 0) {
        self.tableView.backgroundView = [self emptyStateView];
    } else {
        self.tableView.backgroundView = nil;
    }
    [self.tableView reloadData];
}

- (void)setIsLoading:(BOOL)isLoading {
    _isLoading = isLoading;
    self.view.userInteractionEnabled = !isLoading;
}




@end
