<?php

namespace App\Components;

use App\Interface\NoteOwner;
use App\Models\Note;
use App\Services\NoteService;
use App\Services\WipService;
use App\Trait\SupportsWip;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;
use Livewire\WithPagination;

class NoteManager extends Component
{
    use AuthorizesRequests, WithPagination, SupportsWip;

    public NoteOwner $owner;
    public bool $show = false;
    public string $note = '';
    public $perPage = 10;
    public bool $primary = false;

    protected $paginationTheme = 'bootstrap';

    public function mount(NoteOwner $owner)
    {
        $this->owner = $owner;
        $this->show = false;
    }

    public function showAddNote()
    {
        $this->show = true;
        $this->startWipTimer();
    }

    public function addNote(NoteService $noteService, WipService $wipService)
    {
        $this->authorize('notes.create');

        $data = $this->validate([
            'note' => 'required|string|min:1',
        ]);

        $this->stopWipTimer();

        $note = $noteService->addNote($this->owner, $data['note'], $this->primary);

        $wipService->create([
            'client_id' => $this->resolveWipClientId(),
            'claim_id' => $this->resolveWipClaimId(),    
            ...$this->getWipPayload('note'),
            'description' => $this->wipDescription ?: 'Added note',
        ], $note);

        $this->resetWip();
        $this->resetPage();
        $this->hideAddNote();
    }

    public function hideAddNote()
    {
        $this->show = false;
        $this->reset('note');
    }

    public function deleteNote(NoteService $noteService, int $id)
    {
        $this->authorize('notes.delete');

        $note = Note::findOrFail($id);

        $noteService->deleteNote($note);

        $this->resetPage();
    }

    public function render()
    {
        $builder = $this->primary ? $this->owner->keyInfo() : $this->owner->notes()->where('is_primary', false);

        return view('components.note-manager', [
            'notes' => $builder->paginate($this->perPage),
        ]);
    }
}