<?php

declare(strict_types=1);

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

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Form\Admin\PageFrontEditType;
use CpCreation\VitiCore\PageBuilder\Model\Page;
use CpCreation\VitiCore\PageBuilder\Repository\PageRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveAction;
use Symfony\UX\LiveComponent\Attribute\LiveProp;
use Symfony\UX\LiveComponent\ComponentWithFormTrait;
use Symfony\UX\LiveComponent\DefaultActionTrait;

#[AsLiveComponent('page_builder:PageEditor', template: '@components/page_builder/PageEditor.html.twig')]
final class PageEditor extends AbstractController
{
    use ComponentWithFormTrait;
    use DefaultActionTrait;

    #[LiveProp(writable: false)]
    public Page $page;

    #[LiveProp(writable: false)]
    public bool $panelMode = false;

    public bool $saved = false;

    public function __construct(
        private readonly PageRepository $pageRepository,
    ) {
    }

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

    #[LiveAction]
    public function save(): void
    {
        $this->saved = false;

        try {
            $this->submitForm();
        } catch (UnprocessableEntityHttpException) {
            return;
        }

        $this->pageRepository->save($this->page);
        $this->saved = true;
    }
}
