<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\ExamAttempt;
use App\Models\ExamAttemptAnswer;
// use App\Models\ExamAttemptAnswer;
use App\Models\ExamQuestion;
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

class ExamAttemptController extends Controller
{
    public function index(Request $request): View
    {
        $attempts = ExamAttempt::with('exam')
            ->where('user_id', $request->user()->id)
            ->latest()
            ->paginate(15);

        return view('user.attempts.index', compact('attempts'));
    }

    public function show(Request $request, ExamAttempt $attempt): View
    {
        abort_unless($attempt->user_id === $request->user()->id, 403);

        $attempt->load('exam');

        return view('user.attempts.show', compact('attempt'));
    }

    public function take(Request $request, ExamAttempt $attempt): View|RedirectResponse
    {
        abort_unless($attempt->user_id === $request->user()->id, 403);

        $attempt->load('exam.course');

        if ($attempt->status !== 'in_progress') {
            return redirect()->route('user.attempts.result', $attempt);
        }

        $endsAt = $attempt->started_at
            ->copy()
            ->addMinutes($attempt->exam->duration_minutes);

        // if (now()->greaterThanOrEqualTo($endsAt)) {
        //     return redirect()
        //         ->route('user.attempts.submit', $attempt);
        // }

        $questions = ExamQuestion::where('exam_attempt_id', $attempt->id)
            ->orderBy('sort_order')
            ->get();

        return view('user.attempts.take', [
            'attempt' => $attempt,
            'questions' => $questions,
            'endsAt' => $endsAt,
        ]);
    }

    public function saveAnswer(Request $request, ExamAttempt $attempt)
    {
        abort_unless($attempt->user_id === $request->user()->id, 403);
        abort_unless($attempt->status === 'in_progress', 403);

        $validated = $request->validate([
            'exam_question_id' => ['required', 'integer', 'exists:exam_questions,id'],
            'selected_option_id' => ['nullable', 'integer'],
        ]);

        $examQuestion = ExamQuestion::where('id', $validated['exam_question_id'])
            ->where('exam_attempt_id', $attempt->id)
            ->firstOrFail();

        $selectedOption = null;

        if (!empty($validated['selected_option_id'])) {
            $selectedOption = collect($examQuestion->options_snapshot)
                ->firstWhere('id', (int) $validated['selected_option_id']);
        }

        $isCorrect = null;

        if ($selectedOption) {
            $isCorrect = (int) $selectedOption['id'] === (int) $examQuestion->correct_option_id;
        }

        // Update snapshot question record
        $examQuestion->update([
            'selected_option_id' => $selectedOption['id'] ?? null,
            'selected_option_key' => $selectedOption['key'] ?? null,
            'selected_option_text' => $selectedOption['text'] ?? null,
            'is_correct' => $isCorrect,
        ]);

        // Create or update actual attempt answer
        ExamAttemptAnswer::updateOrCreate(
            [
                'attempt_id' => $attempt->id,
                'question_id' => $examQuestion->question_id,
            ],
            [
                'selected_option_id' => $selectedOption['id'] ?? null,
                'is_correct' => $isCorrect,
            ]
        );

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

    public function submit(Request $request, ExamAttempt $attempt): RedirectResponse
    {
        abort_unless($attempt->user_id === $request->user()->id, 403);

        $questions = ExamQuestion::where('exam_attempt_id', $attempt->id)->get();

        $totalQuestions = $questions->count();

        $correctAnswers = $questions->where('is_correct', true)->count();

        $wrongAnswers = $questions
            ->whereNotNull('selected_option_id')
            ->where('is_correct', false)
            ->count();

        $unanswered = $questions->whereNull('selected_option_id')->count();

        $percentage = $totalQuestions > 0
            ? round(($correctAnswers / $totalQuestions) * 100, 2)
            : 0;

        $attempt->update([
            'submitted_at' => now(),
            'score' => $correctAnswers,
            'percentage' => $percentage,
            'correct_answers' => $correctAnswers,
            'wrong_answers' => $wrongAnswers,
            'unanswered' => $unanswered,
            'status' => 'completed',
        ]);

        return redirect()->route('user.attempts.result', $attempt)
            ->with('success', 'Exam submitted successfully.');
    }

    public function result(Request $request, ExamAttempt $attempt): View
    {
        abort_unless($attempt->user_id === $request->user()->id, 403);

        $attempt->load('exam.course');

        return view('user.attempts.result', compact('attempt'));
    }

    public function revision(Request $request, ExamAttempt $attempt): View|RedirectResponse
    {
        abort_unless($attempt->user_id === $request->user()->id, 403);
        // abort_unless($attempt->status === 'completed', 403);
        if ($attempt->status !== 'completed') {
            return redirect()
                ->route('user.attempts.result', $attempt)
                ->withErrors('You cannot review this exam because it was not completed.');
        }

        $attempt->load('exam.course');

        $questions = ExamQuestion::where('exam_attempt_id', $attempt->id)
            ->orderBy('sort_order')
            ->get();

        return view('user.attempts.revision', compact('attempt', 'questions'));
    }
}