<?php

namespace App\Components\PensionCase;

use App\Models\PensionCase\PensionCase;
use App\Models\PensionCase\PensionCaseComment;
use App\Services\PensionCaseService;
use Livewire\Component;

class CommentManager extends Component {
    public PensionCase $pensionCase;
    public string $newComment = '';

    public ?int $editingId = null;
    public string $editingText = '';

    protected function rules(): array {
        return [
            'newComment'  => 'required|string|min:1|max:10000',
            'editingText' => 'required|string|min:1|max:10000',
        ];
    }

    public function addComment(PensionCaseService $service): void {
        $this->validateOnly('newComment');

        $service->addComment($this->pensionCase, $this->newComment);

        $this->newComment = '';
        $this->dispatch('toast', title: 'Comment added', type: 'success');
    }

    public function startEdit(int $id): void {
        $comment = PensionCaseComment::where('pension_case_id', $this->pensionCase->id)->findOrFail($id);

        $this->editingId = $comment->id;
        $this->editingText = $comment->comment_text;
    }

    public function cancelEdit(): void {
        $this->editingId = null;
        $this->editingText = '';
    }

    public function saveEdit(): void {
        $this->validateOnly('editingText');

        if (!$this->editingId) {
            return;
        }

        $comment = PensionCaseComment::where('pension_case_id', $this->pensionCase->id)->findOrFail($this->editingId);
        $comment->update(['comment_text' => $this->editingText]);

        $this->cancelEdit();
        $this->dispatch('toast', title: 'Comment updated', type: 'success');
    }

    public function deleteComment(int $id): void {
        $comment = PensionCaseComment::where('pension_case_id', $this->pensionCase->id)->findOrFail($id);
        $comment->delete();

        $this->dispatch('toast', title: 'Comment deleted', type: 'success');
    }

    public function render() {
        $comments = $this->pensionCase->comments()->with('author')->get();
        return view('components.pension-case.comment-manager', compact('comments'));
    }
}
