<?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\AdminBundle\Components;

use Doctrine\ORM\EntityManagerInterface;
use Ferienpass\CoreBundle\Entity\Offer\OfferInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Workflow\Exception\NotEnabledTransitionException;
use Symfony\Component\Workflow\WorkflowInterface;
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;
use Symfony\UX\TwigComponent\Attribute\ExposeInTemplate;

#[AsLiveComponent(route: 'live_component_admin')]
class OfferStatusSelect extends AbstractController
{
    use DefaultActionTrait;

    #[LiveProp]
    public OfferInterface $offer;

    #[LiveProp]
    public ?string $size = null;

    public bool $confirm = false;

    public function __construct(private readonly WorkflowInterface $offerWorkflow)
    {
    }

    public function transitions(): array
    {
        return $this->offerWorkflow->getEnabledTransitions($this->offer);
    }

    #[ExposeInTemplate]
    public function currentStatus(): string
    {
        $statuses = array_keys($this->offer->getStatus());

        $priority = ['cancelled', 'completed', 'published', 'reviewed', 'finalized', 'draft'];

        foreach ($priority as $status) {
            if (\in_array($status, $statuses, true)) {
                return $status;
            }
        }

        return (string) ($statuses[0] ?? '');
    }

    #[ExposeInTemplate]
    public function currentLabel(): string
    {
        return 'offers.status.'.$this->currentStatus();
    }

    #[LiveAction]
    public function applyTransition(#[LiveArg] string $transition, EntityManagerInterface $entityManager): void
    {
        try {
            $this->offerWorkflow->apply($this->offer, $transition);
            $entityManager->flush();

            $this->confirm = true;
        } catch (NotEnabledTransitionException) {
            // ignore
        }
    }
}
