<?php

namespace Drupal\straker_translate\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StreamWrapper\LocalStream;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\straker_translate\StrakerTranslateInterfaceTranslationServiceInterface;
use Drupal\straker_translate\StrakerTranslateSetupTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Extension\ThemeHandlerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;

/**
 * Class StrakerTranslateInterfaceTranslationForm.
 *
 * Provides a translation interface form.
 *
 * @package Drupal\straker_translate\Form
 */
class StrakerTranslateInterfaceTranslationForm extends FormBase {

  use StringTranslationTrait;

  use StrakerTranslateSetupTrait;

  /**
   * The language manager.
   *
   * @var \Drupal\language\ConfigurableLanguageManagerInterface
   */
  protected $languageManager;

  /**
   * The module handler.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * The theme handler.
   *
   * @var \Drupal\Core\Extension\ThemeHandlerInterface
   */
  protected $themeHandler;

  /**
   * The Straker Translate interface translation service.
   *
   * @var \Drupal\straker_translate\StrakerTranslateInterfaceTranslationServiceInterface
   */
  protected $straker_translateInterfaceTranslation;

  /**
   * Constructs a new StrakerTranslateInterfaceTranslationForm object.
   *
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
   *   The language manager service.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler.
   * @param \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler
   *   The theme handler.
   * @param \Drupal\straker_translate\StrakerTranslateInterfaceTranslationServiceInterface $straker_translate_interface_translation
   *   The Straker Translate interface translation service.
   */
  public function __construct(LanguageManagerInterface $language_manager, ModuleHandlerInterface $module_handler, ThemeHandlerInterface $theme_handler, StrakerTranslateInterfaceTranslationServiceInterface $straker_translate_interface_translation) {
    $this->languageManager = $language_manager;
    $this->moduleHandler = $module_handler;
    $this->themeHandler = $theme_handler;
    $this->straker_translateInterfaceTranslation = $straker_translate_interface_translation;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('language_manager'),
      $container->get('module_handler'),
      $container->get('theme_handler'),
      $container->get('straker_translate.interface_translation')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'straker_translate_interface_translation_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    if ($redirect = $this->checkSetup()) {
      return $redirect;
    }
    if (!$this->moduleHandler->moduleExists('potx')) {
      $form['missing_potx'] = [
        '#type' => 'markup',
        '#markup' => $this->t('The <a href=":potx">potx</a> module is required for interface translation with Straker', [':potx' => 'https://www.drupal.org/project/potx']),
      ];
      return $form;
    }

    $form['theme_vtab'] = [
      '#type' => 'vertical_tabs',
      '#title' => $this->t('Themes'),
    ];
    $form['module_vtab'] = [
      '#type' => 'vertical_tabs',
      '#title' => $this->t('Modules'),
    ];
    $form['profile_vtab'] = [
      '#type' => 'vertical_tabs',
      '#title' => $this->t('Profiles'),
    ];

    $form['theme']['custom'] = [
      '#type' => 'details',
      '#title' => $this->t('Custom themes'),
      '#open' => TRUE,
      '#group' => 'theme_vtab',
    ];
    $form['theme']['contrib'] = [
      '#type' => 'details',
      '#title' => $this->t('Contributed themes'),
      '#open' => FALSE,
      '#group' => 'theme_vtab',
    ];
    $form['theme']['core'] = [
      '#type' => 'details',
      '#title' => $this->t('Drupal Core themes'),
      '#open' => FALSE,
      '#group' => 'theme_vtab',
    ];

    $form['module']['custom'] = [
      '#type' => 'details',
      '#title' => $this->t('Custom modules'),
      '#open' => TRUE,
      '#group' => 'module_vtab',
    ];
    $form['module']['contrib'] = [
      '#type' => 'details',
      '#title' => $this->t('Contributed modules'),
      '#open' => FALSE,
      '#group' => 'module_vtab',
    ];
    $form['module']['core'] = [
      '#type' => 'details',
      '#title' => $this->t('Drupal Core modules'),
      '#open' => FALSE,
      '#group' => 'module_vtab',
    ];

