<?php

namespace Aura\Forms\Http\Livewire;

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

class QuestionsField extends Component
{
    public $field;

    public Form $form;

    public $model;

    public $questions = [];

    public $trigger;

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

    public function addQuestion()
    {
        if (! $this->questions) {
            $this->questions = [];
        }

        $count = count($this->questions);

        $this->questions[] = [
            '_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->dispatch('updateField', ['slug' => $this->field['slug'], 'value' => json_encode($this->questions)]);

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

    public function duplicateQuestion($id, $slug)
    {
        $fields = collect($this->questions);

        $field = $fields->where('slug', $slug)->first();

        $field['slug'] = $field['slug'].'_'.Str::random(4);
        $field['name'] = $field['name'].' Copy';

        do {
            $field['_id'] = rand(1, 10000);
        } while ($fields->pluck('_id')->contains($field['_id']));

        // get index of the field
        $index = $fields->search(function ($item) use ($slug) {
            return $item['slug'] == $slug;
        });

        // duplicate field in at index of the field + 1
        $fields->splice($index + 1, 0, [$field]);

        $fields = $fields->toArray();

        $this->questions = $fields;

        $this->dispatch('updateField', ['slug' => $this->field['slug'], 'value' => json_encode($this->questions)]);
    }

    public function fieldUpdated()
    {
        $this->dispatch('saveModel');
    }

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

        if (is_string($this->model->questions)) {
            $this->questions = json_decode($this->model->questions, true);
        } else {
            $this->questions = $this->model->questions;
        }
    }

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

    public function removeQuestion($slug)
    {
        // get the index of the question with the slug $slug
        $index = array_search($slug['slug'], array_column($this->questions, 'slug'));
        // delete the question from the array
        unset($this->questions[$index]);

        // reindex the array
        $this->questions = array_values($this->questions);

        // this emit update field with array slug and value
        $this->dispatch('updateField', ['slug' => $this->field['slug'], 'value' => json_encode($this->questions)]);
    }

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

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

        $questions = $this->questions;

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

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

        $this->dispatch('updateField', ['slug' => $this->field['slug'], 'value' => json_encode($this->questions)]);
    }

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

        $this->dispatch('updateField', ['slug' => $this->field['slug'], 'value' => json_encode($this->questions)]);

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

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

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

        $question = $data['value'];

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

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

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

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

    protected function rules()
    {
        return [
            'questions.*.name' => 'required|string',
            'questions.*.type' => 'required|string',
        ];
    }
}
