<?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;

#[Layout('layouts.app')]
class TaskCalendar extends Component
{
    public ?Project $project = null;

    public $viewMode = 'dayGridMonth'; // dayGridMonth, timeGridWeek, timeGridDay, listWeek

    public $search = '';

    public $assigneeFilter = '';

    public $phaseFilter = '';

    public $priorityFilter = '';

    public $statusFilter = '';

    protected $queryString = [
        'viewMode' => ['except' => 'dayGridMonth'],
        'search' => ['except' => ''],
        'assigneeFilter' => ['except' => ''],
        'phaseFilter' => ['except' => ''],
        'priorityFilter' => ['except' => ''],
        'statusFilter' => ['except' => ''],
    ];

    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 refreshCalendar(): void
    {
        // Trigger re-render
    }

    public function render()
    {
        $user = Auth::user();
        $query = Task::with(['project', 'phase', 'assignee'])
            ->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) {
            $query->where('project_id', $this->project->id);
        }

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

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

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

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

        if ($this->statusFilter) {
            $query->where('status', $this->statusFilter);
        }

        $tasks = $query->get();

        // Transform tasks to FullCalendar events
        $events = $tasks->map(function ($task) {
            $start = $task->start_date ?? $task->due_date ?? $task->created_at->toDateString();
            $end = $task->due_date ?? $task->start_date;

            return [
                'id' => $task->id,
                'title' => $task->title,
                'start' => $start,
                'end' => $end ? $end->addDay()->toDateString() : null, // FullCalendar end is exclusive
                'url' => route('projects.tasks.show', [$task->project_id, $task->id]),
                'backgroundColor' => $task->priority_color,
                'borderColor' => $task->priority_color,
                'textColor' => '#ffffff',
                'extendedProps' => [
                    'status' => $task->status,
                    'statusLabel' => $task->status_label,
                    'priority' => $task->priority,
                    'priorityLabel' => $task->priority_label,
                    'project' => $task->project->name ?? '—',
                    'phase' => $task->phase->name ?? '—',
                    'assignee' => $task->assignee->name ?? 'Sin asignar',
                    'dueDate' => $task->due_date?->format('d/m/Y'),
                    'isOverdue' => $task->is_overdue,
                    'isDueToday' => $task->is_due_today,
                    'progress' => $task->progress,
                    'subtasksCount' => $task->subtasks->count(),
                    'completedSubtasksCount' => $task->subtasks->where('status', 'completed')->count(),
                ],
                'classNames' => [
                    'fc-task-'.$task->status,
                    $task->is_overdue ? 'fc-task-overdue' : '',
                    $task->is_due_today ? 'fc-task-due-today' : '',
                ],
            ];
        })->toArray();

        // 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-calendar', [
            'events' => json_encode($events),
            'assignees' => $assignees,
            'phases' => $phases,
            'statusOptions' => Task::statusOptions(),
            'priorityOptions' => Task::priorityOptions(),
        ]);
    }
}
