<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Course;
use App\Models\ExamAttempt;
use App\Models\StudyGroup;
use App\Models\StudyGroupMember;
use App\Models\StudyLog;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\View\View;

class AnalyticsController extends Controller
{
    public function index(Request $request): View|JsonResponse
    {
        $user = $request->user();

        if ($request->boolean('ajax')) {
            return $this->analyticsData($request);
        }

        $courses = Course::where('is_active', true)
            ->orderBy('sort_order')
            ->orderBy('name')
            ->get();

        $groups = StudyGroup::whereHas('members', function ($query) use ($user) {
                $query->where('user_id', $user->id)
                    ->where('status', 'active');
            })
            ->orderBy('name')
            ->get();

        return view('user.analytics.index', compact('courses', 'groups'));
    }

    public function storeStudyLog(Request $request): RedirectResponse|JsonResponse
    {
        $validated = $request->validate([
            'course_id' => ['nullable', 'exists:courses,id'],
            'study_group_id' => ['nullable', 'exists:study_groups,id'],
            'study_date' => ['required', 'date'],
            'minutes' => ['required', 'integer', 'min:1', 'max:1440'],
            'type' => ['required', 'in:personal,group'],
            'title' => ['nullable', 'string', 'max:255'],
            'notes' => ['nullable', 'string'],
        ]);

        if ($validated['type'] === 'group' && empty($validated['study_group_id'])) {
            return response()->json([
                'message' => 'Please select a study group for group study log.',
            ], 422);
        }

        if (!empty($validated['study_group_id'])) {
            $isMember = StudyGroupMember::where('study_group_id', $validated['study_group_id'])
                ->where('user_id', $request->user()->id)
                ->where('status', 'active')
                ->exists();

            abort_unless($isMember, 403);
        }

        StudyLog::create([
            'user_id' => $request->user()->id,
            ...$validated,
        ]);

        return response()->json([
            'status' => true,
            'message' => 'Study log saved successfully.',
        ]);
    }

    public function createGroup(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:120'],
            'description' => ['nullable', 'string'],
            'visibility' => ['required', 'in:private,public'],
        ]);

        $group = DB::transaction(function () use ($request, $validated) {
            $group = StudyGroup::create([
                'owner_id' => $request->user()->id,
                'name' => $validated['name'],
                'slug' => Str::slug($validated['name']) . '-' . Str::lower(Str::random(6)),
                'description' => $validated['description'] ?? null,
                'visibility' => $validated['visibility'],
                'is_active' => true,
            ]);

            StudyGroupMember::create([
                'study_group_id' => $group->id,
                'user_id' => $request->user()->id,
                'role' => 'owner',
                'status' => 'active',
                'joined_at' => now(),
            ]);

            return $group;
        });

        return response()->json([
            'status' => true,
            'message' => 'Study group created successfully.',
            'group' => [
                'id' => $group->id,
                'name' => $group->name,
            ],
        ]);
    }

    private function analyticsData(Request $request): JsonResponse
    {
        $user = $request->user();

        $attempts = ExamAttempt::with('exam.course')
            ->where('user_id', $user->id)
            ->where('status', 'completed')
            ->latest()
            ->limit(20)
            ->get()
            ->reverse()
            ->values();

        $studyLogs = StudyLog::with(['course', 'group'])
            ->where('user_id', $user->id)
            ->latest('study_date')
            ->limit(20)
            ->get();

        $dailyStudy = StudyLog::where('user_id', $user->id)
            ->selectRaw('study_date, SUM(minutes) as total_minutes')
            ->whereDate('study_date', '>=', now()->subDays(14))
            ->groupBy('study_date')
            ->orderBy('study_date')
            ->get();

        $coursePerformance = ExamAttempt::query()
            ->join('exams', 'exam_attempts.exam_id', '=', 'exams.id')
            ->leftJoin('courses', 'exams.course_id', '=', 'courses.id')
            ->where('exam_attempts.user_id', $user->id)
            ->where('exam_attempts.status', 'completed')
            ->selectRaw('COALESCE(courses.name, "Full Exam") as course_name, AVG(exam_attempts.percentage) as avg_percentage')
            ->groupBy('course_name')
            ->orderBy('course_name')
            ->get();

        return response()->json([
            'summary' => [
                'completed_attempts' => ExamAttempt::where('user_id', $user->id)->where('status', 'completed')->count(),
                'average_score' => round((float) ExamAttempt::where('user_id', $user->id)->where('status', 'completed')->avg('percentage'), 2),
                'study_minutes' => StudyLog::where('user_id', $user->id)->sum('minutes'),
                'study_groups' => StudyGroupMember::where('user_id', $user->id)->where('status', 'active')->count(),
            ],
            'attempt_chart' => [
                'labels' => $attempts->map(fn ($attempt) => $attempt->created_at->format('M d'))->values(),
                'scores' => $attempts->map(fn ($attempt) => (float) $attempt->percentage)->values(),
            ],
            'study_chart' => [
                'labels' => $dailyStudy->map(fn ($log) => date('M d', strtotime($log->study_date)))->values(),
                'minutes' => $dailyStudy->map(fn ($log) => (int) $log->total_minutes)->values(),
            ],
            'course_chart' => [
                'labels' => $coursePerformance->pluck('course_name')->values(),
                'scores' => $coursePerformance->map(fn ($item) => round((float) $item->avg_percentage, 2))->values(),
            ],
            'study_logs' => $studyLogs->map(fn ($log) => [
                'id' => $log->id,
                'title' => $log->title ?: 'Study Session',
                'course' => $log->course?->name ?: '-',
                'group' => $log->group?->name ?: '-',
                'type' => ucfirst($log->type),
                'minutes' => $log->minutes,
                'date' => $log->study_date?->format('M d, Y'),
                'notes' => $log->notes,
            ]),
        ]);
    }
}