#import "DashboardViewController.h"
#import "DashboardHeaderView.h"
#import <CoreGraphics/CoreGraphics.h>
#import "AddIssueViewController.h"

@implementation DashboardViewController {
    DashboardHeaderView *_headerView;
    UIScrollView *_scrollView;
    UIView *_contentContainer;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithWhite:0.96 alpha:1.0]; // #F2F2F2

    [self setupHeader];
    [self setupScrollContent];
    [self setupFooter];

}

#pragma mark - Header

- (void)setupHeader {
    CGFloat headerHeight = 220.0;
    _headerView = [[DashboardHeaderView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, headerHeight)];
    [_headerView configureWithProjectName:@"Project A"
                                 unitName:@"Unit 3A"
                         backgroundImage:[UIImage imageNamed:@"header_bg"]
                            overlayImage:[UIImage imageNamed:@"overlay"]];
    [self.view addSubview:_headerView];
  
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    backButton.frame = CGRectMake(16, 44, 60, 40); // adjust Y for safe area
    [backButton setImage:[UIImage systemImageNamed:@"chevron.left"] forState:UIControlStateNormal];
    [backButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    backButton.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    [backButton addTarget:self action:@selector(handleBackButtonTapped)
         forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backButton];
}

- (void)handleBackButtonTapped {
    NSLog(@"🔙 Back button tapped – attempting to close DashboardViewController");
    if (self.presentingViewController) {
        [self dismissViewControllerAnimated:YES completion:nil];
    } else if (self.navigationController) {
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        NSLog(@"⚠️ No parent VC found to close!");
    }
}

#pragma mark - Footer

- (void)setupFooter {
    CGFloat footerHeight = 80.0;
    CGFloat bottomInset = self.view.safeAreaInsets.bottom;
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(
        0,
        self.view.bounds.size.height - footerHeight,
        self.view.bounds.size.width,
        footerHeight + bottomInset
    )];
    footerView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth;
    footerView.backgroundColor = [UIColor whiteColor];
    footerView.layer.shadowColor = [UIColor colorWithWhite:0 alpha:0.1].CGColor;
    footerView.layer.shadowOpacity = 0.8;
    footerView.layer.shadowOffset = CGSizeMake(0, -1);
    [self.view addSubview:footerView];

    // Button info
    NSArray *titles = @[ @"Make Appointment", @"Add Issue", @"View Access Item" ];
    NSArray *icons  = @[ @"calendar", @"plus.circle", @"list.bullet" ];
    CGFloat visibleButtonHeight = footerHeight;
    CGFloat buttonWidth = self.view.bounds.size.width / titles.count;

    for (NSInteger i = 0; i < titles.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake(i * buttonWidth, 0, buttonWidth, visibleButtonHeight);
        [button setTitle:titles[i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0]
                     forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont boldSystemFontOfSize:13];
        button.tintColor = [UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0];

        UIImage *icon = [UIImage systemImageNamed:icons[i]];
        [button setImage:icon forState:UIControlStateNormal];

        // Center icon above title
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        button.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;

        // Adjust spacing between image and text
        CGFloat spacing = 6.0;
        CGSize imageSize = button.imageView.frame.size;
        CGSize titleSize = button.titleLabel.frame.size;

        button.titleEdgeInsets = UIEdgeInsetsMake(
            imageSize.height + spacing,           // move text below image
            -imageSize.width,                     // center horizontally
            0,
            0
        );

        button.imageEdgeInsets = UIEdgeInsetsMake(
            -titleSize.height - spacing / 2,      // move image up
            0,
            0,
            -titleSize.width
        );

        button.tag = i;
        [button addTarget:self action:@selector(footerButtonTapped:)
          forControlEvents:UIControlEventTouchUpInside];
        [footerView addSubview:button];

        // Divider line between buttons (except after last one)
        if (i < titles.count - 1) {
            UIView *divider = [[UIView alloc] initWithFrame:CGRectMake(
                (i + 1) * buttonWidth - 0.5,
                10,
                1,
                footerHeight - 20
            )];
            divider.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1.0];
            divider.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
            [footerView addSubview:divider];
        }
    }
}

- (void)footerButtonTapped:(UIButton *)sender {
    NSLog(@"🟢 Footer button tapped with tag: %ld", (long)sender.tag);
    NSString *title = sender.titleLabel.text;
    NSLog(@"Footer button tapped: %@", title);

    switch (sender.tag) {
        case 0:
            // Make Appointment
            NSLog(@"Make Appointment tapped");
            break;

        case 1: {
            // Add Issue
            AddIssueViewController *addIssueVC = [[AddIssueViewController alloc] init];
            addIssueVC.modalPresentationStyle = UIModalPresentationFullScreen;
            if (!addIssueVC) {
                NSLog(@"❌ AddIssueViewController class not found!");
                return;
            }
            [self presentViewController:addIssueVC animated:YES completion:nil];
            break;
        }

        case 2:
            // View Access Item
            NSLog(@"View Access Item tapped");
            break;

        default:
            break;
    }
}

#pragma mark - Scrollable Content

- (void)setupScrollContent {
    CGFloat topOffset = 220.0;
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, topOffset, self.view.bounds.size.width, self.view.bounds.size.height - topOffset)];
    _scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:_scrollView];
    _scrollView.clipsToBounds = NO;
  
    _contentContainer.clipsToBounds = NO;
    _contentContainer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _scrollView.bounds.size.width, 800)];
    _contentContainer.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [_scrollView addSubview:_contentContainer];

    CGFloat y = 20;
    y = [self addSectionWithTitle:@"Project Update" text:@"12/10/2025\nAnnouncement Title" y:y];
    y = [self addSectionWithTitle:@"Appointments" text:@"You have a joint inspection on 25 Oct 2025" y:y];
    y = [self addSectionWithTitle:@"Issue Updates" text:@"Issue REF123 has been lodged." y:y];

    _contentContainer.frame = CGRectMake(0, 0, _scrollView.bounds.size.width, y + 20);
    _scrollView.contentSize = CGSizeMake(_scrollView.bounds.size.width, CGRectGetMaxY(_contentContainer.frame));
}

- (CGFloat)addSectionWithTitle:(NSString *)title text:(NSString *)text y:(CGFloat)y {
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(16, y, self.view.bounds.size.width - 32, 22)];
    titleLabel.text = title;
    titleLabel.font = [UIFont boldSystemFontOfSize:18];
    [_contentContainer addSubview:titleLabel];
    y += 30;

    UIView *card = [[UIView alloc] initWithFrame:CGRectMake(16, y, self.view.bounds.size.width - 32, 100)];
    card.backgroundColor = [UIColor whiteColor];
    card.layer.cornerRadius = 8;
    card.layer.shadowColor = [UIColor colorWithWhite:0 alpha:0.1].CGColor;
    card.layer.shadowOpacity = 0.8;
    card.layer.shadowOffset = CGSizeMake(0, 1);
    [_contentContainer addSubview:card];

    UILabel *body = [[UILabel alloc] initWithFrame:CGRectMake(12, 12, card.bounds.size.width - 24, 80)];
    body.text = text;
    body.numberOfLines = 0;
    body.font = [UIFont systemFontOfSize:15];
    [card addSubview:body];

    return y + 120;
}

@end