    $form['profile']['custom'] = [
      '#type' => 'details',
      '#title' => $this->t('Custom profiles'),
      '#open' => TRUE,
      '#group' => 'profile_vtab',
    ];
    $form['profile']['contrib'] = [
      '#type' => 'details',
      '#title' => $this->t('Contributed profiles'),
      '#open' => FALSE,
      '#group' => 'profile_vtab',
    ];
    $form['profile']['core'] = [
      '#type' => 'details',
      '#title' => $this->t('Drupal Core profiles'),
      '#open' => FALSE,
      '#group' => 'profile_vtab',
    ];

    $tables = ['core', 'custom', 'contrib'];
    $componentTypes = ['theme', 'module', 'profile'];
    foreach ($componentTypes as $componentType) {
      foreach ($tables as $table) {
        $form[$componentType][$table]['table'] = [
          '#type' => 'table',
          '#header' => [
            'label' => $this->t('Label'),
            'machine_name' => $this->t('Machine name'),
            'source' => $this->t('Source'),
            'project_status' => $this->t('Project Status'),
            'translations' => $this->t('Translations'),
            'target_status' => $this->t('Target Status'),
          ],
          '#empty' => $this->t('No %component to translate in this category', ['%component' => $componentType]),
          '#rows' => [],
        ];
      }
    }

    $themes = $this->themeHandler->listInfo();
    foreach ($themes as $theme => $themeInfo) {
      $component = $themeInfo->getPath();

      $targetStatuses = $this->straker_translateInterfaceTranslation->getTargetStatuses($component);
      unset($targetStatuses['EN']);
      $sourceStatus = $this->straker_translateInterfaceTranslation->getSourceStatus($component);

      $row = [
        'label' => $themeInfo->info['name'],
        'machine_name' => $themeInfo->getName(),
        'source' => [
          'data' => [
            '#markup' => $this->languageManager->getLanguage('en')->getName(),
          ],
        ],
        'project_status' => $this->getProjectStatusText($sourceStatus, $component),
        'translations' => [
          'data' => [
            '#type' => 'markup',
            '#markup' => $this->getTranslationsContent($component),
          ],
        ],
        'target_status' => [
          'data' => [
            '#type' => 'markup',
            '#markup' => $this->getTargetStatusContent($component),
            '#attached' => [
              'library' => [
                'straker_translate/base',
                'straker_translate/target_status_dropdown',
                'straker_translate/straker_translate',
                'straker_translate/straker_translate.target_actions',
              ],
            ],
          ],
        ],
      ];

      [$path_part1, $path_part2] = explode('/', $themeInfo->getPath());
      if ($path_part1 == 'core') {
        $form['theme']['core']['table']['#rows'][] = $row;
      }
      elseif ($path_part1 == 'contrib' || $path_part2 == 'contrib') {
        $form['theme']['contrib']['table']['#rows'][] = $row;
      }
      elseif ($path_part1 == 'custom' || $path_part2 == 'custom') {
        $form['theme']['custom']['table']['#rows'][] = $row;
      }
      else {
        $form['theme']['custom']['table']['#rows'][] = $row;
      }
    }
    if ($this->moduleHandler->moduleExists('cohesion')) {
      $template_location = COHESION_TEMPLATE_PATH;
      // Get real path to templates and extract relative path for interface translation.
      if ($wrapper = \Drupal::service('stream_wrapper_manager')
        ->getViaUri($template_location)) {
        if ($wrapper instanceof LocalStream) {
          $template_path = $wrapper->getDirectoryPath() . '/cohesion/templates';
        }
      }
      // This is a fake component.
      $component = $template_path ?? NULL;
      $sourceStatus = $this->straker_translateInterfaceTranslation->getSourceStatus($component);

      $row = [
        'label' => 'Cohesion templates',
        'machine_name' => 'cohesion_templates',
        'source' => [
          'data' => [
            '#markup' => $this->languageManager->getLanguage('en')->getName(),
          ],
        ],
        'project_status' => $this->getProjectStatusText($sourceStatus, $component),
        'translations' => [
          'data' => [
            '#type' => 'markup',
            '#markup' => $this->getTranslationsContent($component),
          ],
        ],
        'target_status' => [
          'data' => [
            '#type' => 'markup',
            '#markup' => $this->getTargetStatusContent($component),
            '#attached' => [
              'library' => [
                'straker_translate/base',
                'straker_translate/target_status_dropdown',
                'straker_translate/straker_translate',
                'straker_translate/straker_translate.target_actions',
              ],
            ],
          ],
        ],
      ];
      $form['theme']['custom']['table']['#rows'][] = $row;
    }

