// Copyright 2025 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#import "ios/chrome/browser/content_suggestions/ui/cells/content_suggestions_action_tile_view.h"

#import <UIKit/UIKit.h>

#import "ios/chrome/browser/content_suggestions/ui/cells/content_suggestions_action_item.h"
#import "ios/chrome/browser/content_suggestions/ui/cells/content_suggestions_cells_constants.h"
#import "ios/chrome/browser/ntp/ui_bundled/new_tab_page_color_palette.h"
#import "ios/chrome/browser/ntp/ui_bundled/new_tab_page_image_background_trait.h"
#import "ios/chrome/browser/ntp/ui_bundled/new_tab_page_trait.h"
#import "ios/chrome/browser/shared/public/features/features.h"
#import "ios/chrome/browser/shared/ui/symbols/symbols.h"
#import "ios/chrome/browser/shared/ui/util/uikit_ui_util.h"
#import "ios/chrome/common/ui/colors/semantic_color_names.h"
#import "ios/chrome/common/ui/util/constraints_ui_util.h"
#import "ios/chrome/common/ui/util/dynamic_type_util.h"

namespace {

const CGFloat kCountWidth = 20;
const CGFloat kCountBorderWidth = 24;

}  // namespace

@implementation ContentSuggestionsActionTileView
@synthesize countLabel = _countLabel;

- (instancetype)initWithFrame:(CGRect)frame {
  self = [super initWithFrame:frame
                     tileType:ContentSuggestionsTileType::kAction];
  if (self) {
    _iconView = [[UIImageView alloc] initWithFrame:self.bounds];
    _iconView.translatesAutoresizingMaskIntoConstraints = NO;

    [self.imageContainerView addSubview:_iconView];
    AddSameConstraints(self.imageContainerView, _iconView);
    [NSLayoutConstraint activateConstraints:@[
      [_iconView.widthAnchor
          constraintEqualToConstant:kMagicStackImageContainerWidth],
      [_iconView.heightAnchor constraintEqualToAnchor:_iconView.widthAnchor],
    ]];

    [self registerViewForTraitChanges];
    [self applyBackgroundTheme];
  }
  return self;
}

- (instancetype)initWithConfiguration:(ContentSuggestionsActionItem*)config {
  self = [self initWithFrame:CGRectZero];
  if (self) {
    self.accessibilityCustomActions = nil;
    self.isAccessibilityElement = YES;
    _iconView.contentMode = UIViewContentModeCenter;

    [self updateConfiguration:config];
    [self registerViewForTraitChanges];
  }
  return self;
}

- (void)updateConfiguration:(ContentSuggestionsActionItem*)config {
  _config = config;
  self.titleLabel.text = config.title;
  self.titleLabel.font = [self titleLabelFont];
  self.accessibilityTraits =
      UIAccessibilityTraitButton | config.accessibilityTraits;
  self.accessibilityLabel = config.accessibilityLabel.length
                                ? config.accessibilityLabel
                                : config.title;
  // The accessibilityUserInputLabel should just be the title, with nothing
  // extra from the accessibilityLabel.
  self.accessibilityUserInputLabels = @[ config.title ];
  self.iconView.image = config.icon;
  self.countContainer.hidden = config.count == 0;
  if (config.count > 0) {
    self.countLabel.text = [@(config.count) stringValue];
  }
  self.alpha = config.disabled ? 0.3 : 1.0;
}

- (void)applyBackgroundTheme {
  BOOL hasImageBackground =
      [self.traitCollection boolForNewTabPageImageBackgroundTrait];
  NewTabPageColorPalette* colorPalette =
      [self.traitCollection objectForNewTabPageTrait];

  if (hasImageBackground) {
    self.imageBackgroundView.tintColor = [UIColor colorNamed:kGrey100Color];
    self.iconView.tintColor = [UIColor colorNamed:kTextPrimaryColor];
    // Don't create count label if it's not already created.
    _countLabel.backgroundColor = [UIColor colorNamed:kBlueColor];
  } else if (colorPalette) {
    self.imageBackgroundView.tintColor = colorPalette.tertiaryColor;
    self.iconView.tintColor = colorPalette.tintColor;
    // Don't create count label if it's not already created.
    _countLabel.backgroundColor = colorPalette.tintColor;
  } else {
    self.imageBackgroundView.tintColor = [UIColor colorNamed:kBlueHaloColor];
    self.iconView.tintColor = nil;
    // Don't create count label if it's not already created.
    _countLabel.backgroundColor = [UIColor colorNamed:kBlueColor];
  }
}

