<?php

namespace Drupal\straker_translate\Plugin\StrakerTranslateFormComponent\Field;

use Drupal\Core\Entity\EntityInterface;
use Drupal\straker_translate\FormComponent\StrakerTranslateFormComponentFieldBase;

/**
 * Defines a Straker Translate form-field plugin for an entity's Project Status.
 *
 * @StrakerTranslateFormComponentField(
 *   id = "project_status",
 *   title = @Translation("Project Status"),
 *   weight = 350,
 *   form_ids = {
 *     "straker_translate_management",
 *     "straker_translate_entity_management",
 *     "straker_translate_job_content_entities_management"
 *   }
 * )
 */
class ProjectStatus extends StrakerTranslateFormComponentFieldBase {

  /**
   * {@inheritdoc}
   */
  public function getHeader($entity_type_id = NULL) {
    return $this->t('Project Status');
  }

  /**
   * {@inheritdoc}
   */
  public function getData(EntityInterface $entity) {
    // Get the Straker Translate translation service to check project status
    $translation_service = \Drupal::service('straker_translate.content_translation');

    // Get the document ID for this entity
    $document_id = $translation_service->getDocumentId($entity);
    $source_status = $translation_service->getSourceStatus($entity);
    if ($document_id) {
      // Return a human-readable status with dropdown
      switch ($source_status) {
        case 'CURRENT':
          return $this->buildStatusWithDropdown('source-current', $this->t('Verify Translated'), $this->t('Source Translated'), $entity, $source_status);
        case 'READY':
          return $this->buildStatusWithDropdown('source-ready', $this->t('Check Status'), $this->t('Project Created, Check Status Pending'), $entity, $source_status);
        case 'PROCESSING':
          return $this->buildStatusWithDropdown('source-processing', $this->t('In Progress'), $this->t('Project created, Translation in progress'), $entity, $source_status);
        case 'IMPORTING':
          return $this->buildStatusWithDropdown('source-importing', $this->t('Importing'), $this->t('Token payment pending'), $entity, $source_status);
        case 'PENDING':
          return $this->buildStatusWithDropdown('target-pending', $this->t('Pending'), $this->t('Translation requested but not started yet'), $entity, $source_status);
        case 'REQUEST':
          return $this->buildStatusWithDropdown('source-request', $this->t('Not Started'), $this->t('Upload'), $entity, $source_status);
        case 'EDITED':
          $tooltip = $document_id ?
            $this->t('Re-upload (content has changed since last upload)') :
            $this->t('Upload');
          return $this->buildStatusWithDropdown('source-edited', $this->t('Document Edited'), $tooltip, $entity, $source_status);
        case 'ERROR':
          return $this->buildStatusWithDropdown('source-error', $this->t('Error'), $this->t('Error'), $entity, $source_status);
        case 'CANCELLED':
          return $this->buildStatusWithDropdown('source-cancelled', $this->t('Cancelled'), $this->t('Cancelled by user'), $entity, $source_status);
        case 'DISABLED':
          return $this->buildStatusWithDropdown('source-disabled', $this->t('Disabled'), $this->t('Disabled, cannot request translation'), $entity, $source_status);
        case 'DELETED':
          return $this->buildStatusWithDropdown('source-deleted', $this->t('Deleted'), $this->t('This document was deleted in Verify. Re-upload to translate.'), $entity, $source_status);
        case 'ARCHIVED':
          return $this->buildStatusWithDropdown('source-archived', $this->t('Archived'), $this->t('This document was archived in Verify. Re-upload to translate.'), $entity, $source_status);
        case 'NONE':
          return $this->buildStatusWithDropdown('source-none', $this->t('No Status'), $this->t('No status available'), $entity, $source_status);
        default:
          return $this->buildStatusWithDropdown('source-none', $this->t('Unknown'), $this->t('Unknown status'), $entity, $source_status);
      }
    }

    // No document ID means not uploaded to Verify yet
    return $this->buildStatusWithDropdown('source-request', $this->t('Not Started'), $this->t('Upload to start translation project'), $entity, $source_status);
  }

