//  AccessItemViewController.m

#import "AccessItemViewController.h"
#import "APIClient.h"
#import <UIKit/UIKit.h>
#import "AccessAppointmentViewController.h"
#import "AccessTransactionViewController.h"
#import "PullToRefresh.h"

// Custom Card
@interface SubmittedItemCell : UITableViewCell

@property (nonatomic, strong) UIImageView *iconView;
@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) UILabel *codeLabel;
@property (nonatomic, strong) UILabel *possessor;
@property (nonatomic, strong) UIView *cardView;

- (void)configureWithItem:(NSDictionary *)item;

@end

@implementation SubmittedItemCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (!self) return nil;
    
    self.selectionStyle = UITableViewCellSelectionStyleNone;
  
    // Card container
    self.cardView = [[UIView alloc] init];
    self.cardView.translatesAutoresizingMaskIntoConstraints = NO;
    self.cardView.layer.cornerRadius = 12;
    self.cardView.backgroundColor = UIColor.whiteColor;
    self.cardView.layer.shadowColor = [UIColor blackColor].CGColor;
    self.cardView.layer.shadowOpacity = 0.05;
    self.cardView.layer.shadowRadius = 4;
    self.cardView.layer.shadowOffset = CGSizeMake(0, 2);

    [self.contentView addSubview:self.cardView];

    [NSLayoutConstraint activateConstraints:@[
        [self.cardView.topAnchor constraintEqualToAnchor:self.contentView.topAnchor constant:8],
        [self.cardView.bottomAnchor constraintEqualToAnchor:self.contentView.bottomAnchor constant:-8],
        [self.cardView.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],
        [self.cardView.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-16],
    ]];

    self.iconView = [[UIImageView alloc] init];
    self.iconView.translatesAutoresizingMaskIntoConstraints = NO;
    self.iconView.contentMode = UIViewContentModeScaleAspectFit;
    [self.cardView addSubview:self.iconView];
  
    self.possessor = [[UILabel alloc] init];
    self.possessor.translatesAutoresizingMaskIntoConstraints = NO;
    self.possessor.font = [UIFont boldSystemFontOfSize:16];
    [self.cardView addSubview:self.possessor];
    
    self.nameLabel = [[UILabel alloc] init];
    self.nameLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.nameLabel.font = [UIFont systemFontOfSize:14];
    [self.cardView addSubview:self.nameLabel];

    self.codeLabel = [[UILabel alloc] init];
    self.codeLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.codeLabel.font = [UIFont systemFontOfSize:14];
    self.codeLabel.textColor = UIColor.darkGrayColor;
    [self.cardView addSubview:self.codeLabel];
  
    self.possessor.numberOfLines = 0;
    self.nameLabel.numberOfLines = 0;
    self.codeLabel.numberOfLines = 0;

    [self setupConstraints];

    return self;
}

- (void)setupConstraints {
    [NSLayoutConstraint activateConstraints:@[
      [self.iconView.leadingAnchor constraintEqualToAnchor:self.cardView.leadingAnchor constant:12],
      [self.iconView.topAnchor constraintEqualToAnchor:self.cardView.topAnchor constant:12],
      [self.iconView.widthAnchor constraintEqualToConstant:32],
      [self.iconView.heightAnchor constraintEqualToConstant:32],

      [self.possessor.leadingAnchor constraintEqualToAnchor:self.iconView.trailingAnchor constant:12],
      [self.possessor.trailingAnchor constraintEqualToAnchor:self.cardView.trailingAnchor constant:-12],
      [self.possessor.topAnchor constraintEqualToAnchor:self.cardView.topAnchor constant:12],

      [self.nameLabel.leadingAnchor constraintEqualToAnchor:self.possessor.leadingAnchor],
      [self.nameLabel.trailingAnchor constraintEqualToAnchor:self.possessor.trailingAnchor],
      [self.nameLabel.topAnchor constraintEqualToAnchor:self.possessor.bottomAnchor constant:4],

      [self.codeLabel.leadingAnchor constraintEqualToAnchor:self.possessor.leadingAnchor],
      [self.codeLabel.trailingAnchor constraintEqualToAnchor:self.possessor.trailingAnchor],
      [self.codeLabel.topAnchor constraintEqualToAnchor:self.nameLabel.bottomAnchor constant:4],
      [self.codeLabel.bottomAnchor constraintEqualToAnchor:self.cardView.bottomAnchor constant:-12]
    ]];
}