- (UILabel*)countLabel {
  if (!_countLabel) {
    _countContainer = [[UIView alloc] init];
    _countContainer.backgroundColor = [UIColor colorNamed:kBackgroundColor];
    // Unfortunately, simply setting a CALayer borderWidth and borderColor
    // on `_countContainer`, and setting a background color on `_countLabel`
    // will result in the inner color bleeeding thru to the outside.
    _countContainer.layer.cornerRadius = kCountBorderWidth / 2;
    _countContainer.layer.masksToBounds = YES;

    _countLabel = [[UILabel alloc] init];
    _countLabel.layer.cornerRadius = kCountWidth / 2;
    _countLabel.layer.masksToBounds = YES;
    _countLabel.textColor = [UIColor colorNamed:kSolidButtonTextColor];
    _countLabel.textAlignment = NSTextAlignmentCenter;

    NewTabPageColorPalette* colorPalette =
        [self.traitCollection objectForNewTabPageTrait];
    // Only color the count label if there's no image background.
    if (![self.traitCollection boolForNewTabPageImageBackgroundTrait] &&
        colorPalette) {
      _countLabel.backgroundColor = colorPalette.tintColor;
    } else {
      _countLabel.backgroundColor = [UIColor colorNamed:kBlueColor];
    }

    _countContainer.translatesAutoresizingMaskIntoConstraints = NO;
    _countLabel.translatesAutoresizingMaskIntoConstraints = NO;

    [self addSubview:self.countContainer];
    [self.countContainer addSubview:self.countLabel];

    [NSLayoutConstraint activateConstraints:@[
      [_countContainer.widthAnchor constraintEqualToConstant:kCountBorderWidth],
      [_countContainer.heightAnchor
          constraintEqualToAnchor:_countContainer.widthAnchor],
      [_countContainer.topAnchor constraintEqualToAnchor:self.topAnchor],
      [_countContainer.centerXAnchor
          constraintEqualToAnchor:self.imageContainerView.trailingAnchor],
      [_countLabel.widthAnchor constraintEqualToConstant:kCountWidth],
      [_countLabel.heightAnchor
          constraintEqualToAnchor:_countLabel.widthAnchor],
    ]];
    const CGFloat kCaptionFontSize = 12.0;
    const UIFontWeight kCaptionFontWeight = UIFontWeightRegular;
    _countLabel.font = [UIFont systemFontOfSize:kCaptionFontSize
                                         weight:kCaptionFontWeight];
    AddSameCenterConstraints(_countLabel, _countContainer);
  }
  return _countLabel;
}

#pragma mark - Private

- (UIFont*)titleLabelFont {
  return PreferredFontForTextStyleWithMaxCategory(
      UIFontTextStyleCaption2,
      self.traitCollection.preferredContentSizeCategory,
      UIContentSizeCategoryAccessibilityLarge);
}

// Registers a list of UITraits to observe and invokes the
// `updateTitleLabelFontOnTraitChange` function whenever one of the observed
// trait's values change.
- (void)registerViewForTraitChanges {
  [self registerForTraitChanges:@[ UITraitPreferredContentSizeCategory.class ]
                     withAction:@selector(updateTitleLabelFontOnTraitChange)];
  [self registerForTraitChanges:
            @[ NewTabPageTrait.class, NewTabPageImageBackgroundTrait.class ]
                     withAction:@selector(applyBackgroundTheme)];
}

// Update the `titleLabel` font when the device's content size changes.
- (void)updateTitleLabelFontOnTraitChange {
  self.titleLabel.font = [self titleLabelFont];
}

@end
