<?php

declare(strict_types=1);

namespace App\Framework\LiveComponents\FormBuilder;

use App\Framework\View\FormBuilder;
use App\Framework\View\ValueObjects\FormElement;

/**
 * LiveComponent-aware FormBuilder extension
 *
 * Erweitert den bestehenden FormBuilder mit LiveComponent-spezifischen Features:
 * - Automatische data-live-action Attribute
 * - Automatische Debounce-Konfiguration
 * - Multi-step Form Support
 */
final readonly class LiveFormBuilder
{
    public function __construct(
        private FormBuilder $formBuilder
    ) {
    }

    public static function create(): self
    {
        return new self(FormBuilder::create('', 'post'));
    }

    /**
     * Add text input with automatic live updates
     */
    public function addLiveTextInput(
        string $name,
        string $value = '',
        string $label = '',
        int $debounceMs = 300
    ): self {
        $elements = [];

        if ($label) {
            $elements[] = FormElement::label($label, $name);
        }

        $input = FormElement::textInput($name, $value)
            ->withId($name)
            ->withAttribute('data-live-action', 'updateField')
            ->withAttribute('data-live-debounce', (string) $debounceMs);

        $elements[] = $input;

        $newFormBuilder = $this->formBuilder;
        foreach ($elements as $element) {
            $newFormBuilder = $newFormBuilder->addElement($element);
        }

        return new self($newFormBuilder);
    }

    /**
     * Add email input with automatic live updates
     */
    public function addLiveEmailInput(
        string $name,
        string $value = '',
        string $label = '',
        int $debounceMs = 300
    ): self {
        $elements = [];

        if ($label) {
            $elements[] = FormElement::label($label, $name);
        }

        $input = FormElement::emailInput($name, $value)
            ->withId($name)
            ->withRequired()
            ->withAttribute('data-live-action', 'updateField')
            ->withAttribute('data-live-debounce', (string) $debounceMs);

        $elements[] = $input;

        $newFormBuilder = $this->formBuilder;
        foreach ($elements as $element) {
            $newFormBuilder = $newFormBuilder->addElement($element);
        }

        return new self($newFormBuilder);
    }

    /**
     * Add radio button group with live updates
     */
    public function addLiveRadioGroup(
        string $name,
        array $options,
        string $selectedValue = '',
        string $label = ''
    ): self {
        $elements = [];

        if ($label) {
            $elements[] = FormElement::label($label);
        }

        foreach ($options as $value => $optionLabel) {
            $radioId = "{$name}_{$value}";
            $checked = $value === $selectedValue;

            $radio = FormElement::input('radio', $name, $value)
                ->withId($radioId)
                ->withAttribute('data-live-action', 'updateField');

            if ($checked) {
                $radio = $radio->withAttribute('checked', null);
            }

            $elements[] = FormElement::label($optionLabel, $radioId)
                ->withClass('radio-label');
        }

        $newFormBuilder = $this->formBuilder;
        foreach ($elements as $element) {
            $newFormBuilder = $newFormBuilder->addElement($element);
        }

        return new self($newFormBuilder);
    }

    /**
     * Add checkbox with live updates
     */
    public function addLiveCheckbox(
        string $name,
        bool $checked = false,
        string $label = ''
    ): self {
        $checkbox = FormElement::input('checkbox', $name, 'yes')
            ->withId($name)
            ->withAttribute('data-live-action', 'updateField');

        if ($checked) {
            $checkbox = $checkbox->withAttribute('checked', null);
        }

        $elements = [];
        if ($label) {
            $elements[] = FormElement::label($label, $name)
                ->withClass('checkbox-label');
        }
        $elements[] = $checkbox;

        $newFormBuilder = $this->formBuilder;
        foreach ($elements as $element) {
            $newFormBuilder = $newFormBuilder->addElement($element);
        }

        return new self($newFormBuilder);
    }

    /**
     * Add select dropdown with live updates
     */
    public function addLiveSelect(
        string $name,
        array $options,
        string $selectedValue = '',
        string $label = ''
    ): self {
        $elements = [];

        if ($label) {
            $elements[] = FormElement::label($label, $name);
        }

        $optionsHtml = '';
        foreach ($options as $value => $optionLabel) {
            $selected = $value === $selectedValue ? ' selected' : '';
            $optionsHtml .= "<option value=\"{$value}\"{$selected}>{$optionLabel}</option>\n";
        }

        $select = new FormElement(
            \App\Framework\View\ValueObjects\HtmlTag::select(),
            \App\Framework\View\ValueObjects\HtmlAttributes::empty()
                ->withId($name)
                ->withName($name)
                ->with('data-live-action', 'updateField'),
            $optionsHtml
        );

        $elements[] = $select;

        $newFormBuilder = $this->formBuilder;
        foreach ($elements as $element) {
            $newFormBuilder = $newFormBuilder->addElement($element);
        }

        return new self($newFormBuilder);
    }

    /**
     * Add navigation button (Previous/Next/Submit)
     */
    public function addNavigationButton(
        string $action,
        string $text,
        string $buttonClass = 'btn'
    ): self {
        $button = FormElement::button($text, 'button')
            ->withAttribute('data-live-action', $action)
            ->withClass($buttonClass);

        return new self($this->formBuilder->addElement($button));
    }

    /**
     * Add submit button with live action
     */
    public function addLiveSubmitButton(string $text = 'Submit', string $action = 'submit'): self
    {
        $button = FormElement::button($text, 'button')
            ->withAttribute('data-live-action', $action)
            ->withClass('btn btn-primary');

        return new self($this->formBuilder->addElement($button));
    }

    /**
     * Add previous step button
     */
    public function addPreviousButton(string $text = '← Zurück'): self
    {
        return $this->addNavigationButton('previousStep', $text, 'btn btn-secondary');
    }

    /**
     * Add next step button
     */
    public function addNextButton(string $text = 'Weiter →'): self
    {
        return $this->addNavigationButton('nextStep', $text, 'btn btn-primary');
    }

    /**
     * Add any element from the base FormBuilder
     */
    public function addElement(\App\Framework\View\ValueObjects\HtmlElement $element): self
    {
        return new self($this->formBuilder->addElement($element));
    }

    /**
     * Add raw HTML
     */
    public function addHtml(string $html): self
    {
        $element = new \App\Framework\View\ValueObjects\HtmlElement(
            \App\Framework\View\ValueObjects\HtmlTag::div(),
            \App\Framework\View\ValueObjects\HtmlAttributes::empty(),
            $html
        );

        return new self($this->formBuilder->addElement($element));
    }

    /**
     * Build the form HTML
     */
    public function build(): string
    {
        return $this->formBuilder->build();
    }

    /**
     * Get the underlying FormBuilder for advanced customization
     */
    public function getFormBuilder(): FormBuilder
    {
        return $this->formBuilder;
    }

    public function __toString(): string
    {
        return $this->build();
    }
}
