<?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\ParcelTemplate\Grid;

use InPost\International\Api\Shipment\Model\Parcel\ParcelType;
use InPost\International\Controller\Admin\ConfigurationController;
use InPost\International\Enum\Form\Type\EnumType;
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\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\Common\ActionColumn;
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\Common\ToggleColumn;
use PrestaShop\PrestaShop\Core\Grid\Column\Type\DataColumn as LegacyDataColumn;
use PrestaShop\PrestaShop\Core\Grid\Definition\Factory\AbstractFilterableGridDefinitionFactory;
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 ParcelTemplateGridDefinitionFactory extends AbstractFilterableGridDefinitionFactory
{
    public const GRID_ID = 'inpost_intl_parcel_template';

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

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

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

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

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

        return (new ColumnCollection())
            ->add(
                (new IdentifierColumn('id'))
                    ->setName($this->trans('ID', [], 'Admin.Global'))
                    ->setOptions([
                        'identifier_field' => 'id',
                    ])
            )
            ->add(
                (new $dataColumnClass('name'))
                    ->setName($this->trans('Name', [], 'Admin.Global'))
                    ->setOptions([
                        'field' => 'name',
                    ])
            )
            ->add(
                (new $dataColumnClass('type'))
                    ->setName($this->trans('Parcel type', [], 'Modules.Inpostinternational.Shipment'))
                    ->setOptions([
                        'field' => 'type',
                    ])
            )
            ->add(
                (new $dataColumnClass('dimensions'))
                    ->setName($this->trans('Dimensions', [], 'Modules.Inpostinternational.Shipment'))
                    ->setOptions([
                        'field' => 'dimensions',
                        'sortable' => false,
                    ])
            )
            ->add(
                (new $dataColumnClass('weight'))
                    ->setName($this->trans('Weight', [], 'Admin.Global'))
                    ->setOptions([
                        'field' => 'weight',
                        'sortable' => false,
                    ])
            )
            ->add(
                (new ToggleColumn('is_default'))
                    ->setName($this->trans('Default', [], 'Modules.Inpostinternational.Admin'))
                    ->setOptions([
                        'field' => 'is_default',
                        'primary_field' => 'id',
                        'route' => 'admin_inpost_intl_parcel_templates_select_default',
                        'route_param_name' => 'id',
                    ])
            )
            ->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', NumberType::class))
                    ->setTypeOptions([
                        'attr' => [
                            'placeholder' => $this->trans('Search ID', [], 'Admin.Actions'),
                        ],
                        'required' => false,
                    ])
                    ->setAssociatedColumn('id')
            )
            ->add(
                (new Filter('name', TextType::class))
                    ->setTypeOptions([
                        'attr' => [
                            'placeholder' => $this->trans('Search name', [], 'Admin.Actions'),
                        ],
                        'required' => false,
                    ])
                    ->setAssociatedColumn('name')
            )
            ->add(
                (new Filter('type', EnumType::class))
                    ->setTypeOptions([
                        'class' => ParcelType::class,
                        'input' => 'value',
                        'placeholder' => $this->trans('All', [], 'Admin.Global'),
                        'required' => false,
                    ])
                    ->setAssociatedColumn('type')
            )
            ->add(
                (new Filter('dimensions', NumberType::class))
                    ->setTypeOptions([
                        'attr' => [
                            'placeholder' => $this->trans('Search dimensions', [], 'Modules.Inpostinternational.Shipment'),
                        ],
                        'required' => false,
                    ])
                    ->setAssociatedColumn('dimensions')
            )
            ->add(
                (new Filter('weight', NumberType::class))
                    ->setTypeOptions([
                        'attr' => [
                            'placeholder' => $this->trans('Search weight', [], 'Modules.Inpostinternational.Shipment'),
                        ],
                        'required' => false,
                    ])
                    ->setAssociatedColumn('weight')
            )
            ->add(
                (new Filter('is_default', YesAndNoChoiceType::class))
                    ->setTypeOptions([
                        'required' => false,
                    ])
                    ->setAssociatedColumn('is_default')
            )
            ->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_parcel_templates_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, ConfigurationController::TAB_NAME)) {
            $collection->add(
                (new LinkRowAction('edit'))
                    ->setName($this->trans('Edit', [], 'Admin.Actions'))
                    ->setOptions([
                        'route' => 'admin_inpost_intl_parcel_templates_edit',
                        'route_param_name' => 'id',
                        'route_param_field' => 'id',
                    ])
                    ->setIcon('edit')
            );
        }

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

        return $collection;
    }
}
