<?php

declare(strict_types=1);

namespace Drupal\conductor\Controller;

use Drupal\Component\Datetime\TimeInterface;
use Drupal\conductor\ConductorHttpApiClient;
use Drupal\conductor\Exception\ConductorCredentialsNotFoundException;
use Drupal\conductor\Repository\DraftRepository;
use Drupal\conductor\Repository\DraftRepositoryInterface;
use Drupal\Core\Datetime\DateFormatterInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Controller for displaying the drafts.
 */
final class ConductorDraftDashboard implements ContainerInjectionInterface {

  use StringTranslationTrait;

  public function __construct(
    private readonly DraftRepositoryInterface $draftRepository,
    private readonly EntityTypeManagerInterface $entityTypeManager,
    private readonly DateFormatterInterface $dateFormatter,
    private readonly ConductorHttpApiClient $conductorHttpApiClient,
    private readonly TimeInterface $time,
  ) {
  }

  public static function create(ContainerInterface $container): self {
    return new self(
      $container->get(DraftRepository::class),
      $container->get('entity_type.manager'),
      $container->get('date.formatter'),
      $container->get(ConductorHttpApiClient::class),
      $container->get('datetime.time'),
    );
  }

  public function __invoke(Request $request): array {

    $current_year = $this->dateFormatter->format(
      $this->time->getCurrentTime(),
      'custom',
      'Y'
    );
    $drafts = $this->draftRepository->getDrafts((int) $current_year);

    $headers = ['Draft ID', 'Entity', 'Created', 'Changed', 'Status'];
    $rows = [];

    foreach ($drafts as $draft) {
      $rows[] = [
        $this->buildConductorsDraftLink($draft['draft_id']),
        [
          'data' => $this->buildEntityLink(
            $draft['entity_type'],
            $draft['entity_id']
          ),
        ],
        $this->dateFormatter->format($draft['created']),
        $this->dateFormatter->format($draft['changed']),
        $draft['deleted'] ? $this->t('Deleted') : $this->t('Published'),
      ];
    }

    $build = [
      'available_drafts' => [
        '#type' => 'details',
        '#title' => $this->t('Drafts usage'),
        '#open' => TRUE,
        'usage' => [
          '#markup' => $this->t(
            '<span>@used/@total</span> drafts used for year @year',
            [
              '@used' => $this->draftRepository->getUsedDrafts(),
              '@total' => $this->draftRepository->getMaxDrafts(),
              '@year' => $current_year,
            ]
          ),
        ],
      ],

      'drafts' => [
        '#attributes' => ['class' => ['drafts']],
        '#theme' => 'table',
        '#header' => $headers,
        '#rows' => $rows,
        '#empty' => $this->t('No drafts found for the current year.'),
      ],
    ];

    return $build;
  }

  private function buildEntityLink(
    string $entity_type,
    string $entity_id,
  ): array {
    try {
      $entity = $this->entityTypeManager->getStorage($entity_type)->load(
        $entity_id
      );
    }
    catch (\Exception) {
      $entity = NULL;
    }
    if (NULL === $entity) {
      return [
        '#markup' => $this->t('Entity @type:@id (not found or deleted)', [
          '@type' => $entity_type,
          '@id' => $entity_id,
        ]),
      ];
    }

    return $entity->toLink()->toRenderable();
  }

  private function buildConductorsDraftLink(string $draft_id): array|string {
    try {
      $accountId = $this->conductorHttpApiClient->getAccountId();
    }
    catch (ConductorCredentialsNotFoundException) {
      return $draft_id;
    }

    $link = [
      'data' => [
        '#type' => 'link',
        '#title' => $draft_id,
        '#url' => Url::fromUri(
          "https://app.conductor.com/u/$accountId/writing-assistant/draft/",
          [
            'query' => [
              'draftId' => $draft_id,
            ],
          ]
        ),
        'attributes' => [
          '#target' => '_blank',
        ],
      ],
    ];

    return $link;
  }

}
