<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\DailyWorkLog;
use App\Models\Task;
use App\Models\TimeLog;
use App\Services\TimeTrackingService;
use App\Traits\LogsActivity;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class TimeTrackingController extends Controller
{
    use LogsActivity;

    public function __construct(private readonly TimeTrackingService $timeTrackingService)
    {
    }

    public function employeeDashboard(Request $request): View
    {
        $userId = auth()->id();

        return view('employee.time-tracking.dashboard', [
            'tasks' => Task::orderBy('title')->get(),
            'activeLog' => TimeLog::with('task')
                ->where('user_id', $userId)
                ->whereIn('status', ['running', 'paused'])
                ->latest()
                ->first(),
            'dailyLogs' => DailyWorkLog::where('user_id', $userId)
                ->latest('work_date')
                ->take(14)
                ->get(),
            'todaySummary' => DailyWorkLog::firstWhere(['user_id' => $userId, 'work_date' => now()->toDateString()]),
        ]);
    }

    public function adminDashboard(Request $request): View
    {
        return view('admin.time-tracking.dashboard', [
            'dailyLogs' => DailyWorkLog::with('user')->latest('work_date')->paginate(20),
            'runningLogs' => TimeLog::with(['user', 'task'])->where('status', 'running')->latest()->get(),
        ]);
    }

    public function start(Request $request): JsonResponse
    {
        $data = $request->validate([
            'task_id' => 'required|exists:tasks,id',
            'manual_notes' => 'nullable|string|max:2000',
        ]);

        $timeLog = $this->timeTrackingService->startTimer(auth()->id(), (int) $data['task_id'], $data['manual_notes'] ?? null);
        $this->logActivity('timer_start', 'time_tracking', 'Timer started', ['time_log_id' => $timeLog->id]);

        if ($request->wantsJson()) {
            return response()->json(['success' => true, 'time_log' => $timeLog]);
        }
        return response()->json(['message' => 'Timer started.', 'time_log' => $timeLog]);
    }

    public function pause(Request $request, TimeLog $timeLog): JsonResponse
    {
        abort_unless($timeLog->user_id === auth()->id(), 403);

        $updated = $this->timeTrackingService->pauseTimer($timeLog);
        $this->logActivity('timer_pause', 'time_tracking', 'Timer paused', ['time_log_id' => $updated->id]);

        return response()->json(['success' => true, 'message' => 'Timer paused.', 'time_log' => $updated]);
    }

    public function resume(Request $request, TimeLog $timeLog): JsonResponse
    {
        abort_unless($timeLog->user_id === auth()->id(), 403);

        $updated = $this->timeTrackingService->resumeTimer($timeLog);
        $this->logActivity('timer_resume', 'time_tracking', 'Timer resumed', ['time_log_id' => $updated->id]);

        return response()->json(['success' => true, 'message' => 'Timer resumed.', 'time_log' => $updated]);
    }

    public function stop(Request $request, TimeLog $timeLog): JsonResponse
    {
        abort_unless($timeLog->user_id === auth()->id(), 403);

        $updated = $this->timeTrackingService->stopTimer($timeLog);
        $this->logActivity('timer_stop', 'time_tracking', 'Timer stopped', ['time_log_id' => $updated->id]);

        return response()->json(['success' => true, 'message' => 'Timer stopped.', 'time_log' => $updated]);
    }

    public function idle(Request $request): JsonResponse
    {
        $data = $request->validate([
            'time_log_id' => 'required|exists:time_logs,id',
            'idle_seconds' => 'required|integer|min:1|max:86400',
            'reason' => 'nullable|string|max:255',
        ]);

        $idle = $this->timeTrackingService->logIdle(auth()->id(), (int) $data['time_log_id'], (int) $data['idle_seconds'], $data['reason'] ?? null);
        $this->logActivity('idle_log', 'time_tracking', 'Idle time logged', ['idle_log_id' => $idle->id]);

        return response()->json(['message' => 'Idle logged.', 'idle_log' => $idle]);
    }

    public function manualNote(Request $request, TimeLog $timeLog): RedirectResponse
    {
        abort_unless($timeLog->user_id === auth()->id(), 403);

        $data = $request->validate(['manual_notes' => 'nullable|string|max:2000']);
        $timeLog->update(['manual_notes' => $data['manual_notes']]);
        $this->logActivity('note_update', 'time_tracking', 'Manual note updated', ['time_log_id' => $timeLog->id]);

        return back()->with('success', 'Manual note updated.');
    }
}
