<?php
/**
 * @author 1902 Software
 * @copyright Copyright © 2023 1902 Software (https://1902software.com/magento/)
 * @package WriteTextAI_WriteTextAI
 */

namespace WriteTextAI\WriteTextAI\Ui\Components\Products\Listing\Column;

use Magento\Framework\View\Element\UiComponentFactory;
use Magento\Framework\View\Element\UiComponent\ContextInterface;
use Magento\Backend\Model\UrlInterface;
use Magento\Ui\Component\Listing\Columns\Column;
use WriteTextAI\WriteTextAI\Helper\Product as ProductHelper;
use Magento\Framework\View\LayoutInterface;
use Magento\Catalog\Model\Product\Visibility;
use WriteTextAI\WriteTextAI\ViewModel\Permissions;
use WriteTextAI\WriteTextAI\Model\Api\Session as ApiSession;
use WriteTextAI\WriteTextAI\Model\BulkRequestsManager;
use WriteTextAI\WriteTextAI\Model\BulkTransferRequestsManager;

class Actions extends Column
{
    public const URL_PATH_TRANSFER = 'wtai/grid/transfer';

    /**
     * @var UrlInterface
     */
    protected $urlBuilder;

    /**
     * @var ProductHelper
     */
    protected $productHelper;

    /**
     * @var LayoutInterface
     */
    protected $layout;

    /**
     * @var Permissions
     */
    protected $permissions;

    /**
     * @var ApiSession
     */
    protected $apiSession;

    /**
     * @var BulkTransferRequestsManager
     */
    protected $bulkTransferRequestsManager;

    /**
     * @var BulkRequestsManager
     */
    protected $bulkRequestsManager;

    /**
     * Constructor
     *
     * @param ContextInterface $context
     * @param UiComponentFactory $uiComponentFactory
     * @param UrlInterface $urlBuilder
     * @param ProductHelper $productHelper
     * @param LayoutInterface $layout
     * @param Permissions $permissions
     * @param ApiSession $apiSession
     * @param BulkTransferRequestsManager $bulkTransferRequestsManager
     * @param BulkRequestsManager $bulkRequestsManager
     * @param array $components
     * @param array $data
     */
    public function __construct(
        ContextInterface $context,
        UiComponentFactory $uiComponentFactory,
        UrlInterface $urlBuilder,
        ProductHelper $productHelper,
        LayoutInterface $layout,
        Permissions $permissions,
        ApiSession $apiSession,
        BulkTransferRequestsManager $bulkTransferRequestsManager,
        BulkRequestsManager $bulkRequestsManager,
        array $components = [],
        array $data = []
    ) {
        $this->urlBuilder = $urlBuilder;
        $this->productHelper = $productHelper;
        $this->layout = $layout;
        $this->permissions = $permissions;
        $this->apiSession = $apiSession;
        $this->bulkTransferRequestsManager = $bulkTransferRequestsManager;
        $this->bulkRequestsManager = $bulkRequestsManager;
        parent::__construct(
            $context,
            $uiComponentFactory,
            $components,
            $data
        );
    }

    /**
     * Prepare Data Source
     *
     * @param array $dataSource
     * @return array
     */
    public function prepareDataSource(array $dataSource)
    {
        $isTransferOngoing = false;
        $isBulkJobOngoing = false;
        try {
            $user = $this->apiSession->getCurrentUser();
            $userEmail = $user ? $user->getEmail() : '';
            if ($userEmail) {
                $existing = $this->bulkTransferRequestsManager->getByUser($userEmail);
                $isTransferOngoing = (bool) ($existing
                    && !(bool) $existing->getIsCancelled()
                    && !empty($existing->getQueueIds()));

                $inProgressStatuses = ['Preparing', 'Pending', 'Running', 'AttemptingCancel', 'Cancelling'];
                $bulkStatuses = $this->bulkRequestsManager->getBulkRequests();
                foreach ($bulkStatuses as $status) {
                    if (($status['user'] ?? '') !== $userEmail) {
                        continue;
                    }
                    if (!in_array(($status['subType'] ?? null), [0, 1, 2], true)) {
                        continue;
                    }
                    if (in_array(($status['status'] ?? ''), $inProgressStatuses, true)) {
                        $isBulkJobOngoing = true;
                        break;
                    }
                }
            }
        } catch (\Exception $e) {
            $isTransferOngoing = false;
            $isBulkJobOngoing = false;
        }

        if (isset($dataSource['data']['items'])) {
            foreach ($dataSource['data']['items'] as &$item) {
                $name = $this->getData('name');
                if (isset($item['entity_id'])) {
                    $item[$name]['edit'] = [
                        'label' => __('Edit'),
                        'record_id' => $item['entity_id'],
                        'store_id' => $item['store_id']
                    ];

                    if ($this->permissions->isTransferAllowed()) {
                        $item[$name]['transfer'] = [
                            'label' => __('Transfer to Magento'),
                            'record_id' => $item['entity_id'],
                            'store_id' => $item['store_id'],
                            'url'  => $this->urlBuilder->getUrl(static::URL_PATH_TRANSFER),
                            'disabled' => $isTransferOngoing || $isBulkJobOngoing,
                            'confirm' => [
                                'title' => __('Transfer to Magento'),
                                'message' => $this->getTransferConfirmContent()
                            ]
                        ];
                    }

                    if ((int)$item['visibility'] !== Visibility::VISIBILITY_NOT_VISIBLE
                        && isset($item['view_link'])
                    ) {
                        if (!empty($item['view_link'])) {
                            $item[$name]['view'] = [
                                'label' => __('View'),
                                'href'  => $item['view_link'],
                                'target' => '_blank'
                            ];
                        }
                    }
                }
            }
        }

        return $dataSource;
    }

    /**
     * Get transfer confirm content
     *
     * @return string
     */
    protected function getTransferConfirmContent()
    {
        $block = $this->layout->createBlock(\WriteTextAI\WriteTextAI\Block\Adminhtml\Grid\TransferPrompt::class);
        return $block->toHtml();
    }
}