- (UIImage *)iconForPossessor:(NSString *)possessor {
    if ([possessor.lowercaseString containsString:@"owner"]) {
        return [UIImage imageNamed:@"icon_owner"];
    }
    return [UIImage imageNamed:@"icon_other"];
}

- (void)configureWithItem:(NSDictionary *)item {
    self.nameLabel.text = item[@"name"] ?: @"";
    self.codeLabel.text = item[@"code"] ?: @"";
    self.possessor.text = item[@"possessor"] ?: @"";

    NSString *possessor = item[@"possessor"] ?: @"";
    self.iconView.image = [self iconForPossessor:possessor];
}

@end

@interface TransactionItemCell : UITableViewCell

@property (nonatomic, strong) UIView *cardView;
@property (nonatomic, strong) UIImageView *statusIcon;
@property (nonatomic, strong) UILabel *statusLabel;
@property (nonatomic, strong) UILabel *codeLabel;
@property (nonatomic, strong) UILabel *dateLabel;

- (void)configureWithItem:(NSDictionary *)item;

@end

@implementation TransactionItemCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (!self) return nil;

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

    // Card container
    self.cardView = [[UIView alloc] init];
    self.cardView.translatesAutoresizingMaskIntoConstraints = NO;
    self.cardView.backgroundColor = UIColor.whiteColor;
    self.cardView.layer.cornerRadius = 12;
    self.cardView.layer.masksToBounds = NO;
    self.cardView.layer.shadowColor = [UIColor blackColor].CGColor;
    self.cardView.layer.shadowOpacity = 0.05;
    self.cardView.layer.shadowRadius = 4;
    self.cardView.layer.shadowOffset = CGSizeMake(0, 2);
    [self.contentView addSubview:self.cardView];

    // Status icon
    self.statusIcon = [[UIImageView alloc] init];
    self.statusIcon.translatesAutoresizingMaskIntoConstraints = NO;
    self.statusIcon.contentMode = UIViewContentModeScaleAspectFit;
    [self.cardView addSubview:self.statusIcon];

    // Status label
    self.statusLabel = [[UILabel alloc] init];
    self.statusLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.statusLabel.font = [UIFont boldSystemFontOfSize:16];
    self.statusLabel.textColor = UIColor.darkGrayColor;
    self.statusLabel.numberOfLines = 0;
    self.statusLabel.lineBreakMode = NSLineBreakByWordWrapping;
    [self.cardView addSubview:self.statusLabel];

    // Code label
    self.codeLabel = [[UILabel alloc] init];
    self.codeLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.codeLabel.font = [UIFont systemFontOfSize:14];
    self.codeLabel.numberOfLines = 0;
    self.codeLabel.lineBreakMode = NSLineBreakByWordWrapping;
    [self.cardView addSubview:self.codeLabel];

    // Date label
    self.dateLabel = [[UILabel alloc] init];
    self.dateLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.dateLabel.font = [UIFont italicSystemFontOfSize:14];
    self.dateLabel.textColor = UIColor.grayColor;
    self.dateLabel.numberOfLines = 0;
    self.dateLabel.lineBreakMode = NSLineBreakByWordWrapping;
    [self.cardView addSubview:self.dateLabel];

    [self setupConstraints];

    return self;
}