  /**
   * Build a status pill with dropdown functionality.
   */
  protected function buildStatusWithDropdown($css_class, $status_text, $tooltip, EntityInterface $entity, $status) {
    $actions = $this->getProjectStatusActions($entity, $status);
    $dropdown_id = 'project-status-' . $entity->getEntityTypeId() . '-' . $entity->id();

    $dropdown_html = '';
    if (!empty($actions)) {
      $dropdown_html = '<span class="project-status-dropdown-toggle"></span>';
      $dropdown_html .= '<ul class="project-status-dropdown-menu" id="' . $dropdown_id . '">';
      foreach ($actions as $action) {
        $target = $action['new_window'] ? ' target="_blank"' : '';
        $dropdown_html .= '<li><a href="' . $action['url']->toString() . '"' . $target . '>' . $action['title'] . '</a></li>';
      }
      $dropdown_html .= '</ul>';
    }

    return [
      'data' => [
        '#markup' => '<div class="project-status-wrapper"><span class="language-icon ' . $css_class . '" title="' . $tooltip . '">' . $status_text . $dropdown_html . '</span></div>',
        '#attached' => [
          'library' => ['straker_translate/project_status_dropdown'],
        ],
      ],
    ];
  }

  /**
   * Get actions available for the project status.
   */
  protected function getProjectStatusActions(EntityInterface $entity, $status) {
    $actions = [];
    $translation_service = \Drupal::service('straker_translate.content_translation');
    $query_options = ['query' => ['destination' => \Drupal::request()->getRequestUri()]];

    switch ($status) {
      case 'IMPORTING':
        if ($doc_id = $translation_service->getDocumentId($entity)) {
          $actions[] = [
            'title' => $this->t('Confirm document'),
            'url' => \Drupal\Core\Url::fromRoute('straker_translate.entity.confirm', [
              'doc_id' => $doc_id,
            ], $query_options),
            'new_window' => FALSE,
          ];
        }
        break;

      case 'READY':
      case 'PROCESSING':
      case 'ERROR':
      case 'CURRENT':
        if ($doc_id = $translation_service->getDocumentId($entity)) {
          if ($status != 'CURRENT') {
            $actions[] = [
              'title' => $this->t('Check translation status'),
              'url' => \Drupal\Core\Url::fromRoute('straker_translate.entity.check_upload', [
                'doc_id' => $doc_id,
              ], $query_options),
              'new_window' => FALSE,
            ];
          }
          $actions[] = [
            'title' => $this->t('Re-upload document'),
            'url' => \Drupal\Core\Url::fromRoute('straker_translate.entity.update', [
              'entity_type' => $entity->getEntityTypeId(),
              'entity_id' => $entity->id(),
            ], $query_options),
            'new_window' => FALSE,
          ];
        }
        break;

      case 'REQUEST':
      case 'EDITED':
      case 'UNTRACKED':
      case 'CANCELLED':
      case 'ARCHIVED':
      case 'DELETED':
        if ($doc_id = $translation_service->getDocumentId($entity)) {
          $actions[] = [
            'title' => $this->t('Update document'),
            'url' => \Drupal\Core\Url::fromRoute('straker_translate.entity.update', [
              'entity_type' => $entity->getEntityTypeId(),
              'entity_id' => $entity->id(),
            ], $query_options),
            'new_window' => FALSE,
          ];
        }
        else {
          $actions[] = [
            'title' => $this->t('Upload document'),
            'url' => \Drupal\Core\Url::fromRoute('straker_translate.entity.upload', [
              'entity_type' => $entity->getEntityTypeId(),
              'entity_id' => $entity->id(),
            ], $query_options),
            'new_window' => FALSE,
          ];
        }
        break;
    }

    // Always add view option last
    if ($entity->hasLinkTemplate('canonical')) {
      $actions[] = [
        'title' => $this->t('View'),
        'url' => $entity->toUrl(),
        'new_window' => FALSE,
      ];
    }

    return $actions;
  }

}
