<?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'];

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

        $this->emit('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';

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

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

        $this->questions = json_decode($this->model->questions, true);
    }

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

    public function removeQuestion($slug)
    {
        // dd($slug, $this->questions);
        // get the index of the question with the slug $slug
        $index = array_search($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->emit('updateField', ['slug' => $this->field['slug'], 'value' => json_encode($this->questions)]);
    }

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

    public function reorder($ids)
    {
        // dd($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();

        // dd($ids, $questions);

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

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

    public function save()
    {
        // dd('save', $this->model->toArray());
        $this->validate();

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

        $this->emit('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)
    {
        dd('hi');
        // $this->emit('openSlideOver', 'edit-question', ['model' => $questionId]);
    }

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