<?php

/*
 * This file is part of the Serenity 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 Serenity\MediaBundle\Twig\Components;

use Serenity\CoreBundle\Notification\Command\NotificationCommand;
use Serenity\CoreBundle\Notification\Enum\PushLevel;
use Serenity\MediaBundle\Doctrine\Repository\ImageRepository;
use Serenity\MediaBundle\Form\Type\EditImageType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\Attribute\Target;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Uid\Uuid;
use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveAction;
use Symfony\UX\LiveComponent\Attribute\LiveArg;
use Symfony\UX\LiveComponent\Attribute\LiveListener;
use Symfony\UX\LiveComponent\Attribute\LiveProp;
use Symfony\UX\LiveComponent\ComponentToolsTrait;
use Symfony\UX\LiveComponent\ComponentWithFormTrait;
use Symfony\UX\LiveComponent\DefaultActionTrait;

#[AsLiveComponent(template: '@components/SerenityMedia/EditImage.html.twig')]
class EditImage extends AbstractController
{
    use ComponentToolsTrait;
    use ComponentWithFormTrait;
    use DefaultActionTrait;

    #[LiveProp]
    public bool $open = false;
    #[LiveProp]
    public ?\Serenity\MediaBundle\Entity\Image $data = null;

    public function __construct(private readonly ImageRepository $imageRepository,
        #[Target]
        private readonly MessageBusInterface $commandBus,
        private readonly TranslatorInterface $translator,
    ) {
    }

    protected function instantiateForm(): FormInterface
    {
        return $this->createForm(EditImageType::class, $this->data);
    }

    #[LiveAction]
    public function save(Request $request): void
    {
        try {
            $this->submitForm();
            if ($this->form instanceof FormInterface) {
                $data = $this->form->getData();
                $this->imageRepository->persist($data);
                $this->imageRepository->flush();
            }
        } catch (UnprocessableEntityHttpException $e) {
            $form = $this->getForm(); // safe même en erreur
            if ($form->getErrors(true)->count() > 0) {
                $notification = new NotificationCommand(
                    message: $this->translator->trans('form.error', [], 'serenity_core_messages.admin'),
                    level: PushLevel::ERROR
                );
                $this->commandBus->dispatch($notification);
            }
        }

        $this->dispatchBrowserEvent('modal:close');
        $this->open = false;
    }

    #[LiveListener(eventName: 'editImage:edit')]
    public function edit(#[LiveArg] string $id): void
    {
        /** @var \Serenity\MediaBundle\Entity\Image|null $image */
        $image = $this->imageRepository->findOneById(Uuid::fromString($id));
        $this->data = $image;
        $this->dispatchBrowserEvent('modal:open', ['name' => 'editImage']);
        $this->resetForm();
    }
}
