<?php

namespace Aura\Forms\Http\Livewire;

use Aura\Forms\Resources\Form;
use Illuminate\Support\Str;
use Livewire\Component;

class ActionsField extends Component
{
    public $actions = [];

    public Form $form;

    public $model;

    protected $listeners = ['refreshComponent' => '$refresh', 'updatedQuestion' => 'refresh', 'saveFormField' => 'saveFormField'];

    // rules
    protected $rules = [
    ];

    public function addQuestion()
    {
        $count = count($this->actions);

        $this->actions[] = [
            '_id' => rand(1, 1000),
            'name' => 'Question '.$count + 1,
            'slug' => 'question-'.$count + 1,
            'type' => 'Aura\\Forms\\Fields\\Text',
            'options' => [],
            'validation' => '',
            'conditional_logic' => [],
            'style' => [
                'width' => '100',
            ],
        ];

        $this->model->actions = $this->actions;
        $this->save();
    }

    public function mount($model)
    {
        $this->form = $model;
        $this->model = $model;
        $this->actions = $this->model->actions;
    }

    public function refresh()
    {
        // $this->operations = $this->flow->fresh()->operations;
        $this->dispatch('refreshComponent');
        $this->save();
    }

    public function removeQuestion($index)
    {
        unset($this->actions[$index]);
    }

    public function render()
    {
        return view('forms::livewire.actions-field');
    }

    public function reorder($ids)
    {
        $ids = collect($ids)->map(function ($id) {
            return (int) Str::after($id, 'field_');
        });

        $actions = $this->actions;

        // take $actions array and set _id as key
        $actions = collect($actions)->keyBy('_id')->toArray();

        // dd($ids, $actions);

        $this->actions = $ids->map(function ($id) use ($actions) {
            return $actions[$id];
        })->toArray();

        $this->model->actions = $this->actions;
        $this->save();
    }

    public function save()
    {
        $this->validate();

        $this->model->save();

        $this->dispatch('refreshComponent');
    }

    public function saveFormField($data)
    {
        // get the actions form the form and update the question with the slug $data['slug'] with the new value $data['value']
        $actions = collect($this->actions);

        $question = $actions->where('slug', $data['slug'])->first();

        $question = $data['value'];

        $index = $actions->search(function ($item) use ($data) {
            return $item['slug'] == $data['slug'];
        });

        $this->actions[$index] = $data['value'];

        $this->model->actions = $this->actions;
        $this->save();
    }

    public function selectOperation($questionId)
    {
        // $this->dispatch('openSlideOver', 'edit-question', ['model' => $questionId]);
    }
}