- (void)setupConstraints {
    CGFloat padding = 12.0;

    [NSLayoutConstraint activateConstraints:@[
        // CardView edges
        [self.cardView.topAnchor constraintEqualToAnchor:self.contentView.topAnchor constant:padding],
        [self.cardView.bottomAnchor constraintEqualToAnchor:self.contentView.bottomAnchor constant:-padding],
        [self.cardView.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],
        [self.cardView.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-16],

        // Status icon
        [self.statusIcon.leadingAnchor constraintEqualToAnchor:self.cardView.leadingAnchor constant:padding],
        [self.statusIcon.topAnchor constraintEqualToAnchor:self.cardView.topAnchor constant:padding],
        [self.statusIcon.widthAnchor constraintEqualToConstant:28],
        [self.statusIcon.heightAnchor constraintEqualToConstant:28],

        // Status label
        [self.statusLabel.leadingAnchor constraintEqualToAnchor:self.statusIcon.trailingAnchor constant:padding],
        [self.statusLabel.trailingAnchor constraintEqualToAnchor:self.cardView.trailingAnchor constant:-padding],
        [self.statusLabel.topAnchor constraintEqualToAnchor:self.cardView.topAnchor constant:padding],

        // Code label
        [self.codeLabel.leadingAnchor constraintEqualToAnchor:self.statusLabel.leadingAnchor],
        [self.codeLabel.trailingAnchor constraintEqualToAnchor:self.statusLabel.trailingAnchor],
        [self.codeLabel.topAnchor constraintEqualToAnchor:self.statusLabel.bottomAnchor constant:4],

        // Date label
        [self.dateLabel.leadingAnchor constraintEqualToAnchor:self.statusLabel.leadingAnchor],
        [self.dateLabel.trailingAnchor constraintEqualToAnchor:self.statusLabel.trailingAnchor],
        [self.dateLabel.topAnchor constraintEqualToAnchor:self.codeLabel.bottomAnchor constant:4],
        [self.dateLabel.bottomAnchor constraintEqualToAnchor:self.cardView.bottomAnchor constant:-padding],
    ]];
}

- (UIImage *)iconForStatus:(NSString *)status {
    if ([status.lowercaseString containsString:@"approved"]) {
        return [UIImage imageNamed:@"icon_success"];
    }
    if ([status.lowercaseString containsString:@"pending"]) {
        return [UIImage imageNamed:@"icon_pending"];
    }
    if ([status.lowercaseString containsString:@"rectification"]) {
        return [UIImage imageNamed:@"icon_calendar"];
    }
    return [UIImage imageNamed:@"icon_default"];
}

- (void)configureWithItem:(NSDictionary *)item {
    self.statusLabel.text = item[@"status"] ?: @"";
    self.codeLabel.text = item[@"code"] ?: @"";
    NSString *rawDate = item[@"created_at"];
    self.dateLabel.text = [self formattedDateFromString:rawDate] ?: @"";

    NSString *status = item[@"status"] ?: @"";
    self.statusIcon.image = [self iconForStatus:status];
}

- (NSString *)formattedDateFromString:(NSString *)dateString {
    // 1. Input formatter matches your API format
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    inputFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    inputFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]; // ensures consistent parsing
    
    NSDate *date = [inputFormatter dateFromString:dateString];
    if (!date) return dateString; // fallback if parsing fails
    
    // 2. Output formatter for desired display
    NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
    outputFormatter.dateFormat = @"dd MMM yyyy h:mm a";
    outputFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US"];
    
    return [outputFormatter stringFromDate:date];
}

@end


@interface AccessItemViewController () <UITableViewDelegate, UITableViewDataSource>

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

// Main container
@property (nonatomic, strong) UIView *contentContainer;

@property (nonatomic, strong) UITableView *tableView;

// API
@property (nonatomic, strong) NSString *termsName;
@property (nonatomic, strong) NSString *termsContent;

@end

@implementation AccessItemViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self requestAccessItem];
    self.view.backgroundColor = UIColor.whiteColor;
    
    [self setupHeader];
    [self setupMainContainer];
    [self setupTable];
}