    $modules = $this->moduleHandler->getModuleList();
    foreach ($modules as $module => $moduleInfo) {
      $component = $moduleInfo->getPath();
      $type = $moduleInfo->getType();
      // We don't inject this service as its interface is not considered "stable".
      /** @var \Drupal\Core\Extension\ModuleExtensionList $moduleExtensionList */
      $moduleExtensionList = \Drupal::service('extension.list.module');
      $userFriendlyName = $moduleExtensionList->getName($module);
      $sourceStatus = $this->straker_translateInterfaceTranslation->getSourceStatus($component);

      $row = [
        'label' => $userFriendlyName,
        'machine_name' => $moduleInfo->getName(),
        'source' => [
          'data' => [
            '#markup' => $this->languageManager->getLanguage('en')->getName(),
          ],
        ],
        'project_status' => $this->getProjectStatusText($sourceStatus, $component),
        'translations' => [
          'data' => [
            '#type' => 'markup',
            '#markup' => $this->getTranslationsContent($component),
          ],
        ],
        'target_status' => [
          'data' => [
            '#type' => 'markup',
            '#markup' => $this->getTargetStatusContent($component),
            '#attached' => [
              'library' => [
                'straker_translate/base',
                'straker_translate/target_status_dropdown',
                'straker_translate/straker_translate',
                'straker_translate/straker_translate.target_actions',
              ],
            ],
          ],
        ],
      ];

      [$path_part1, $path_part2] = explode('/', $moduleInfo->getPath());
      if ($path_part1 == 'core') {
        $form[$type]['core']['table']['#rows'][] = $row;
      }
      elseif ($path_part1 == 'contrib' || $path_part2 == 'contrib') {
        $form[$type]['contrib']['table']['#rows'][] = $row;
      }
      elseif ($path_part1 == 'custom' || $path_part2 == 'custom') {
        $form[$type]['custom']['table']['#rows'][] = $row;
      }
      else {
        $form[$type]['custom']['table']['#rows'][] = $row;
      }
    }

    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['clear_metadata'] = [
      '#type' => 'submit',
      '#value' => $this->t('Clear Straker interface translation metadata'),
      '#button_type' => 'danger',
      '#submit' => [[$this, 'clearInterfaceMetadata']],
    ];

    // Ensure all CSS libraries are attached at form level
    $form['#attached']['library'][] = 'straker_translate/base';
    $form['#attached']['library'][] = 'straker_translate/project_status_dropdown';
    $form['#attached']['library'][] = 'straker_translate/target_status_dropdown';

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function clearInterfaceMetadata(array &$form, FormStateInterface $form_state) {
    // Redirect to the confirmation form.
    $form_state->setRedirect('straker_translate.manage_interface_translation.clear_metadata');
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Do nothing for now, there's no form actually.
  }

