<?php

/*
 * This file is part of the VITICORE2 package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Twig\Components\Site;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Form\Site\ContactFormType;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Messenger\Messaging\CommandBusInterface;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Notification\Command\NotificationCommand;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Notification\Enum\PushLevel;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Notification\Enum\PushTransport;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Twig\Components\Behavior\HasTemplateOverride;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Utils\Mailer;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveAction;
use Symfony\UX\LiveComponent\ComponentToolsTrait;
use Symfony\UX\LiveComponent\ComponentWithFormTrait;
use Symfony\UX\LiveComponent\DefaultActionTrait;

#[AsLiveComponent('site:ContactForm', template: '@components/site/ContactForm.html.twig')]
final class ContactForm
{
    use ComponentToolsTrait;
    use ComponentWithFormTrait;
    use DefaultActionTrait;
    use HasTemplateOverride;

    public function __construct(
        private readonly FormFactoryInterface $formFactory,
        private readonly Mailer $mailer,
        private readonly TranslatorInterface $translator,
        private readonly CommandBusInterface $commandSimpleBus,
    ) {
    }

    protected function instantiateForm(): FormInterface
    {
        return $this->formFactory->create(ContactFormType::class);
    }

    #[LiveAction]
    public function submitContact(): void
    {
        try {
            $this->submitForm();
        } catch (UnprocessableEntityHttpException) {
            $this->notifyFirstFormError();

            return;
        }

        $data = $this->form?->getData();
        $payload = \is_array($data) ? $data : [];

        try {
            $this->mailer->sendContact($payload);
            $this->notify(
                $this->translator->trans(
                    'contact.success',
                    [
                        '%firstname%' => (string) ($payload['firstname'] ?? ''),
                        '%lastname%' => (string) ($payload['lastname'] ?? ''),
                    ],
                    'form'
                ),
                PushLevel::SUCCESS
            );

            $this->resetForm();
            $this->isValidated = false;
            $this->validatedFields = [];
        } catch (\Throwable) {
            $this->notify(
                $this->translator->trans('contact.error', [], 'form'),
                PushLevel::ERROR
            );
        }
    }

    private function notifyFirstFormError(): void
    {
        $error = $this->form?->getErrors(true)->current();
        if (null === $error) {
            return;
        }

        $this->notify($error->getMessage(), PushLevel::ERROR);
    }

    private function notify(string $message, PushLevel $level): void
    {
        $this->commandSimpleBus->dispatch(new NotificationCommand(
            message: $message,
            level: $level,
            transport: PushTransport::MERCURE,
        ));
    }
}