#pragma mark - Header
- (void)setupHeader{
    self.headerView = [[UIView alloc] init];
    self.headerView.backgroundColor = [UIColor colorWithRed:0.0 green:0.45 blue:0.55 alpha:1];
    self.headerView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.headerView];
    
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.textColor = UIColor.whiteColor;
    self.titleLabel.font = [UIFont boldSystemFontOfSize:18];
    self.titleLabel.text = @"Access Item";
    [self.headerView addSubview:self.titleLabel];
    
    self.backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.backButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.backButton setImage:[UIImage systemImageNamed:@"chevron.backward"]
                      forState:UIControlStateNormal];
    [self.backButton addTarget:self
                       action:@selector(onBack)
               forControlEvents:UIControlEventTouchUpInside];
    self.backButton.tintColor = UIColor.whiteColor;
    [self.headerView addSubview:self.backButton];
  
    [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:48],

        [self.backButton.leadingAnchor constraintEqualToAnchor:self.headerView.leadingAnchor constant:12],
        [self.backButton.centerYAnchor constraintEqualToAnchor:self.headerView.centerYAnchor],

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

#pragma mark - Container
- (void)setupMainContainer{
    self.contentContainer = [[UIView alloc] init];
    self.contentContainer.translatesAutoresizingMaskIntoConstraints = NO;
    self.contentContainer.backgroundColor = [UIColor colorWithWhite:0.96 alpha:1];
    [self.view addSubview:self.contentContainer];

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

#pragma mark - Setup Table
- (void)setupTable {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView.translatesAutoresizingMaskIntoConstraints = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 80;
    
    [self.tableView registerClass:[SubmittedItemCell class] forCellReuseIdentifier:@"SubmittedItemCell"];
    [self.tableView registerClass:[TransactionItemCell class] forCellReuseIdentifier:@"TransactionItemCell"];
    __weak typeof(self) weakSelf = self;

    [self.tableView addPullToRefresh:^(UIRefreshControl *refresh) {
        [weakSelf requestAccessItem];
    }];

    [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 - Api
- (void)requestAccessItem{
  [APIClient requestAccessItem:@"135"
                            completion:^(BOOL success, NSDictionary *data, NSError *error) {
    
    NSLog(@"📦 Received General Info Data: %@", data);
    NSDictionary *general = data[@"Data"];
    // 1️⃣ Write to file for debugging (your existing logic)
    NSString *plainText = [NSString stringWithFormat:@"%@", data];
    NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    NSString *filePath = [docsPath stringByAppendingPathComponent:@"generalData.txt"];
    [plainText writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"📁 appointData saved as plain text to: %@", filePath);
    
    NSDictionary *accessItem = data[@"Data"];
      
    self.termsName = accessItem[@"termsCondition_name"] ?: @"";
    self.termsContent = accessItem[@"termsCondition_content"] ?: @"";
    self.submittedItems = accessItem[@"item_submitted"] ?: @[];
    self.transactionItems = accessItem[@"item_transaction"] ?: @[];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
        [self.tableView endPullToRefresh];
    });
  }];
}

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

#pragma mark - TableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) return self.submittedItems.count;
    return self.transactionItems.count;
}

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

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

    if (indexPath.section == 0) {
        SubmittedItemCell *cell =
            [tableView dequeueReusableCellWithIdentifier:@"SubmittedItemCell" forIndexPath:indexPath];
        [cell configureWithItem:self.submittedItems[indexPath.row]];
        return cell;
    }

    TransactionItemCell *cell =
        [tableView dequeueReusableCellWithIdentifier:@"TransactionItemCell" forIndexPath:indexPath];
    [cell configureWithItem:self.transactionItems[indexPath.row]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.section == 1) {
        NSDictionary *item = self.transactionItems[indexPath.row];

        if ([item[@"status"] isEqualToString:@"Rectification Appointment"]) {
          AccessAppointmentViewController *vc = [[AccessAppointmentViewController alloc] init];
            vc.appointmentData = item;
            vc.unitID = self.unitID;
            vc.unitName = self.unitName;
            vc.modalPresentationStyle = UIModalPresentationFullScreen;
            [self presentViewController:vc animated:YES completion:nil];
        } else {
            AccessTransactionViewController *vc = [[AccessTransactionViewController alloc] init];
            vc.transactionData = item;
            vc.unitID = self.unitID;
            vc.termsName = self.termsName;
            vc.termsContent = self.termsContent;
            vc.modalPresentationStyle = UIModalPresentationFullScreen;
            [self presentViewController:vc animated:YES completion:nil];
        }
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return (section == 0) ? @"Submitted Items" : @"Transaction";
}

@end
