<?php

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\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;

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

    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder->addEventListener(FormEvents::PRE_SET_DATA, [$this, 'onPreSetData']);
    }

    public function onPreSetData(FormEvent $event): void
    {
        $form = $event->getForm();
        $parent = $form->getParent();

        if ($parent === null) {
            return;
        }

        $normData = $parent->getNormData();
        $userId = \is_object($normData) && method_exists($normData, 'getId') ? $normData->getId() : null;

        if (!$userId) {
            return;
        }

        $result = $this->client->get('/api/client_socials/' . $userId);
        $clientSocial = json_decode($result->getBody()->getContents(), true) ?: [];

        $items = $clientSocial['dataAccounts']['data'] ?? [];
        if (!\is_array($items) || $items === []) {
            if ($parent->has('accountInstagram')) {
                $parent->remove('accountInstagram');
            }

            $parent->add('accountInstagram', ChoiceType::class, [
                'choices' => [],
                'required' => false,
                'multiple' => false,
                'placeholder' => 'Aucun',
                'attr' => ['class' => 'select2'],
            ]);

            return;
        }

        $choices = [];
        foreach ($items as $item) {
            $name = $item['name'] ?? null;
            $instagramId = $item['instagram_business_account']['id'] ?? null;

            if ($name && $instagramId) {
                $choices[$name] = $instagramId;
            }
        }

        if ($parent->has('accountInstagram')) {
            $parent->remove('accountInstagram');
        }

        $parent->add('accountInstagram', ChoiceType::class, [
            'choices' => $choices,
            'required' => false,
            'multiple' => false,
            'placeholder' => 'Aucun',
            'attr' => [
                'class' => 'select2',
            ],
        ]);
    }

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