<?php

use Drupal\Core\Form\FormStateInterface;
use Drupal\image\Entity\ImageStyle;
use Drupal\media\MediaInterface;

/**
 * Implements hook_theme().
 */
function kamihaya_cms_paragraph_type_theme() {
  return [
    'paragraph__accordion' => [
      'base hook' => 'paragraph',
    ],
    'paragraph__accordion_item' => [
      'base hook' => 'paragraph',
    ],
    'paragraph__divider' => [
      'base hook' => 'paragraph',
    ],
    'paragraph__image_link' => [
      'base hook' => 'paragraph',
    ],
    'paragraph__link_button' => [
      'base hook' => 'paragraph',
    ],
    'paragraph__modal_dialog' => [
      'base hook' => 'paragraph',
    ],
    'paragraph__drawer' => [
      'base hook' => 'paragraph',
    ],
    'paragraph__slider_item' => [
      'base hook' => 'paragraph',
    ],
    'paragraph__slider' => [
      'base hook' => 'paragraph',
    ],
    'paragraph__headings' => [
      'base hook' => 'paragraph',
    ],
    'paragraph__h2_title' => [
      'base hook' => 'paragraph',
    ],
    'paragraph__h3_title' => [
      'base hook' => 'paragraph',
    ],
    'paragraph__two_col_table' => [
      'base hook' => 'paragraph',
    ],
    'paragraph__two_col_table_row' => [
      'base hook' => 'paragraph',
    ],
    'paragraph__image' => [
      'base hook' => 'paragraph',
    ],
    'paragraph__video' => [
      'base hook' => 'paragraph',
    ],
    'paragraph__left_image_text' => [
      'base hook' => 'paragraph',
    ],
    'paragraph__right_image_text' => [
      'base hook' => 'paragraph',
    ],
    'paragraph__file_download' => [
      'base hook' => 'paragraph',
    ],
    'paragraph__border_box' => [
      'base hook' => 'paragraph',
    ],
    'paragraph__embed_tag' => [
      'base hook' => 'paragraph',
    ],
    'paragraph__background_image' => [
      'base hook' => 'paragraph',
    ],
  ];
}

/**
 * Implements hook_field_widget_single_element_WIDGET_TYPE_form_alter().
 */
function kamihaya_cms_paragraph_type_field_widget_single_element_layout_paragraphs_form_alter(
  array &$element,
  FormStateInterface $form_state,
  array $context) {
  $element['#attached']['library'][] = 'kamihaya_cms_paragraph_type/lpb_component_list';

  /** @var \Drupal\Core\Extension\ThemeHandlerInterface $thene_handler */
  $thene_handler = Drupal::service('theme_handler');
  if ($thene_handler->themeExists('kamihaya_digitalagency')) {
    $element['#attached']['library'][] = 'kamihaya_digitalagency/components';
  }
}

/**
 * Implements hook_preprocess_paragraph().
 */
function kamihaya_cms_paragraph_type_preprocess_paragraph(array &$variables) {
  $paragraph = $variables['paragraph'];
  if (strpos($paragraph->getType(), 'image') !== FALSE) {
    // Add image URL to the content.
    // This is used to generate the image URL for the paragraph.
    foreach ($variables['content'] as $key => $field) {
      if (!is_array($field) || empty($field['#field_type']) || ($field['#field_type'] !== 'image' && $field['#field_type'] !== 'entity_reference')) {
        continue;
      }
      if ($field['#field_type'] === 'image') {
        $item = $field[0]['#item'] ?? null;
        if (empty($item)) {
          continue;
        }
        // Get the file ID from the item.
        $fid = $item->get('target_id')->getValue();
        // Get the image style from the field.
        $image_style = $field[0]['#image_style'] ?? 'default';
      }
      if ($field['#field_type'] === 'entity_reference') {
        $entity = $field[0]['#entity'] ?? null;
        // Check if the entity is a media entity and has an image field.
        if (empty($entity) || !($entity instanceof MediaInterface) || $entity->bundle() !== 'image') {
          continue;
        }
        // Get the file ID from the media entity.
        $fid = $entity->get('field_media_image')->target_id;
        // Get the image style from the field.
        $image_style = $field[0]['#image_style'] ?? 'default';
      }
      if (empty($fid)) {
        continue;
      }
      /* @var \Drupal\file\FileInterface $file */
      $file = \Drupal::entityTypeManager()->getStorage('file')->load($fid);
      if (empty($file)) {
        continue;
      }

      // Get the file URI and generate the image style URL.
      $uri = $file->getFileUri();
      $style = ImageStyle::load($image_style);

      if (empty($style)) {
        $variables['content']["{$key}_url"] = $file->createFileUrl();
        continue;
      }
      // Generate the URL for the image style.
      $style->createDerivative($uri, $style->buildUri($uri));
      $style_url = $style->buildUrl($uri);
      $parsed_url = parse_url($style_url);
      $relative_path = $parsed_url['path'];
      $variables['content']["{$key}_url"] = $relative_path ?? $uri;
    }
  }

  if ($paragraph->bundle() === 'modal_dialog') {
    $variables['#attached']['drupalSettings']['modal_dialog']['default_open'] = $paragraph->get('field_default_open')->value;
    $variables['#attached']['drupalSettings']['modal_dialog']['cookie_name'] = $paragraph->get('field_cookie_name')->value;
    $variables['#attached']['drupalSettings']['modal_dialog']['one_time'] = $paragraph->get('field_one_time')->value;
  }
  if (in_array($paragraph->bundle(), ['h2_title', 'h3_title', 'h4_title']) && !empty($paragraph->get('field_anchor_link_id')->value)) {
    if (!empty($variables['content']['field_h2_title'][0])) {
      $variables['content']['field_h2_title'][0]['#attributes']['id'] = $paragraph->get('field_anchor_link_id')->value;
    }
    if (!empty($variables['content']['field_h3_title'][0])) {
      $variables['content']['field_h3_title'][0]['#attributes']['id'] = $paragraph->get('field_anchor_link_id')->value;
    }
    if (!empty($variables['content']['field_h4_title'][0])) {
      $variables['content']['field_h4_title'][0]['#attributes']['id'] = $paragraph->get('field_anchor_link_id')->value;
    }
  }
  if ($paragraph->bundle() === 'anchor_link' && !empty($paragraph->get('field_link_item')) && !empty($paragraph->get('field_link_item')->getValue())) {
    $variables['#attached']['library'][] = 'kamihaya_cms_paragraph_type/anchor-link-css';
    $link_items = $paragraph->get('field_link_item')->getValue();
    if (empty($variables['#attributes']['class'])) {
      $variables['#attributes']['class'] = [];
    }
    $variables['attributes']['class'][] = 'links-' . count($link_items);
  }
}
