<?php

namespace Aura\Forms\Http\Livewire;

use Aura\Forms\Events\SubmissionCreated;
use Aura\Forms\Resources\Form;
use Aura\Forms\Resources\Submission;
use Eminiarts\Aura\Pipeline\AddIdsToFields;
use Eminiarts\Aura\Pipeline\ApplyParentConditionalLogic;
use Eminiarts\Aura\Pipeline\ApplyParentDisplayAttributes;
use Eminiarts\Aura\Pipeline\ApplyTabs;
use Eminiarts\Aura\Pipeline\BuildTreeFromFields;
use Eminiarts\Aura\Pipeline\FilterViewFields;
use Eminiarts\Aura\Pipeline\MapFields;
use Eminiarts\Aura\Traits\InputFields;
use Eminiarts\Aura\Traits\MediaFields;
use Illuminate\Pipeline\Pipeline;
use Illuminate\Support\Arr;
use Livewire\Component;

class ViewForm extends Component
{
    use InputFields;
    use MediaFields;

    public $data;

    public Form $form;

    public $hide_form = false;

    public $model;

    public $post;

    public $questions = [];

    public Submission $submission;

    public $url;

    protected $listeners = [
        'updateField' => 'updateField',
        'saveModel' => 'save',
        'refreshComponent' => '$refresh',
    ];

    public function getFields()
    {
        return $this->questions;
    }

    public function getFieldsProperty()
    {
        return $this->viewFields;
    }

    public function getViewFieldsProperty()
    {
        $pipes = [
            ApplyTabs::class,
            MapFields::class,
            AddIdsToFields::class,
            ApplyParentConditionalLogic::class,
            ApplyParentDisplayAttributes::class,
            FilterViewFields::class,
            BuildTreeFromFields::class,
        ];

        return $this->sendThroughPipeline(collect($this->questions), $pipes);
    }

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

        // Ensure that $this->model->questions is a string before decoding
        if (is_string($this->model->questions)) {
            $this->questions = json_decode($this->model->questions, true);
        } else {
            // Handle the case where $this->model->questions is not a string
            $this->questions = $this->model->questions;
        }

        if (optional($this)->submission) {
            $this->post['fields'] = json_decode($this->submission->fields['data'], true);
        }

        $this->url = request()->url();
    }

    public function render()
    {
        return view('forms::livewire.view-form')->layout('aura::components.layout.app');
    }

    public function rules()
    {
        return Arr::dot([
            'post.fields' => $this->validationRules(),
        ]);
    }

    public function sendThroughPipeline($fields, $pipes)
    {
        return app(Pipeline::class)
            ->send($fields)
            ->through($pipes)
            ->thenReturn();
    }

    public function submit()
    {
        //  dd('submit', $this->rules(), $this->post);
        $this->validate();

        // Get User Agent and IP
        // $this->post['fields']['user_agent'] = request()->userAgent();
        // $this->post['fields']['ip'] = request()->ip();
        // // get request Full URL
        // $this->post['fields']['url'] = $this->url;

        // dd($this->post['fields']);

        // remove user_agent, ip and url from fields
        unset($this->post['fields']['user_agent']);
        unset($this->post['fields']['ip']);
        unset($this->post['fields']['url']);

        // Update Submission
        if (optional($this)->submission) {
            $this->submission->update([
                'data' => $this->post['fields'],
            ]);
        } else {
            $this->submission = Submission::create([
                'form_id' => $this->form->id,
                'data' => $this->post['fields'],
                'user_agent' => request()->userAgent(),
                'ip' => request()->ip(),
                'url' => $this->url,
            ]);
        }
        $this->notify('Erfolgreich gespeichert.');

        event(new SubmissionCreated($this->submission));

        $this->emit('refreshComponent');

        // if (isset($this->form->fields['empty_form'])) {
        //     unset($this->post['fields']);
        // }

        // if (isset($this->form->fields['hide_form']) && $this->form->fields['hide_form']) {
        //     $this->hide_form = true;
        // }

        // if ($this->form->fields['success_action_type'] === 'message') {
        //     // Show success message
        //     $this->notify($this->form->fields['success_message']);
        // }
        //elseif ($this->form->fields['success_action_type'] === 'redirect') {
        //     // Redirect to success URL
        //     return redirect()->to($this->form->fields['success_redirect_url']);
        // }
    }
}
