<?php

declare(strict_types=1);

namespace MauticPlugin\DealFlowBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\CallbackTransformer;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

final class DealFlowConfigType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        // License key field — also available in Plugins → Deal Flow popup
        $builder->add('dealflow_license_key', TextType::class, [
            'label' => 'mautic.dealflow.config.license_key',
            'help' => 'mautic.dealflow.config.license_key_help',
            'required' => false,
            'attr' => [
                'autocomplete' => 'off',
                'placeholder' => 'DF-XXXX-XXXX-XXXX-XXXX',
            ],
        ]);

        // Mask the license key for display
        $builder->get('dealflow_license_key')->addViewTransformer(new CallbackTransformer(
            static function (mixed $value): string {
                if (!\is_string($value) || $value === '') {
                    return '';
                }
                if (!preg_match('/^DF-[A-Z2-9]{4}-[A-Z2-9]{4}-[A-Z2-9]{4}-[A-Z2-9]{4}$/', $value)) {
                    return (string) $value;
                }
                $parts = explode('-', $value);

                return $parts[0].'-'.$parts[1].'-****-****-'.$parts[4];
            },
            static function (mixed $value): string {
                return \is_string($value) ? trim($value) : '';
            }
        ));

        // Hidden fields for license state (preserved across saves)
        $builder->add('dealflow_license_status', HiddenType::class);
        $builder->add('dealflow_license_updates_until', HiddenType::class);
        $builder->add('dealflow_license_last_validated_at', HiddenType::class);
        $builder->add('dealflow_license_last_validation_valid', HiddenType::class);

        $builder->add('dealflow_default_association_labels', TextareaType::class, [
            'label' => 'mautic.dealflow.config.default_roles',
            'help' => 'mautic.dealflow.config.default_roles_help',
            'required' => false,
            'attr' => [
                'rows' => 5,
            ],
        ]);

        $builder->add('dealflow_default_sources', TextareaType::class, [
            'label' => 'mautic.dealflow.config.default_sources',
            'help' => 'mautic.dealflow.config.default_sources_help',
            'required' => false,
            'attr' => [
                'rows' => 5,
            ],
        ]);

        $builder->add('dealflow_inbound_webhook_secret', TextType::class, [
            'label' => 'mautic.dealflow.config.webhook_secret',
            'help' => 'mautic.dealflow.config.webhook_secret_help',
            'required' => false,
            'attr' => [
                'autocomplete' => 'off',
            ],
        ]);

        $builder->add('dealflow_default_currency', ChoiceType::class, [
            'label' => 'Default Currency',
            'choices' => [
                'USD' => 'USD',
                'EUR' => 'EUR',
                'GBP' => 'GBP',
                'CAD' => 'CAD',
                'AUD' => 'AUD',
                'JPY' => 'JPY',
                'CHF' => 'CHF',
            ],
            'required' => false,
        ]);

        $builder->add('dealflow_items_per_page', IntegerType::class, [
            'label' => 'Items Per Page',
            'help' => 'Number of deals shown per page in list view.',
            'required' => false,
            'attr' => ['min' => 5, 'max' => 100],
        ]);

        $builder->add('dealflow_health_yellow_days', IntegerType::class, [
            'label' => 'Health Yellow Threshold (days)',
            'help' => 'Days since last update before a deal turns yellow.',
            'required' => false,
            'attr' => ['min' => 1],
        ]);

        $builder->add('dealflow_health_red_days', IntegerType::class, [
            'label' => 'Health Red Threshold (days)',
            'help' => 'Days since last update before a deal turns red.',
            'required' => false,
            'attr' => ['min' => 1],
        ]);

        $builder->add('dealflow_default_task_priority', ChoiceType::class, [
            'label' => 'Default Task Priority',
            'choices' => [
                'Normal' => 'normal',
                'High' => 'high',
                'Urgent' => 'urgent',
            ],
            'required' => false,
        ]);

        foreach (['dealflow_default_association_labels', 'dealflow_default_sources'] as $fieldName) {
            $builder->get($fieldName)->addModelTransformer(new CallbackTransformer(
                static function (mixed $value): string {
                    if (is_array($value)) {
                        return implode("\n", array_values(array_filter(array_map(
                            static fn (mixed $item): string => trim((string) $item),
                            $value
                        ))));
                    }

                    return trim((string) $value);
                },
                static function (mixed $value): array {
                    if (is_array($value)) {
                        return array_values(array_filter(array_map(
                            static fn (mixed $item): string => trim((string) $item),
                            $value
                        )));
                    }

                    $items = preg_split('/\r\n|\r|\n|,/', (string) $value) ?: [];

                    return array_values(array_filter(array_map(
                        static fn (string $item): string => trim($item),
                        $items
                    )));
                }
            ));
        }
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([]);
    }

    public function getBlockPrefix(): string
    {
        return 'dealflow_config';
    }
}
