<?php
/**
 * Copyright since 2025 InPost S.A.
 *
 * For the full license information, please view the LICENSE file bundled with the module.
 *
 * @author InPost S.A.
 * @copyright since 2025 InPost S.A.
 * @license MIT
 */

declare(strict_types=1);

namespace InPost\International\Carrier\Grid;

use InPost\International\Carrier\CarrierType;
use InPost\International\Controller\Admin\CarrierController;
use InPost\International\Country;
use InPost\International\Enum\Form\Type\EnumType;
use InPost\International\PrestaShop\Grid\Action\Row\LegacyLinkRowAction;
use PrestaShop\PrestaShop\Core\Grid\Action\GridActionCollection;
use PrestaShop\PrestaShop\Core\Grid\Action\GridActionCollectionInterface;
use PrestaShop\PrestaShop\Core\Grid\Action\Row\RowActionCollection;
use PrestaShop\PrestaShop\Core\Grid\Action\Row\RowActionCollectionInterface;
use PrestaShop\PrestaShop\Core\Grid\Action\Row\RowActionInterface;
use PrestaShop\PrestaShop\Core\Grid\Action\Row\Type\LinkRowAction;
use PrestaShop\PrestaShop\Core\Grid\Action\Row\Type\SubmitRowAction;
use PrestaShop\PrestaShop\Core\Grid\Action\Type\SimpleGridAction;
use PrestaShop\PrestaShop\Core\Grid\Column\ColumnCollection;
use PrestaShop\PrestaShop\Core\Grid\Column\ColumnCollectionInterface;
use PrestaShop\PrestaShop\Core\Grid\Column\Type\BooleanColumn as LeagcyBooleanColumn;
use PrestaShop\PrestaShop\Core\Grid\Column\Type\Common\ActionColumn;
use PrestaShop\PrestaShop\Core\Grid\Column\Type\Common\BooleanColumn;
use PrestaShop\PrestaShop\Core\Grid\Column\Type\Common\DataColumn;
use PrestaShop\PrestaShop\Core\Grid\Column\Type\Common\IdentifierColumn;
use PrestaShop\PrestaShop\Core\Grid\Column\Type\DataColumn as LegacyDataColumn;
use PrestaShop\PrestaShop\Core\Grid\Definition\Factory\AbstractGridDefinitionFactory;
use PrestaShop\PrestaShop\Core\Grid\Definition\Factory\FilterableGridDefinitionFactoryInterface;
use PrestaShop\PrestaShop\Core\Grid\Filter\Filter;
use PrestaShop\PrestaShop\Core\Grid\Filter\FilterCollection;
use PrestaShop\PrestaShop\Core\Grid\Filter\FilterCollectionInterface;
use PrestaShop\PrestaShop\Core\Hook\HookDispatcherInterface;
use PrestaShopBundle\Event\Dispatcher\NullDispatcher;
use PrestaShopBundle\Form\Admin\Type\SearchAndResetType;
use PrestaShopBundle\Form\Admin\Type\YesAndNoChoiceType;
use PrestaShopBundle\Security\Voter\PageVoter;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

if (!defined('_PS_VERSION_')) {
    exit;
}

final class CarrierGridDefinitionFactory extends AbstractGridDefinitionFactory implements FilterableGridDefinitionFactoryInterface
{
    public const GRID_ID = 'inpost_intl_carrier';

    /**
     * @var AuthorizationCheckerInterface
     */
    private $authorizationChecker;

    /**
     * @var bool
     */
    private $useLegacyCarriersPage;

    public function __construct(TranslatorInterface $translator, AuthorizationCheckerInterface $authorizationChecker, bool $useLegacyCarriersPage = false, HookDispatcherInterface $hookDispatcher = null)
    {
        parent::__construct($hookDispatcher ?? new NullDispatcher());
        $this->translator = $translator;
        $this->authorizationChecker = $authorizationChecker;
        $this->useLegacyCarriersPage = $useLegacyCarriersPage;
    }

    protected function getId(): string
    {
        return self::GRID_ID;
    }

    public function getFilterId(): string
    {
        return $this->getId();
    }

    protected function getName(): string
    {
        return $this->trans('Services', [], 'Modules.Inpostinternational.Carrier');
    }

    protected function getColumns(): ColumnCollectionInterface
    {
        $dataColumnClass = class_exists(DataColumn::class) ? DataColumn::class : LegacyDataColumn::class;
        $booleanColumnClass = class_exists(BooleanColumn::class) ? BooleanColumn::class : LeagcyBooleanColumn::class;

        return (new ColumnCollection())
            ->add(
                (new IdentifierColumn('id_reference'))
                    ->setName($this->trans('Reference ID', [], 'Modules.Inpostinternational.Carrier'))
                    ->setOptions([
                        'identifier_field' => 'id_reference',
                    ])
            )
            ->add(
                (new $dataColumnClass('type'))
                    ->setName($this->trans('Type', [], 'Modules.Inpostinternational.Carrier'))
                    ->setOptions([
                        'field' => 'type',
                    ])
            )
            ->add(
                (new $dataColumnClass('name'))
                    ->setName($this->trans('Name', [], 'Admin.Global'))
                    ->setOptions([
                        'field' => 'name',
                    ])
            )
            ->add(
                (new $booleanColumnClass('active'))
                    ->setName($this->trans('Enabled', [], 'Admin.Global'))
                    ->setOptions([
                        'field' => 'active',
                        'true_name' => $this->trans('Yes', [], 'Admin.Global'),
                        'false_name' => $this->trans('No', [], 'Admin.Global'),
                    ])
            )
            ->add(
                (new $dataColumnClass('countries'))
                    ->setName($this->trans('Countries', [], 'Modules.Inpostinternational.Carrier'))
                    ->setOptions([
                        'field' => 'countries',
                    ])
            )
            ->add(
                (new ActionColumn('actions'))
                    ->setName($this->trans('Actions', [], 'Admin.Global'))
                    ->setOptions([
                        'actions' => $this->getRowActions(),
                    ])
            );
    }