  /**
   * Get readable project status text from source status.
   */
  protected function getProjectStatusText($source_status, $component = null) {
    $project_status = '';
    $project_css_class = '';
    $project_status_tooltip = '';

    switch ($source_status) {
      case 'CURRENT':
        $project_status = $this->t('Verify Translated');
        $project_css_class = 'source-current';
        $project_status_tooltip = $this->t('Source Translated');
        break;
      case 'READY':
        $project_status = $this->t('Check Status');
        $project_css_class = 'source-ready';
        $project_status_tooltip = $this->t('Project Created, Check Status Pending');
        break;
      case 'PROCESSING':
        $project_status = $this->t('In Progress');
        $project_css_class = 'source-processing';
        $project_status_tooltip = $this->t('Project created, Translation in progress');
        break;
      case 'IMPORTING':
        $project_status = $this->t('Importing');
        $project_css_class = 'source-importing';
        $project_status_tooltip = $this->t('Token payment pending');
        break;
      case 'PENDING':
        $project_status = $this->t('Pending');
        $project_css_class = 'target-pending';
        $project_status_tooltip = $this->t('Translation requested but not started yet');
        break;
      case 'REQUEST':
      case 'UNTRACKED':
        $project_status = $this->t('Not Started');
        $project_css_class = 'source-request';
        $project_status_tooltip = $this->t('Upload to start translation project');
        break;
      case 'EDITED':
        $project_status = $this->t('Document Edited');
        $project_css_class = 'source-edited';
        $project_status_tooltip = $this->t('Re-upload (content has changed since last upload)');
        break;
      case 'ERROR':
        $project_status = $this->t('Error');
        $project_css_class = 'source-error';
        $project_status_tooltip = $this->t('Error');
        break;
      case 'CANCELLED':
        $project_status = $this->t('Cancelled');
        $project_css_class = 'source-cancelled';
        $project_status_tooltip = $this->t('Cancelled by user');
        break;
      case 'DISABLED':
        $project_status = $this->t('Disabled');
        $project_css_class = 'source-disabled';
        $project_status_tooltip = $this->t('Disabled, cannot request translation');
        break;
      case 'DELETED':
        $project_status = $this->t('Deleted');
        $project_css_class = 'source-deleted';
        $project_status_tooltip = $this->t('This document was deleted in Verify. Re-upload to translate.');
        break;
      case 'ARCHIVED':
        $project_status = $this->t('Archived');
        $project_css_class = 'source-archived';
        $project_status_tooltip = $this->t('This document was archived in Verify. Re-upload to translate.');
        break;
      case 'NONE':
        $project_status = $this->t('No Status');
        $project_css_class = 'source-none';
        $project_status_tooltip = $this->t('No status available');
        break;
      default:
        $project_status = $this->t('Unknown');
        $project_css_class = 'source-none';
        $project_status_tooltip = $this->t('Unknown status');
        break;
    }

    // Get dropdown actions for this status
    $project_actions = $this->getProjectStatusActions($source_status, $component);

    // Build dropdown HTML
    $dropdown_html = '';
    $wrapper_class = 'project-status-wrapper';
    $dropdown_id = 'project-status-interface-' . md5($component ?? 'unknown');

    if (!empty($project_actions)) {
      $wrapper_class .= ' has-dropdown';
      $dropdown_html = '<span class="project-status-dropdown-toggle"></span>';
      $dropdown_html .= '<ul class="project-status-dropdown-menu" id="' . $dropdown_id . '">';
      foreach ($project_actions as $action) {
        $target = isset($action['new_window']) && $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="' . $wrapper_class . '"><span class="language-icon ' . $project_css_class . '" title="' . $project_status_tooltip . '">' . $project_status . $dropdown_html . '</span></div>',
        '#attached' => [
          'library' => ['straker_translate/base', 'straker_translate/project_status_dropdown'],
        ],
      ],
    ];
  }

