//  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 icon:(UIImage *)icon;
@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: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.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:16],
      [self.iconView.topAnchor constraintEqualToAnchor:self.cardView.topAnchor constant:12],
      [self.iconView.widthAnchor constraintEqualToConstant:24],
      [self.iconView.heightAnchor constraintEqualToConstant:24],

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

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

      [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:-16]
    ]];
}

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

@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 icon:(UIImage *)icon;

@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 {
    [NSLayoutConstraint activateConstraints:@[
        // CardView edges
        [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],

        // Status icon
        [self.statusIcon.leadingAnchor constraintEqualToAnchor:self.cardView.leadingAnchor constant:16],
        [self.statusIcon.topAnchor constraintEqualToAnchor:self.cardView.topAnchor constant:12],
        [self.statusIcon.widthAnchor constraintEqualToConstant:24],
        [self.statusIcon.heightAnchor constraintEqualToConstant:24],

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

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

        // 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:-16],
    ]];
}

- (void)configureWithItem:(NSDictionary *)item icon:(UIImage *)icon {
    self.statusLabel.text = item[@"status"] ?: @"";
    self.codeLabel.text = item[@"code"] ?: @"";
    self.dateLabel.text =
        [self formattedDateFromString:item[@"created_at"]] ?: @"";
    self.statusIcon.image = icon;
}

- (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:^(BOOL success, NSDictionary *data, NSError *error) {
    
    NSLog(@"📦 Received General Info 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) {
        NSDictionary *item = self.submittedItems[indexPath.row];

        UIImage *icon = [self iconForSubmittedItem:item];

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

        [cell configureWithItem:item icon:icon];
        return cell;
    }

    NSDictionary *item = self.transactionItems[indexPath.row];

    UIImage *icon = [self iconForTransactionItem:item];

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

    [cell configureWithItem:item icon:icon];
    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";
}

- (NSString *)normalizedString:(NSString *)value {
    if (![value isKindOfClass:[NSString class]]) return @"";
    return [[value lowercaseString] stringByTrimmingCharactersInSet:
            [NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

- (UIImage *)iconForSubmittedItem:(NSDictionary *)item {
    NSBundle *bundle = [NSBundle bundleForClass:[self class]];
    NSString *possessor = [self normalizedString:item[@"possessor"]];
    if (possessor.length == 0) {
        return [UIImage imageNamed:@"icon_notification_black"
                          inBundle:bundle
     compatibleWithTraitCollection:nil];
    }

    if ([possessor containsString:@"handler"]) {
        return [UIImage imageNamed:@"icon_handler_green"
                          inBundle:bundle
     compatibleWithTraitCollection:nil];
    }

    return [UIImage imageNamed:@"icon_management_green"
                      inBundle:bundle
         compatibleWithTraitCollection:nil];
}

- (UIImage *)iconForTransactionItem:(NSDictionary *)item {
    NSBundle *bundle = [NSBundle bundleForClass:[self class]];
    NSString *status = [self normalizedString:item[@"status"]];

    if (status.length == 0) {
        return [UIImage imageNamed:@"icon_notification_black"
                          inBundle:bundle
             compatibleWithTraitCollection:nil];
    }

    if ([status containsString:@"submit"]) {
        return [UIImage imageNamed:@"icon_submitted_green"
                          inBundle:bundle
             compatibleWithTraitCollection:nil];
    }

    if ([status containsString:@"rectification appointment"]) {
        return [UIImage imageNamed:@"icon_handler_green"
                          inBundle:bundle
             compatibleWithTraitCollection:nil];
    }

    return [UIImage imageNamed:@"icon_return_green"
                      inBundle:bundle
         compatibleWithTraitCollection:nil];
}

@end
