<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CmsBundle\Components;

use Doctrine\ORM\EntityManagerInterface;
use Ferienpass\CmsBundle\Form\UserParticipantsType;
use Ferienpass\CoreBundle\Entity\User;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Response;
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\ComponentWithFormTrait;
use Symfony\UX\LiveComponent\DefaultActionTrait;
use Symfony\UX\LiveComponent\LiveCollectionTrait;

#[AsLiveComponent(template: '@Contao/components/participants.html.twig', route: 'live_component_cms')]
class Participants extends AbstractController
{
    use ComponentWithFormTrait;
    use DefaultActionTrait;
    use LiveCollectionTrait;

    /**
     * UUIDs of existing participants currently switched to the inline edit view.
     *
     * @var string[]
     */
    #[LiveProp]
    public array $editing = [];

    public function __construct(private readonly Security $security)
    {
    }

    #[LiveAction]
    public function edit(#[LiveArg] string $uuid): void
    {
        if (!\in_array($uuid, $this->editing, true)) {
            $this->editing[] = $uuid;
        }
    }

    #[LiveAction]
    public function stopEditing(#[LiveArg] string $uuid): void
    {
        $this->editing = array_values(array_filter($this->editing, static fn (string $u): bool => $u !== $uuid));
    }

    #[LiveAction]
    public function save(EntityManagerInterface $entityManager): ?Response
    {
        $this->submitForm();

        $form = $this->getForm();
        if (!$form->isValid()) {
            // Re-render in place so inline validation errors stay visible.
            return null;
        }

        foreach ($form->get('participants')->getData() as $participant) {
            $entityManager->persist($participant);
        }

        $entityManager->flush();

        // Reload the page so the live collection starts from the freshly persisted
        // state (avoids stale/duplicated rows) and every row collapses to its view.
        return $this->redirectToRoute('user_account', ['alias' => 'account']);
    }

    protected function instantiateForm(): FormInterface
    {
        $user = $this->security->getUser();

        return $this->createForm(UserParticipantsType::class, $user instanceof User ? $user : null);
    }
}
