<?php

namespace KupShop\ComponentsBundle\Twig\Components\Utils\Forms\ProductQuestion;

use KupShop\ComponentsBundle\Attributes\Component;
use KupShop\ComponentsBundle\Attributes\Version;
use KupShop\ComponentsBundle\Twig\Components\Utils\Forms\EmailForm;
use KupShop\ComponentsBundle\Twig\DataProvider\ProductDataTrait;
use KupShop\KupShopBundle\Context\UserContext;
use KupShop\KupShopBundle\Util\StringUtil;
use KupShop\KupShopBundle\Util\System\UrlFinder;
use Symfony\Component\Form\FormInterface;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveAction;
use Symfony\UX\LiveComponent\ComponentWithFormTrait;

#[AsLiveComponent(template: '@Components/components/Utils/Forms/ProductQuestion/Form.1.html.twig')]
#[Component(1, [
    new Version(1, newJs: null),
])]
class Form extends EmailForm
{
    use ComponentWithFormTrait;
    use ProductDataTrait;

    public function __construct(
        private readonly UserContext $userContext,
        private readonly UrlFinder $urlFinder,
    ) {
    }

    protected function instantiateForm(): FormInterface
    {
        $data = new Entity();
        $user = $this->userContext->getActive();

        if ($this->getIsUserLogged() && !empty($user)) {
            $data->name = $user->name;
            $data->email = $user->email;
        }

        return $this->createForm(FormType::class, $data, [
            'action' => 'javascript:void(0);',
        ]);
    }

    public function getIsUserLogged(): bool
    {
        return !empty($this->userContext->getActiveId());
    }

    public function getProductTitle(): string
    {
        return $this->product->title;
    }

    private function processUrl($params): string
    {
        return htmlspecialchars(createScriptURL($params), ENT_QUOTES);
    }

    public function getProductUrl(): string
    {
        return path('products',
            ['id' => $this->product->id, 'name' => StringUtil::slugify($this->getProductTitle())]);
    }

    #[LiveAction]
    public function handleForm()
    {
        $this->submitForm();

        /** @var Entity $entity */
        $entity = $this->getForm()->getData();

        try {
            $this->sendEmail(ProductQuestionEmail::getType(), function (ProductQuestionEmail $emailService) use ($entity) {
                $userEmail = $entity->email;
                $emailService->setSender($userEmail);
                $emailService->setData([
                    'DATA_NAME' => $entity->name,
                    'DATA_EMAIL' => $entity->email,
                    'DATA_SUBJECT' => $this->getProductTitle(),
                    'DATA_COMMENT' => $entity->comment,
                    'DATA_PAGE_URL' => $this->getProductUrl(),
                ]);

                return $emailService;
            });

            // Answer
            $this->sendEmail(ProductQuestionAnswerEmail::getType(), function (ProductQuestionAnswerEmail $emailService) use ($entity) {
                $userEmail = $entity->email;
                $emailService->setSender($userEmail);
                $emailService->setData([
                    'DATA_REPORT_MESSAGE' => $entity->comment,
                ]);

                return $emailService;
            });

            addUserMessage($this->translator->trans('dsa.form.success', [], 'forms'), 'success');
        } catch (\Exception $e) {
            addUserMessage($this->translator->trans('dsa.form.error', [], 'forms'), 'error');
            addUserMessage($e->getMessage(), 'error');
        }

        $this->resetForm();
        $this->dispatchBrowserEvent('modal:close');
    }

    public function getConsentUrl(): string
    {
        return $this->processUrl(['s' => 'page', 'label' => 'consent']);
    }

    public function getPrivacyPolicyUrl(): string
    {
        return $this->processUrl(['s' => 'page', 'label' => 'privacy_policy']);
    }
}