  /**
   * Get actions available for the project status dropdown.
   */
  protected function getProjectStatusActions($source_status, $component) {
    $actions = [];
    $query_options = ['query' => ['destination' => \Drupal::request()->getRequestUri()]];
    $document_id = $this->straker_translateInterfaceTranslation->getDocumentId($component);

    switch ($source_status) {
      case 'READY':
      case 'PROCESSING':
      case 'ERROR':
        // Add check upload status action - matches Source column behavior
        $actions[] = [
          'title' => $this->t('Check translation status'),
          'url' => \Drupal\Core\Url::fromRoute('straker_translate.interface_translation.check_upload', [
            'component' => $component,
          ], $query_options),
          'new_window' => FALSE,
        ];
        break;

      case 'REQUEST':
      case 'UNTRACKED':
        // "Not Started" status - only upload/update actions (no re-upload)
        if ($document_id) {
          $actions[] = [
            'title' => $this->t('Update document'),
            'url' => \Drupal\Core\Url::fromRoute('straker_translate.interface_translation.update', [
              'component' => $component,
            ], $query_options),
            'new_window' => FALSE,
          ];
          $actions[] = [
            'title' => $this->t('Re-Check document'),
            'url' => \Drupal\Core\Url::fromRoute('straker_translate.interface_translation.check_upload', [
              'component' => $component,
            ], $query_options),
            'new_window' => FALSE,
          ];
        }
        else {
          $actions[] = [
            'title' => $this->t('Upload document'),
            'url' => \Drupal\Core\Url::fromRoute('straker_translate.interface_translation.upload', [
              'component' => $component,
            ], $query_options),
            'new_window' => FALSE,
          ];
        }
        break;

      case 'EDITED':
      case 'CANCELLED':
      case 'ARCHIVED':
      case 'DELETED':
        // Add upload/update document action
        if ($document_id) {
          $actions[] = [
            'title' => $this->t('Update document'),
            'url' => \Drupal\Core\Url::fromRoute('straker_translate.interface_translation.update', [
              'component' => $component,
            ], $query_options),
            'new_window' => FALSE,
          ];
          $actions[] = [
            'title' => $this->t('Re-Check document'),
            'url' => \Drupal\Core\Url::fromRoute('straker_translate.interface_translation.check_upload', [
              'component' => $component,
            ], $query_options),
            'new_window' => FALSE,
          ];
        }
        else {
          $actions[] = [
            'title' => $this->t('Upload document'),
            'url' => \Drupal\Core\Url::fromRoute('straker_translate.interface_translation.upload', [
              'component' => $component,
            ], $query_options),
            'new_window' => FALSE,
          ];
        }
        break;

      case 'CURRENT':
        // Add "Open in Verify" for completed translations
        if ($document_id) {
          $actions[] = [
            'title' => $this->t('Open in Verify'),
            'url' => \Drupal\Core\Url::fromRoute('straker_translate.workbench', [
              'doc_id' => $document_id,
            ]),
            'new_window' => TRUE,
          ];
        }
        break;
    }

    // Add Re-upload document for all statuses EXCEPT "Not Started" (REQUEST/UNTRACKED)
    // Only show when document exists
    if ($document_id && !in_array($source_status, ['REQUEST', 'UNTRACKED'])) {
      $reupload_query_options = $query_options;
      $reupload_query_options['query']['reupload'] = '1';
      $actions[] = [
        'title' => $this->t('Re-upload document'),
        'url' => \Drupal\Core\Url::fromRoute('straker_translate.interface_translation.update', [
          'component' => $component,
        ], $reupload_query_options),
        'new_window' => FALSE,
      ];
    }

    return $actions;
  }

