<?php

namespace Aura\Forms\Http\Livewire;

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

class ViewForm extends Component
{
    use InputFields;
    use MediaFields;

    public $data;

    public $form;

    public $hide_form = false;

    public $model;

    public $questions = [];

    public Form $resource;

    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 $resource)
    {
        $this->resource = $resource;

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

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

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

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

    public function rules()
    {
        return Arr::dot([
            'form.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->resource);
        $this->validate();

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

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

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

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

        // dd($this->resource, $this->model->id, $this->submission->report_id);

        // ray($this->model)->blue();

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

        $this->dispatch('refreshComponent');

        // if (isset($this->form->fields['empty_form'])) {
        //     unset($this->form['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']);
        // }
    }
}
