<?php

namespace Drupal\mymodule\Plugin\Block;

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\AlertCommand;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\mymodule\Form\TestForm;

/**
 * Provides
 *
 * @Block(
 *   id = "mymodule_products_suggest",
 *   admin_label = @Translation("Products"),
 *   context_definitions = {
 *     "node" = @ContextDefinition("entity:node", required = FALSE, label = @Translation("Node")),
 *   }
 * )
 */

class ProductsSuggest extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $node = $this->getContextValue('node');
    $node_id = $node->id();

    $products = \Drupal::entityTypeManager()
      ->getStorage('commerce_product')
      ->loadByProperties(['field_node' => $node_id]);

    foreach ($products as $product) {
      $test = \Drupal::entityTypeManager()
        ->getViewBuilder('commerce_product')
        ->view($product, 'cart');
      $label = $product->label();
      $variations = $product->getVariations();

      unset($options);
      foreach ($variations as $variation) {
        if (empty($price)) {
          $price = $variation->getPrice();
        }
        $attribute = $variation->getAttributeValue('attribute_size');
        $options[] = $attribute->label();
      }

      $build[$label]['card'] = [
        '#type' => 'container',
        '#attributes' => [
          'class' => ['card']
        ]
      ];

      $build[$label]['card']['title'] = [
        '#type' => 'html_tag',
        '#tag' => 'h2',
        '#value' => $label,
        '#attributes' => [
          'class' => ['card_title']
        ]
      ];

      $build[$label]['card']['price'] = [
        '#type' => 'html_tag',
        '#tag' => 'p',
        '#value' => $price,
        '#attributes' => [
          'class' => ['card_price']
        ]
      ];

      $build[$label]['card']['form'] = [
        '#type' => 'form',
        '#attributes' => [
          'action' => '#'
        ]
      ];

      $build[$label]['card']['form']['size'] = [
        '#type' => 'select',
        '#title' => 'Size',
        '#options' => $options,

      ];

      $build[$label]['card']['form']['button'] = [
        '#type' => 'submit',
        '#value' => 'Добавить в корзину',
        '#ajax' => [
          'callback' => '::changePrice',
          'event' => 'click',
        ],
      ];
    }

    empty($products) ? $build = ['#markup' => 'Ничего не найдено'] : '';
    return $build;
  }

  public function changePrice() {
    $response = new AjaxResponse();
    $response->addCommand(new AlertCommand('Hello'));
    return $response;
  }
}
