<?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\Edition;

use Doctrine\ORM\EntityManagerInterface;
use Ferienpass\CoreBundle\Emoji\EmojiDictionary;
use Ferienpass\CoreBundle\Entity\Edition;
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;

/**
 * Inline emoji picker shown next to the edition title on admin_editions_show.
 * Clicking the current emoji opens a searchable grid of the curated
 * {@see EmojiDictionary}; picking one persists it as a short code on the edition.
 */
#[AsLiveComponent('Admin:Edition:EmojiPicker', route: 'live_component_admin')]
class EmojiPicker extends AbstractController
{
    use DefaultActionTrait;

    #[LiveProp]
    public Edition $edition;

    #[LiveProp]
    public bool $open = false;

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

    /**
     * @return list<string>
     */
    public function codes(): array
    {
        $query = trim(mb_strtolower($this->query));
        if ('' === $query) {
            return EmojiDictionary::CODES;
        }

        $needle = str_replace([':', ' '], ['', '_'], $query);

        return array_values(array_filter(
            EmojiDictionary::CODES,
            static fn (string $code): bool => str_contains($code, $needle),
        ));
    }

    #[LiveAction]
    public function toggle(): void
    {
        $this->open = !$this->open;
        $this->query = '';
    }

    #[LiveAction]
    public function close(): void
    {
        $this->open = false;
        $this->query = '';
    }

    #[LiveAction]
    public function select(#[LiveArg] string $code, EntityManagerInterface $entityManager): void
    {
        if (!EmojiDictionary::has($code)) {
            return;
        }

        $this->edition->setEmoji($code);
        $entityManager->flush();

        $this->open = false;
        $this->query = '';
    }
}
