<?php
declare(strict_types=1);

namespace FiloBlu\ActiveCampaign\Block\Adminhtml\System\Config\Form\Field;

use Magento\Config\Block\System\Config\Form\Field\FieldArray\AbstractFieldArray;
use Magento\Framework\Data\Form\Element\AbstractElement;
use Magento\Framework\DataObject;
use Magento\Framework\Module\Manager as ModuleManager;
use Magento\Backend\Block\Template\Context;
use Magento\Framework\View\Element\Html\Select;
use Magento\Config\Model\Config\Source\Yesno;
use FiloBlu\ConsentsManager\Model\ConsentTypeRepositoryFactory;
use FiloBlu\ActiveCampaign\Model\Config\Source\Lists as SourceLists;

class ProfilesList extends AbstractFieldArray
{
    /** @var ModuleManager  */
    private $moduleManager;

    /** @var Yesno  */
    private $yesno;

    /** @var Select|null */
    private $consentSelect;

    /** @var Select|null */
    private $campaignSelect;

    /** @var Select|null */
    private $yesnoSelect;
    /**
     * @var ConsentTypeRepositoryFactory
     */
    private $consentTypeRepositoryFactory;
    /**
     * @var SourceLists
     */
    private $sourceLists;

    public function __construct(
        Context $context,
        ModuleManager $moduleManager,
        Yesno $yesno,
        ConsentTypeRepositoryFactory $consentTypeRepositoryFactory,
        SourceLists $sourceLists,
        array $data = []
    ) {

        $this->moduleManager = $moduleManager;
        $this->yesno = $yesno;
        $this->consentTypeRepositoryFactory = $consentTypeRepositoryFactory;
        $this->sourceLists = $sourceLists;

        parent::__construct($context, $data);
    }

    /**
     * Nasconde il campo se FiloBlu_ConsentsManager non è attivo.
     */
    public function render(AbstractElement $element): string
    {
        if (!$this->moduleManager->isEnabled('FiloBlu_ConsentsManager')) {
            return '';
        }

        return parent::render($element);
    }

    protected function _prepareToRender(): void
    {
        $this->addColumn('consent', [
            'label'    => __('Consent'),
            'renderer' => $this->getConsentSelect(),
        ]);

        $this->addColumn('campaign', [
            'label'    => __('Campaign'),
            'renderer' => $this->getCampaignSelect(),
        ]);

        $this->addColumn('enabled', [
            'label'    => __('Enabled'),
            'renderer' => $this->getYesNoSelect(),
        ]);

        $this->_addAfter = false;
        $this->_addButtonLabel = __('Add Profile');
    }

    private function getConsentSelect(): Select
    {
        if ($this->consentSelect === null) {
            /** @var Select $select */
            $select = $this->getLayout()->createBlock(
                Select::class,
                '',
                ['data' => []]
            );

            $consentRepository = $this->consentTypeRepositoryFactory->create();
            $consents = $consentRepository->getList();


            // TODO: popola con le vere opzioni (da FiloBlu_ConsentsManager)
            $select->setOptions([
                ['label' => __('-- Select consent --'), 'value' => ''],
            ]);

            foreach ($consents->getItems() as $consent) {
                $select->addOption($consent->getId(), $consent->getName());
            }

            $select->setId($this->_getCellInputElementId('<%- _id %>', 'consent'))
                ->setName($this->_getCellInputElementName('consent'))
                ->setClass('select');

            $this->consentSelect = $select;
        }
        return $this->consentSelect;
    }

    private function getCampaignSelect(): Select
    {
        if ($this->campaignSelect === null) {
            /** @var Select $select */
            $select = $this->getLayout()->createBlock(
                Select::class,
                '',
                ['data' => []]
            );

            $options = array_map(static function (array $opt): array {
                return ['label' => (string)$opt['name'], 'value' => (string)$opt['ac_id']];
            }, $this->sourceLists->getLists());

            // aggiungi l’opzione vuota in cima
            array_unshift($options, [
                'label' => __('-- Select consent --'),
                'value' => ''
            ]);

            $select->setOptions($options);

            $select->setId($this->_getCellInputElementId('<%- _id %>', 'campaign'))
                ->setName($this->_getCellInputElementName('campaign'))
                ->setClass('select');

            $this->campaignSelect = $select;
        }
        return $this->campaignSelect;
    }

    private function getYesNoSelect(): Select
    {
        if ($this->yesnoSelect === null) {
            /** @var Select $select */
            $select = $this->getLayout()->createBlock(
                Select::class,
                '',
                ['data' => []]
            );

            $options = array_map(static function (array $opt): array {
                return ['label' => (string)$opt['label'], 'value' => (string)$opt['value']];
            }, $this->yesno->toOptionArray());

            $select->setOptions($options);

            $select->setId($this->_getCellInputElementId('<%- _id %>', 'enabled'))
                ->setName($this->_getCellInputElementName('enabled'))
                ->setClass('select');

            $this->yesnoSelect = $select;
        }
        return $this->yesnoSelect;
    }
}