  /**
   * Gets target status content for display in the Target Status column.
   *
   * @param string $component
   *   The component path.
   *
   * @return string
   *   The HTML for target status display.
   */
  protected function getTargetStatusContent($component) {
    // Get enabled languages in weight order
    $languages = \Drupal::service('straker_translate.configuration')->getEnabledLanguages();

    // Get target statuses and document information
    $target_statuses = $this->straker_translateInterfaceTranslation->getTargetStatuses($component);
    $document_id = $this->straker_translateInterfaceTranslation->getDocumentId($component);

    $target_status_html = '';
    $query_options = ['query' => ['destination' => \Drupal::request()->getRequestUri()]];

    foreach ($languages as $langcode => $language) {
      if ($langcode !== 'en') { // Skip source language
        $status = isset($target_statuses[$langcode]) ? $target_statuses[$langcode] : 'REQUEST';

        // Skip if no document and status is REQUEST (not tracked)
        if (!$document_id && $status == 'REQUEST') {
          continue;
        }

        // Handle "New Language" case: document exists but target status is UNTRACKED or REQUEST
        // This indicates the language was added after the document was uploaded
        if ($document_id && ($status == 'UNTRACKED' || $status == 'REQUEST')) {
          $status_text = $this->t('New Language');
          $css_class = 'target-newlanguage';
          $tooltip = $this->t('@language was added after document upload', ['@language' => $language->getName()]);
        } else {
          $status_text = $this->getTargetStatusShortText($status, $langcode);
          $css_class = $this->getTargetStatusCssClass($status);
          $tooltip = $this->getTargetStatusTooltip($status, $langcode);
        }

        $actions = $this->getTargetStatusActions($component, $status, $langcode, $query_options);

        $wrapper_class = 'target-status-pill-wrapper';
        $dropdown_html = '';

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

        $target_status_html .= '<div class="' . $wrapper_class . '">';
        $target_status_html .= '<span class="language-icon ' . $css_class . '" title="' . $tooltip . '">';
        $target_status_html .= $status_text . $dropdown_html;
        $target_status_html .= '</span></div>';
      }
    }

    return $target_status_html;
  }

  /**
   * Get simple translations content - just language names without styling.
   */
  protected function getTranslationsContent($component) {
    // Get enabled languages in weight order
    $languages = \Drupal::service('straker_translate.configuration')->getEnabledLanguages();

    // Get target statuses and document information
    $target_statuses = $this->straker_translateInterfaceTranslation->getTargetStatuses($component);
    $document_id = $this->straker_translateInterfaceTranslation->getDocumentId($component);

    $language_items = [];

    foreach ($languages as $langcode => $language) {
      if ($langcode !== 'en') { // Skip source language
        $status = isset($target_statuses[$langcode]) ? $target_statuses[$langcode] : 'REQUEST';

        // Skip if no document and status is REQUEST (not tracked)
        if (!$document_id && $status == 'REQUEST') {
          continue;
        }

        // Get full language name and wrap in styled div
        $language_name = $language->getName();
        $language_items[] = '<div class="interface-translation-language-item">' . $language_name . '</div>';
      }
    }

    if (empty($language_items)) {
      return $this->t('No targets');
    }

    return '<div class="interface-translation-languages-wrapper">' . implode('', $language_items) . '</div>';
  }

  /**
   * Get short status text for target status pills.
   */
  protected function getTargetStatusShortText($status, $langcode) {
    switch ($status) {
      case 'CURRENT':
        return $this->t('Synced with Verify');
      case 'READY':
        return $this->t('Ready for Download');
      case 'PENDING':
        return $this->t('Pending');
      case 'ERROR':
        return $this->t('Error');
      case 'UNTRACKED':
        return $this->t('Not Started');
      case 'DISABLED':
        return $this->t('Disabled');
      case 'PROCESSING':
        return $this->t('Processing');
      case 'INTERMEDIATE':
        return $this->t('Intermediate');
      case 'CANCELLED':
        return $this->t('Cancelled');
      case 'DELETED':
        return $this->t('Deleted');
      case 'ARCHIVED':
        return $this->t('Archived');
      case 'REQUEST':
        return $this->t('Request');
      default:
        return ucfirst(strtolower($status));
    }
  }

