<?php

declare(strict_types=1);

namespace Drupal\layout_builder_browser_library\Controller;

use Drupal\Component\Utility\Xss;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\File\FileUrlGeneratorInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Url;
use Drupal\layout_builder_browser\Entity\LayoutBuilderBrowserBlock;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Controller class responsible for managing the browser block library.
 */
class LibraryController extends ControllerBase {

  public const CONTENT_WEIGHT = 20;

  public const IMAGE_WEIGHT = 10;

  /**
   * The file URL generator service.
   *
   * @var \Drupal\Core\File\FileUrlGeneratorInterface
   */
  protected FileUrlGeneratorInterface $fileUrlGenerator;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container): static {
    $instance = parent::create($container);
    $instance->fileUrlGenerator = $container->get('file_url_generator');
    return $instance;
  }

  /**
   * Display a library of blocks presents in Layout Builder Browser.
   */
  public function library(): array {
    $block_categories = [];
    /** @var \Drupal\layout_builder_browser\Entity\LayoutBuilderBrowserBlockCategory[] $blockcats */
    $blockcats = $this->entityTypeManager()
      ->getStorage('layout_builder_browser_blockcat')
      ->loadByProperties(['status' => TRUE]);
    \uasort($blockcats, ['Drupal\Core\Config\Entity\ConfigEntityBase', 'sort']);

    foreach ($blockcats as $blockcat) {
      /** @var \Drupal\layout_builder_browser\Entity\LayoutBuilderBrowserBlock[] $blocks */
      $blocks = $this->entityTypeManager()
        ->getStorage('layout_builder_browser_block')
        ->loadByProperties([
          'category' => $blockcat->id,
          'status' => TRUE,
        ]);
      \uasort($blocks, ['Drupal\Core\Config\Entity\ConfigEntityBase', 'sort']);

      if (empty($blocks)) {
        continue;
      }
      $label = $blockcat->label();
      $label = $label instanceof TranslatableMarkup ? $label->__toString() : $label;
      $block_categories[$blockcat->id()] = [
        'title' => [
          '#type' => 'html_tag',
          '#tag' => 'h3',
          '#value' => Xss::filterAdmin($label ?? ''),
        ],
        'items' => [
          '#type' => 'container',
          '#attributes' => [
            'class' => [
              'card-list',
              'card-list--four-cols',
            ],
          ],
        ],
      ];

      foreach ($blocks as $block) {
        $block_categories[$blockcat->id()]['items'][] = $this->getBlockLibraryBlock($block);
      }
    }

    $build = [
      'description' => [
        '#markup' => '<p>' . $this->t('Below, you will find the list of all the components that can be used to compose pages.') . '</p>',
      ],
    ];
    $build['block_categories'] = $block_categories;
    return $build;
  }

  /**
   * Gets a render array of block.
   *
   * @param \Drupal\layout_builder_browser\Entity\LayoutBuilderBrowserBlock $block
   *   The layout builder browser block.
   *
   * @return array
   *   The block render array.
   */
  protected function getBlockLibraryBlock(LayoutBuilderBrowserBlock $block): array {
    $layout_builder_browser_library = $block->getThirdPartySettings('layout_builder_browser_library');
    $render = [
      '#type' => 'container',
      '#attributes' => [
        'class' => [
          'card',
          'card-list__item',
        ],
      ],
      'content' => [
        '#type' => 'container',
        '#attributes' => [
          'class' => [
            'card__content-wrapper',
          ],
        ],
        '#weight' => static::CONTENT_WEIGHT,
      ],
    ];

    if (isset($layout_builder_browser_library['library_image_path']) && \trim($layout_builder_browser_library['library_image_path']) != '') {
      $url = $this->fileUrlGenerator->transformRelative($this->fileUrlGenerator->generateString($layout_builder_browser_library['library_image_path']));
      $render['image'] = [
        '#type' => 'link',
        '#title' => [
          '#theme' => 'image',
          '#uri' => $layout_builder_browser_library['library_image_path'],
          '#alt' => $layout_builder_browser_library['library_image_alt'] ?? '',
        ],
        '#url' => Url::fromUserInput($url),
        '#weight' => static::IMAGE_WEIGHT,
      ];
    }

    $label = $block->label();
    $label = $label instanceof TranslatableMarkup ? $label->__toString() : $label;
    $render['content']['label'] = [
      '#markup' => '<h4>' . Xss::filterAdmin($label ?? '') . '</h4>',
    ];

    if (!empty($layout_builder_browser_library['description'])) {
      $render['content']['description'] = [
        '#markup' => '<p>' . Xss::filterAdmin($layout_builder_browser_library['description']) . '</p>',
      ];
    }

    return $render;
  }

}