    protected function getFilters(): FilterCollectionInterface
    {
        return (new FilterCollection())
            ->add(
                (new Filter('id_reference', NumberType::class))
                    ->setTypeOptions([
                        'attr' => [
                            'placeholder' => $this->trans('Search ID', [], 'Admin.Actions'),
                        ],
                        'required' => false,
                    ])
                    ->setAssociatedColumn('id_reference')
            )
            ->add(
                (new Filter('type', EnumType::class))
                    ->setTypeOptions([
                        'class' => CarrierType::class,
                        'input' => 'value',
                        'placeholder' => $this->trans('All', [], 'Admin.Global'),
                        'required' => false,
                    ])
                    ->setAssociatedColumn('type')
            )
            ->add(
                (new Filter('name', TextType::class))
                    ->setTypeOptions([
                        'attr' => [
                            'placeholder' => $this->trans('Search name', [], 'Admin.Actions'),
                        ],
                        'required' => false,
                    ])
                    ->setAssociatedColumn('name')
            )
            ->add(
                (new Filter('active', YesAndNoChoiceType::class))
                    ->setTypeOptions([
                        'required' => false,
                    ])
                    ->setAssociatedColumn('active')
            )
            ->add(
                (new Filter('countries', EnumType::class))
                    ->setTypeOptions([
                        'class' => Country::class,
                        'input' => 'value',
                        'placeholder' => $this->trans('All', [], 'Admin.Global'),
                        'required' => false,
                    ])
                    ->setAssociatedColumn('countries')
            )
            ->add(
                (new Filter('actions', SearchAndResetType::class))
                    ->setTypeOptions([
                        'reset_route' => 'admin_common_reset_search_by_filter_id',
                        'reset_route_params' => [
                            'filterId' => self::GRID_ID,
                        ],
                        'redirect_route' => 'admin_inpost_intl_carriers_index',
                    ])
                    ->setAssociatedColumn('actions')
            );
    }

    protected function getGridActions(): GridActionCollectionInterface
    {
        return (new GridActionCollection())
            ->add(
                (new SimpleGridAction('common_refresh_list'))
                    ->setName($this->trans('Refresh list', [], 'Admin.Advparameters.Feature'))
                    ->setIcon('refresh')
            )
            ->add(
                (new SimpleGridAction('common_show_query'))
                    ->setName($this->trans('Show SQL query', [], 'Admin.Actions'))
                    ->setIcon('code')
            )
            ->add(
                (new SimpleGridAction('common_export_sql_manager'))
                    ->setName($this->trans('Export to SQL Manager', [], 'Admin.Actions'))
                    ->setIcon('storage')
            );
    }

    private function getRowActions(): RowActionCollectionInterface
    {
        $collection = new RowActionCollection();

        if ($this->authorizationChecker->isGranted(PageVoter::UPDATE, CarrierController::CARRIERS_TAB_NAME)) {
            $collection
                ->add(
                    (new LinkRowAction('edit'))
                        ->setName($this->trans('Edit', [], 'Admin.Actions'))
                        ->setOptions([
                            'route' => 'admin_inpost_intl_carriers_edit',
                            'route_param_name' => 'id',
                            'route_param_field' => 'id_reference',
                        ])
                        ->setIcon('edit')
                )
                ->add($this->getNativeCarrierEditionRowAction());
        }

        if ($this->authorizationChecker->isGranted(PageVoter::DELETE, CarrierController::CARRIERS_TAB_NAME)) {
            $collection->add(
                (new SubmitRowAction('delete'))
                    ->setName($this->trans('Delete', [], 'Admin.Actions'))
                    ->setOptions([
                        'route' => 'admin_inpost_intl_carriers_delete',
                        'method' => 'DELETE',
                        'route_param_name' => 'id',
                        'route_param_field' => 'id_reference',
                        'confirm_message' => $this->trans('Delete selected item?', [], 'Admin.Notifications.Warning'),
                    ])
                    ->setIcon('delete')
            );
        }

        return $collection;
    }

    private function getNativeCarrierEditionRowAction(): RowActionInterface
    {
        if ($this->useLegacyCarriersPage) {
            return (new LegacyLinkRowAction('edit_data'))
                ->setName($this->trans('Edit carrier', [], 'Modules.Inpostinternational.Carrier'))
                ->setOptions([
                    'controller' => 'AdminCarrierWizard',
                    'route_param_name' => 'id_carrier',
                    'route_param_field' => 'id_carrier',
                ])
                ->setIcon('local_shipping');
        }

        return (new LinkRowAction('edit_data'))
            ->setName($this->trans('Edit carrier', [], 'Modules.Inpostinternational.Carrier'))
            ->setOptions([
                'route' => 'admin_carriers_edit',
                'route_param_name' => 'carrierId',
                'route_param_field' => 'id_carrier',
            ])
            ->setIcon('edit');
    }
}
