<?php

namespace App\Livewire\Tasks;

use App\Models\Comment;
use App\Models\Project;
use App\Models\Task;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Livewire\Attributes\Layout;
use Livewire\Component;
use Livewire\WithFileUploads;

#[Layout('layouts.app')]
class TaskDetail extends Component
{
    use WithFileUploads;

    public Task $task;

    public ?Project $project = null;

    // Comment form
    public $commentBody = '';

    public $editingCommentId = null;

    public $editingCommentBody = '';

    // Subtask form
    public $subtaskTitle = '';

    protected $listeners = ['tasksChanged' => '$refresh', 'commentAdded' => '$refresh', 'subtaskAdded' => '$refresh'];

    public function mount(Task $task): void
    {
        $this->task = $task->load(['project', 'phase', 'assignee', 'creator', 'completer', 'subtasks', 'media', 'comments.user', 'comments.replies.user']);
        $this->project = $this->task->project;

        abort_unless(Auth::user()->can('view', $this->task), 403);
    }

    public function addComment(): void
    {
        $this->validate(['commentBody' => 'required|string|max:5000']);

        $this->task->comments()->create([
            'user_id' => Auth::id(),
            'body' => $this->commentBody,
        ]);

        $this->commentBody = '';
        $this->dispatch('commentAdded');
        $this->dispatch('tasksChanged');
    }

    public function startEditComment($commentId): void
    {
        $comment = $this->task->comments()->find($commentId);
        if ($comment && $comment->user_id === Auth::id()) {
            $this->editingCommentId = $commentId;
            $this->editingCommentBody = $comment->body;
        }
    }

    public function saveEditComment(): void
    {
        $this->validate(['editingCommentBody' => 'required|string|max:5000']);

        $comment = Comment::find($this->editingCommentId);
        if ($comment && $comment->user_id === Auth::id()) {
            $comment->update(['body' => $this->editingCommentBody]);
        }

        $this->editingCommentId = null;
        $this->editingCommentBody = '';
        $this->dispatch('commentAdded');
    }

    public function cancelEditComment(): void
    {
        $this->editingCommentId = null;
        $this->editingCommentBody = '';
    }

    public function deleteComment($commentId): void
    {
        $comment = Comment::find($commentId);
        if ($comment && ($comment->user_id === Auth::id() || Auth::user()->can('manage all tasks'))) {
            $comment->delete();
            $this->dispatch('commentAdded');
        }
    }

    public function addSubtask(): void
    {
        $this->validate(['subtaskTitle' => 'required|string|max:255']);

        $maxOrder = $this->task->subtasks()->max('order') ?? 0;

        $this->task->subtasks()->create([
            'title' => $this->subtaskTitle,
            'status' => 'pending',
            'priority' => 'medium',
            'project_id' => $this->task->project_id,
            'phase_id' => $this->task->phase_id,
            'parent_task_id' => $this->task->id,
            'created_by' => Auth::id(),
            'order' => $maxOrder + 1,
            'uuid' => Str::uuid(),
        ]);

        $this->subtaskTitle = '';
        $this->dispatch('subtaskAdded');
        $this->dispatch('tasksChanged');
    }

    public function updateSubtaskStatus(Task $subtask, string $status): void
    {
        abort_unless(Auth::user()->can('update', $subtask), 403);

        $data = ['status' => $status];
        if ($status === 'completed') {
            $data['completed_at'] = now();
            $data['completed_by'] = Auth::id();
        } elseif ($subtask->status === 'completed') {
            $data['completed_at'] = null;
            $data['completed_by'] = null;
        }

        $subtask->update($data);
        $this->dispatch('tasksChanged');
    }

    public function deleteSubtask(Task $subtask): void
    {
        abort_unless(Auth::user()->can('delete', $subtask), 403);
        $subtask->delete();
        $this->dispatch('tasksChanged');
    }

    public function changeStatus(string $status): void
    {
        abort_unless(Auth::user()->can('update', $this->task), 403);

        $oldStatus = $this->task->status;
        $data = ['status' => $status];

        if ($oldStatus !== 'completed' && $status === 'completed') {
            $data['completed_at'] = now();
            $data['completed_by'] = Auth::id();
        } elseif ($oldStatus === 'completed' && $status !== 'completed') {
            $data['completed_at'] = null;
            $data['completed_by'] = null;
        }

        $this->task->update($data);
        $this->task->refresh();
        $this->dispatch('tasksChanged');
    }

    public function render()
    {
        $assignees = User::whereHas('assignedTasks', function ($q) {
            if ($this->project) {
                $q->where('project_id', $this->project->id);
            }
        })->get(['id', 'name']);

        return view('livewire.tasks.task-detail', [
            'assignees' => $assignees,
            'statusOptions' => Task::statusOptions(),
            'priorityOptions' => Task::priorityOptions(),
        ]);
    }
}
