<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\PersonBundle\Form;

use Chill\MainBundle\Form\Type\ChillTextareaType;
use Chill\MainBundle\Form\Type\CommentType;
use Chill\PersonBundle\Entity\Person\PersonResource;
use Chill\PersonBundle\Entity\Person\PersonResourceKind;
use Chill\PersonBundle\Form\Type\PickPersonDynamicType;
use Chill\PersonBundle\Templating\Entity\ResourceKindRender;
use Chill\ThirdPartyBundle\Form\Type\PickThirdpartyDynamicType;
use Doctrine\ORM\EntityRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Contracts\Translation\TranslatorInterface;

final class PersonResourceType extends AbstractType
{
    public function __construct(private readonly ResourceKindRender $resourceKindRender, private readonly TranslatorInterface $translator) {}

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('kind', EntityType::class, [
                'label' => 'Type',
                'required' => false,
                'class' => PersonResourceKind::class,
                'query_builder' => static function (EntityRepository $er) {
                    $qb = $er->createQueryBuilder('pr');
                    $qb->where($qb->expr()->eq('pr.isActive', 'TRUE'));

                    return $qb;
                },
                'placeholder' => $this->translator->trans('Select a type'),
                'choice_label' => function (PersonResourceKind $personResourceKind) {
                    $options = [];

                    return $this->resourceKindRender->renderString($personResourceKind, $options);
                },
            ])
            ->add('person', PickPersonDynamicType::class, [
                'label' => $this->translator->trans('person_resource.person_non_prof'),
            ])
            ->add('thirdparty', PickThirdpartyDynamicType::class, [
                'label' => $this->translator->trans('person_resource.thirdparty_prof'),
            ])
            ->add('freetext', ChillTextareaType::class, [
                'label' => $this->translator->trans('person_resource.freetext'),
                'required' => false,
            ])
            ->add('comment', CommentType::class, [
                'label' => 'Note',
                'required' => false,
            ]);
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => PersonResource::class,
        ]);
    }

    public function getBlockPrefix(): string
    {
        return 'chill_personbundle_person_resource';
    }
}
