<?php

namespace App\Http\Livewire\Posts;

use App\Models\Bank;
use App\Models\Organization;
use App\Models\User;
use Illuminate\Support\Facades\Storage;
use Livewire\Component;

class SelectAuthor extends Component
{
    public $search;
    public $searchResults = [];
    public $showDropdown = false;
    public $selectedId;
    public $selected = [];

    // Properties for receiving author data from parent
    public $authorId;
    public $authorModel;

    protected $listeners = [
        'resetForm',
        'authorExists'
    ];

    public function mount($authorId = null, $authorModel = null)
    {
        $this->authorId = $authorId;
        $this->authorModel = $authorModel;

        // If author data is provided, populate the selected data
        if ($this->authorId && $this->authorModel) {
            $this->populateAuthorData($this->authorId, $this->authorModel);
        }
    }

    private function populateAuthorData($authorId, $authorModel)
    {
        $this->selectedId = $authorId;
        $this->selected['id'] = $authorId;
        $this->selected['type'] = $authorModel;

        try {
            if ($authorModel == User::class) {
                $author = User::where('id', $authorId)->select('name', 'profile_photo_path')->firstOrFail();
                $description = '';
            } elseif ($authorModel == Organization::class) {
                $author = Organization::where('id', $authorId)->select('name', 'profile_photo_path')->firstOrFail();
                $description = __('Organization');
            } elseif ($authorModel == Bank::class) {
                $author = Bank::where('id', $authorId)->select('name', 'profile_photo_path')->firstOrFail();
                $description = __('Bank');
            } else {
                // Unknown author model type
                return;
            }

            $this->selected['name'] = $author->name;
            $this->selected['profile_photo_path'] = url(Storage::url($author->profile_photo_path));
            $this->selected['description'] = $description;
        } catch (\Exception) {
            // Silently fail if author data cannot be loaded
            $this->selectedId = null;
            $this->selected = [];
        }
    }

    public function inputBlur()
    {
        $this->dispatch('toAuthorValidation');
        $this->showDropdown = false;
        $this->search = '';
    }

    public function resetForm()
    {
        $this->reset();
    }

    /**
     * Populate dropdown when already author data exists
     *
     * @param  mixed $value
     * @return void
     */
    public function authorExists($value)
    {
        $this->selectedId = $value['author_id'];
        $this->selected['id'] = $value['author_id'];
        $this->selected['type'] = $value['author_model'];

        if ($value['author_model'] == User::class) {
            $author = User::where('id', $value['author_id'])->select('name', 'profile_photo_path')->firstOrFail();
            $description = '';
        } elseif ($value['author_model'] == Organization::class) {
            $author = Organization::where('id', $value['author_id'])->select('name', 'profile_photo_path')->firstOrFail();
            $description = __('Organization');
        } elseif ($value['author_model'] == Bank::class) {
            $author = Bank::where('id', $value['author_id'])->select('name', 'profile_photo_path')->firstOrFail();
            $description = __('Bank');
        }

        $this->selected['name'] = $author->name;
        $this->selected['profile_photo_path'] = url(Storage::url($author->profile_photo_path));
        $this->selected['description'] = $description;
    }


    public function authorSelected($value)
    {
        $this->selectedId = $value;
        $this->selected = collect($this->searchResults)->where('id', '=', $value)->first();
        $this->showDropdown = false;
        $this->search = '';
        $this->dispatch('authorSelected', $this->selected);
    }


    /**
     * updatedSearch: Search query users, organizations, and banks
     *
     * @param  mixed $newValue
     * @return void
     */
    public function updatedSearch()
    {
        $this->showDropdown = true;
        $search = $this->search;

        // Search Users
        $users = User::where('name', 'like', '%' . $search . '%')
            ->where('id', '!=', '1')        // Exclude Super-Admin user  //TODO: exclude all admin users by role
            ->select('id', 'name', 'profile_photo_path')
            ->get();
        $users = $users->map(function ($item) {
            return
            [
                'id' => $item['id'],
                'type' => User::class,
                'name' => $item['name'],
                'description' => '',
                'profile_photo_path' => url('/storage/' . $item['profile_photo_path'])
            ];
        });

        // Search Organizations
        $organizations = Organization::where('name', 'like', '%' . $search . '%')
            ->select('id', 'name', 'profile_photo_path')
            ->get();
        $organizations = $organizations->map(function ($item) {
            return
            [
                'id' => $item['id'],
                'type' => Organization::class,
                'name' => $item['name'],
                'description' => __('Organization'),
                'profile_photo_path' => url(Storage::url($item['profile_photo_path']))
            ];
        });

        // Search Banks
        $banks = Bank::where('name', 'like', '%' . $search . '%')
            ->select('id', 'name', 'profile_photo_path')
            ->get();
        $banks = $banks->map(function ($item) {
            return
            [
                'id' => $item['id'],
                'type' => Bank::class,
                'name' => $item['name'],
                'description' => __('Bank'),
                'profile_photo_path' => url(Storage::url($item['profile_photo_path']))
            ];
        });

        // Merge all results
        $merged = collect($users)->merge($organizations)->merge($banks);
        $response = $merged->take(6);
        $this->searchResults = $response;
    }

    public function removeSelectedProfile()
    {
        $this->selectedId = null;
        $this->selected = [];
        $this->dispatch('authorSelected', ['id' => null, 'type' => null]);
    }


    public function render()
    {
        return view('livewire.posts.select-author');
    }
}