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

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

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

    _sectionViews = [NSMutableDictionary dictionary];

    [self setupHeader];
    [self setupScrollContent];
    [self setupFooter];
    [self fetchDashboardData];
}

#pragma mark - Layout

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    UIView *footerView = self.view.subviews.lastObject;
    CGFloat footerHeight = 80.0;
    CGFloat bottomInset = self.view.safeAreaInsets.bottom;
    footerView.frame = CGRectMake(
        0,
        self.view.bounds.size.height - footerHeight - bottomInset,
        self.view.bounds.size.width,
        footerHeight + bottomInset
    );
}

#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.translatesAutoresizingMaskIntoConstraints = NO;
    UIImage *backImage = [[UIImage systemImageNamed:@"chevron.left"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    [backButton setImage:backImage forState:UIControlStateNormal];
    backButton.tintColor = [UIColor whiteColor];
    [backButton addTarget:self action:@selector(handleBackButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backButton];

    UIButton *menuButton = [UIButton buttonWithType:UIButtonTypeSystem];
    menuButton.translatesAutoresizingMaskIntoConstraints = NO;
    UIImage *menuImage = [[UIImage systemImageNamed:@"line.3.horizontal"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    [menuButton setImage:menuImage forState:UIControlStateNormal];
    menuButton.tintColor = [UIColor whiteColor];
    [menuButton addTarget:self action:@selector(handleMenuButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:menuButton];

    [NSLayoutConstraint activateConstraints:@[
        [backButton.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:8],
        [backButton.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor constant:4],
        [backButton.widthAnchor constraintEqualToConstant:44],
        [backButton.heightAnchor constraintEqualToConstant:44],

        [menuButton.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:-8],
        [menuButton.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor constant:4],
        [menuButton.widthAnchor constraintEqualToConstant:44],
        [menuButton.heightAnchor constraintEqualToConstant:44],
    ]];
}

- (void)handleBackButtonTapped {
    NSLog(@"🔙 Back button tapped");
    if (self.presentingViewController) {
        [self dismissViewControllerAnimated:YES completion:nil];
    } else if (self.navigationController) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)handleMenuButtonTapped {
    NSLog(@"🍔 Menu button tapped");
}

#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];

    NSArray *titles = @[ @"Make Appointment", @"Add Issue", @"View Access Item" ];
    NSArray *icons = @[ @"calendar", @"plus.circle", @"list.bullet" ];
    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, footerHeight);
        [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];
        [button setImage:[UIImage systemImageNamed:icons[i]] forState:UIControlStateNormal];

        button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        button.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        CGFloat spacing = 6.0;
        CGSize imageSize = button.imageView.frame.size;
        CGSize titleSize = button.titleLabel.frame.size;

        button.titleEdgeInsets = UIEdgeInsetsMake(imageSize.height + spacing, -imageSize.width, 0, 0);
        button.imageEdgeInsets = UIEdgeInsetsMake(-titleSize.height - spacing / 2, 0, 0, -titleSize.width);

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

        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];
            [footerView addSubview:divider];
        }
    }
}

- (void)footerButtonTapped:(UIButton *)sender {
    switch (sender.tag) {
        case 1: {
            PlanViewController *planVC = [[PlanViewController alloc] init];
            planVC.modalPresentationStyle = UIModalPresentationFullScreen;
            [self presentViewController:planVC animated:YES completion:nil];
            break;
        }
        default:
            break;
    }
}

#pragma mark - Scroll 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;
    _scrollView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_scrollView];

    _contentContainer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _scrollView.bounds.size.width, 0)];
    _contentContainer.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [_scrollView addSubview:_contentContainer];

    CGFloat y = 20;

    // Add 3 fixed section titles, store them for later population
    NSArray *sectionNames = @[ @"Project Update", @"Appointments", @"Issue Updates" ];
    for (NSString *name in sectionNames) {
        UILabel *header = [[UILabel alloc] initWithFrame:CGRectMake(16, y, self.view.bounds.size.width - 32, 24)];
        header.text = name;
        header.font = [UIFont boldSystemFontOfSize:18];
        [_contentContainer addSubview:header];
        y += 30;

        UIView *sectionContainer = [[UIView alloc] initWithFrame:CGRectMake(0, y, self.view.bounds.size.width, 0)];
        [_contentContainer addSubview:sectionContainer];
        _sectionViews[name] = sectionContainer;

        y += 20; // spacing before next section
    }

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

#pragma mark - Networking

- (void)fetchDashboardData {
    NSURL *url = [NSURL URLWithString:@"https://jsonplaceholder.typicode.com/posts?_limit=9"];
    __weak typeof(self) weakSelf = self;
    [[[NSURLSession sharedSession] dataTaskWithURL:url
                                 completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error) return;
        NSArray *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf populateSectionsWithData:json];
        });
    }] resume];
}

- (void)populateSectionsWithData:(NSArray *)data {
    NSArray *sectionKeys = @[ @"Project Update", @"Appointments", @"Issue Updates" ];
    int itemsPerSection = (int)ceil(data.count / 3.0);

    CGFloat sectionBottomY = 0;
    for (int i = 0; i < sectionKeys.count; i++) {
        NSString *key = sectionKeys[i];
        UIView *sectionContainer = _sectionViews[key];
        CGFloat y = 0;

        NSArray *subset = [data subarrayWithRange:NSMakeRange(i * itemsPerSection,
            MIN(itemsPerSection, data.count - i * itemsPerSection))];

        for (NSDictionary *item in subset) {
            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);

            UILabel *body = [[UILabel alloc] initWithFrame:CGRectMake(12, 12, card.bounds.size.width - 24, 80)];
            body.text = item[@"title"];
            body.numberOfLines = 2;
            body.font = [UIFont systemFontOfSize:15];
            [card addSubview:body];
            [sectionContainer addSubview:card];
            y += 120;
        }

        sectionContainer.frame = CGRectMake(0, sectionContainer.frame.origin.y, self.view.bounds.size.width, y);
        sectionBottomY = CGRectGetMaxY(sectionContainer.frame) + 20;
    }

    _contentContainer.frame = CGRectMake(0, 0, _scrollView.bounds.size.width, sectionBottomY);
    _scrollView.contentSize = CGSizeMake(_scrollView.bounds.size.width, sectionBottomY);
}

@end
