<?php

namespace App\Components\WillsCase;

use App\Models\WillsCase\WillsCase;
use App\Models\WillsCase\WillsCaseComment;
use Livewire\Component;

class CommentManager extends Component {
    public WillsCase $willsCase;
    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(): void {
        $this->validateOnly('newComment');

        WillsCaseComment::create([
            'wills_case_id'      => $this->willsCase->id,
            'comment_created_by' => auth()->id(),
            'comment_created_at' => now(),
            'comment_text'       => $this->newComment,
        ]);

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

    public function startEdit(int $id): void {
        $comment = WillsCaseComment::where('wills_case_id', $this->willsCase->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 = WillsCaseComment::where('wills_case_id', $this->willsCase->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 = WillsCaseComment::where('wills_case_id', $this->willsCase->id)->findOrFail($id);
        $comment->delete();

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

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