<?php

namespace Daylight\Core\Modules\FormBuilder\Livewire;

use Illuminate\Support\Str;
use Illuminate\View\View;
use Livewire\Attributes\Modelable;
use Livewire\Component;

class FormBuilder extends Component
{
    #[Modelable]
    public array $fields = [];

    public function mount(array $fields = []): void
    {
        $this->fields = $fields;
    }

    public function addField(string $type): void
    {
        $this->fields[] = $this->makeField($type);
    }

    public function addFieldAtPosition(string $type, int $position): void
    {
        $field = $this->makeField($type);

        array_splice($this->fields, $position, 0, [$field]);

        $this->fields = array_values($this->fields);
    }

    public function removeField(string $id): void
    {
        $this->fields = collect($this->fields)
            ->reject(fn (array $field) => $field['id'] === $id)
            ->values()
            ->toArray();
    }

    public function reorderFields(array $order): void
    {
        $reordered = [];

        foreach ($order as $id) {
            $field = collect($this->fields)->firstWhere('id', $id);
            if ($field) {
                $reordered[] = $field;
            }
        }

        $this->fields = array_values($reordered);
    }

    protected function makeField(string $type): array
    {
        return [
            'id' => 'fld_' . Str::random(8),
            'type' => $type,
            'label' => '',
            'placeholder' => '',
            'required' => false,
            'hide_label' => false,
            'checkbox_label' => '',
            'options' => '',
            'width' => 'full',
            'min' => null,
            'max' => null,
            'condition' => null,
        ];
    }

    public function render(): View
    {
        return view('daylight::livewire.form-builder.form-builder');
    }
}
