<?php

namespace App\Livewire\Tasks;

use App\Models\Project;
use App\Models\Task;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Livewire\Attributes\Layout;
use Livewire\Attributes\On;
use Livewire\Component;
use Livewire\WithPagination;

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

    public ?Project $project = null;

    public $search = '';

    public $assigneeFilter = '';

    public $phaseFilter = '';

    public $priorityFilter = '';

    public $showOverdueOnly = false;

    public $perPage = 50;

    protected $queryString = [
        'search' => ['except' => ''],
        'assigneeFilter' => ['except' => ''],
        'phaseFilter' => ['except' => ''],
        'priorityFilter' => ['except' => ''],
        'showOverdueOnly' => ['except' => false],
    ];

    public function mount(?Project $project = null): void
    {
        $this->project = $project;

        if ($project) {
            abort_unless($this->canAccessProject() && Auth::user()->can('view tasks'), 403);
        } else {
            abort_unless(Auth::user()->can('view tasks'), 403);
        }
    }

    private function canAccessProject(): bool
    {
        $user = Auth::user();

        return $user->can('manage all')
            || ($this->project && $this->project->users()->where('user_id', $user->id)->exists());
    }

    #[On('tasksChanged')]
    public function refreshTasks(): void
    {
        // Trigger re-render
    }

    #[On('update-task-status')]
    public function updateTaskStatus(Task $task, string $status): void
    {
        abort_unless(Auth::user()->can('update', $task), 403);

        $oldStatus = $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;
        }

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

    public function updateTaskOrder(int $taskId, int $order): void
    {
        $task = Task::find($taskId);
        if ($task && Auth::user()->can('update', $task)) {
            $task->update(['order' => $order]);
        }
    }

    public function resetFilters(): void
    {
        $this->reset(['search', 'assigneeFilter', 'phaseFilter', 'priorityFilter', 'showOverdueOnly']);
        $this->resetPage();
    }

    public function render()
    {
        $user = Auth::user();
        $baseQuery = Task::with(['project', 'phase', 'assignee', 'creator', 'subtasks'])
            ->where(function ($q) use ($user) {
                if (! $user->can('manage all tasks')) {
                    $q->whereHas('project', function ($sub) use ($user) {
                        $sub->whereHas('users', function ($sub2) use ($user) {
                            $sub2->where('user_id', $user->id);
                        });
                    });
                }
            });

        if ($this->project) {
            $baseQuery->where('project_id', $this->project->id);
        }

        if ($this->search) {
            $baseQuery->where(function ($q) {
                $q->where('title', 'like', '%'.$this->search.'%')
                    ->orWhere('description', 'like', '%'.$this->search.'%');
            });
        }

        if ($this->assigneeFilter) {
            $baseQuery->where('assigned_to', $this->assigneeFilter);
        }

        if ($this->phaseFilter) {
            $baseQuery->where('phase_id', $this->phaseFilter);
        }

        if ($this->priorityFilter) {
            $baseQuery->where('priority', $this->priorityFilter);
        }

        if ($this->showOverdueOnly) {
            $baseQuery->overdue();
        }

        // Get tasks grouped by status
        $statuses = ['pending', 'in_progress', 'completed', 'cancelled'];
        $columns = [];

        foreach ($statuses as $status) {
            $query = clone $baseQuery;
            $query->where('status', $status)
                ->orderBy('order')
                ->orderBy('created_at', 'desc');

            $tasks = $query->get();

            $columns[$status] = [
                'label' => Task::statusOptions()[$status],
                'color' => $this->getStatusColor($status),
                'tasks' => $tasks,
                'count' => $tasks->count(),
            ];
        }

        // Filter options
        $assignees = User::whereHas('assignedTasks', function ($q) use ($user) {
            if (! $user->can('manage all tasks')) {
                $q->whereHas('project', function ($sub) use ($user) {
                    $sub->whereHas('users', function ($sub2) use ($user) {
                        $sub2->where('user_id', $user->id);
                    });
                });
            }
        })->get(['id', 'name']);

        $phases = $this->project
            ? $this->project->phases()->get(['id', 'name'])
            : collect();

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

    private function getStatusColor(string $status): string
    {
        return match ($status) {
            'pending' => '#6b7280', // gray
            'in_progress' => '#3b82f6', // blue
            'completed' => '#10b981', // green
            'cancelled' => '#ef4444', // red
            default => '#6b7280',
        };
    }
}
