<?php

declare(strict_types=1);

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

use CpCreation\VitiCore\PageBuilder\Model\Page;
use CpCreation\VitiCore\PageBuilder\Model\PageSection;
use CpCreation\VitiCore\PageBuilder\Repository\PageSectionRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveAction;
use Symfony\UX\LiveComponent\Attribute\LiveArg;
use Symfony\UX\LiveComponent\Attribute\LiveProp;
use Symfony\UX\LiveComponent\DefaultActionTrait;

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

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

    #[LiveProp(writable: true)]
    public string $selectedType = 'page';

    #[LiveProp(writable: true)]
    public ?string $selectedSectionId = null;

    public function __construct(
        private readonly PageSectionRepository $pageSectionRepository,
    ) {
    }

    /**
     * @return list<PageSection>
     */
    public function getSections(): array
    {
        return $this->pageSectionRepository->findByPageCodeAdmin($this->page->getCode());
    }

    public function getSelectedSection(): ?PageSection
    {
        if (null === $this->selectedSectionId) {
            return null;
        }

        foreach ($this->getSections() as $section) {
            if ((string) $section->getId() === $this->selectedSectionId) {
                return $section;
            }
        }

        return null;
    }

    #[LiveAction]
    public function selectPage(): void
    {
        $this->selectedType = 'page';
        $this->selectedSectionId = null;
    }

    #[LiveAction]
    public function selectSection(#[LiveArg] string $sectionId): void
    {
        $this->selectedType = 'section';
        $this->selectedSectionId = $sectionId;
    }
}