  /**
   * Get CSS class for target status.
   */
  protected function getTargetStatusCssClass($status) {
    switch ($status) {
      case 'CURRENT':
        return 'target-current';
      case 'PENDING':
        return 'target-pending';
      case 'READY':
        return 'target-ready';
      case 'REQUEST':
        return 'target-request';
      case 'UNTRACKED':
        return 'target-untracked';
      case 'PROCESSING':
        return 'target-processing';
      case 'INTERMEDIATE':
        return 'target-intermediate';
      case 'ERROR':
        return 'target-error';
      case 'CANCELLED':
        return 'target-cancelled';
      case 'DISABLED':
        return 'target-disabled';
      case 'DELETED':
        return 'target-deleted';
      case 'ARCHIVED':
        return 'target-archived';
      case 'NEWLANGUAGE':
        return 'target-newlanguage';
      default:
        return 'target-unknown';
    }
  }

  /**
   * Get tooltip text for target status.
   */
  protected function getTargetStatusTooltip($status, $langcode) {
    $language = $this->languageManager->getLanguage($langcode);
    $language_name = $language ? $language->getName() : $langcode;

    switch ($status) {
      case 'CURRENT':
        return $this->t('@language translation is complete and up-to-date', ['@language' => $language_name]);
      case 'PENDING':
        return $this->t('@language translation is pending', ['@language' => $language_name]);
      case 'READY':
        return $this->t('@language translation is ready for download', ['@language' => $language_name]);
      case 'REQUEST':
        return $this->t('@language translation has been requested', ['@language' => $language_name]);
      case 'UNTRACKED':
        return $this->t('@language translation not started', ['@language' => $language_name]);
      case 'PROCESSING':
        return $this->t('@language translation in progress', ['@language' => $language_name]);
      case 'INTERMEDIATE':
        return $this->t('@language translation partially complete', ['@language' => $language_name]);
      case 'ERROR':
        return $this->t('@language translation error', ['@language' => $language_name]);
      case 'CANCELLED':
        return $this->t('@language translation cancelled', ['@language' => $language_name]);
      case 'DISABLED':
        return $this->t('@language translation disabled', ['@language' => $language_name]);
      case 'DELETED':
        return $this->t('@language translation deleted', ['@language' => $language_name]);
      case 'ARCHIVED':
        return $this->t('@language translation archived', ['@language' => $language_name]);
      default:
        return $this->t('@language translation status unknown', ['@language' => $language_name]);
    }
  }

  /**
   * Get actions for target status dropdown.
   */
  protected function getTargetStatusActions($component, $status, $langcode, $query_options) {
    $actions = [];
    $document_id = $this->straker_translateInterfaceTranslation->getDocumentId($component);

    try {
      switch ($status) {
        case 'READY':
        case 'ERROR':
          $target_file_id = $this->straker_translateInterfaceTranslation->getTargetFileId($component, $langcode);
          if ($target_file_id) {
            // Use query parameters for interface translation download
            $download_query = [
              'component' => $component,
              'locale' => $langcode,
            ] + $query_options['query'];

            $actions[] = [
              'title' => $this->t('Download translation'),
              'url' => \Drupal\Core\Url::fromRoute('straker_translate.interface_translation.download', [], [
                'query' => $download_query,
              ]),
              'new_window' => FALSE,
            ];
          }
          if ($document_id) {
            $actions[] = [
              'title' => $this->t('Open in Verify'),
              'url' => \Drupal\Core\Url::fromRoute('straker_translate.workbench', [
                'doc_id' => $document_id,
              ]),
              'new_window' => TRUE,
            ];
          }
          break;

        case 'REQUEST':
          // REQUEST status doesn't have specific actions for interface translations
          break;

        case 'CURRENT':
        case 'INTERMEDIATE':
          if ($document_id) {
            $actions[] = [
              'title' => $this->t('Open in Verify'),
              'url' => \Drupal\Core\Url::fromRoute('straker_translate.workbench', [
                'doc_id' => $document_id,
              ]),
              'new_window' => TRUE,
            ];
          }
          break;
      }
    } catch (\Exception $e) {
      // Log error but don't break the page
      \Drupal::logger('straker_translate')->error('Error generating interface target status actions: @message', ['@message' => $e->getMessage()]);
    }

    return $actions;
  }

}
