<?php

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Form\Admin;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Client\ConnectCpCreationClient;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\OptionsResolver\OptionsResolver;

final class ConnectFacebookUserIdType extends AbstractType
{
    public function __construct(
        private readonly ConnectCpCreationClient $client,
    ) {
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $client = $this->client;

        $resolver->setDefaults([
            'multiple' => false,
            'placeholder' => '— Sélectionner —',
            'attr' => [
                'class' => 'select2',
            ],
            // Chargement lazy des choix (pas de requête HTTP au construct)
            'choice_loader' => new class($client) implements ChoiceLoaderInterface {
                public function __construct(
                    private readonly ConnectCpCreationClient $client,
                ) {
                }

                public function loadChoiceList(?callable $value = null)
                {
                    $response = $this->client->get('/api/client_socials', [
                        'query' => ['network' => 'facebook'],
                    ]);

                    $data = json_decode($response->getBody()->getContents(), true, 512, \JSON_THROW_ON_ERROR);
                    $items = $data['hydra:member'] ?? [];

                    // On construit un tableau label => value
                    $choices = [];
                    foreach ($items as $item) {
                        $label = mb_trim(($item['username'] ?? '').' '.($item['email'] ?? ''));
                        $choices[$label] = (string) ($item['id'] ?? '');
                    }

                    // ChoiceList::fromChoices() attend une liste de "choices"
                    // Ici on convertit le tableau label=>value en "choices" (values)
                    // et on utilise un callback pour afficher le label.
                    return \Symfony\Component\Form\ChoiceList\ChoiceList::fromChoices(
                        array_values($choices),
                        $value,
                        fn (string $v) => array_search($v, $choices, true) ?: $v
                    );
                }

                public function loadChoicesForValues(array $values, ?callable $value = null): array
                {
                    // Simple: on recharge la liste et on filtre
                    $list = $this->loadChoiceList($value);
                    $choices = $list->getChoices();

                    return array_values(array_filter($choices, fn ($c) => \in_array((string) $c, $values, true)));
                }

                public function loadValuesForChoices(array $choices, ?callable $value = null): array
                {
                    return array_map('strval', $choices);
                }
            },
        ]);
    }

    public function getParent(): string
    {
        return ChoiceType::class;
    }
}
