<?php

namespace App\Http\Controllers;

use App\Models\TypingJobSubmission;
use App\Services\TypingJobService;
use App\Support\TypingJobSettings;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;
use Illuminate\View\View;

class TypingJobController extends Controller
{
    public function __construct(private TypingJobService $typingJobService)
    {
    }

    public function index(): View
    {
        $user = auth()->user();
        $progress = $this->typingJobService->progressForUser($user);
        $pendingTask = $this->typingJobService->pendingTaskForUser($user, $progress);

        return view('user.typing_job.index', [
            'progress' => $progress,
            'pendingTask' => $pendingTask,
            'recentSubmissions' => $this->typingJobService->recentSubmissionsForUser($user),
            'copy' => $this->copyForProgress($progress),
        ]);
    }

    public function history(Request $request): View
    {
        $user = $request->user();
        $progress = $this->typingJobService->progressForUser($user);

        if (Schema::hasTable('typing_job_submissions')) {
            $submissions = TypingJobSubmission::query()
                ->where('user_id', $user->id)
                ->latest('submitted_at')
                ->latest('id')
                ->paginate(20)
                ->withQueryString();
        } else {
            $submissions = new LengthAwarePaginator(
                [],
                0,
                20,
                max(1, (int) $request->query('page', 1)),
                [
                    'path' => $request->url(),
                    'query' => $request->query(),
                ]
            );
        }

        return view('user.typing_job.history', [
            'progress' => $progress,
            'submissions' => $submissions,
            'copy' => $this->copyForProgress($progress),
        ]);
    }

    public function submit(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'task_token' => ['required', 'string', 'max:100'],
            'answer' => ['required', 'integer'],
        ]);

        $this->typingJobService->submitAnswer(
            $request->user(),
            (string) $validated['task_token'],
            (int) $validated['answer']
        );

        return redirect()
            ->route('typing-job.index')
            ->with('success', 'সঠিক উত্তর সাবমিট হয়েছে। আপনার ব্যালেন্সে ৳' . number_format($this->typingJobService->rewardAmount(), 2) . ' যোগ হয়েছে।');
    }

    private function copyForProgress(array $progress): array
    {
        return TypingJobSettings::content([
            ':tasks_per_referral' => (string) ($progress['tasks_per_verified_referral'] ?? TypingJobSettings::tasksPerVerifiedReferral()),
            ':reward' => number_format((float) ($progress['task_reward'] ?? TypingJobSettings::rewardAmount()), 2, '.', ''),
            ':earned' => number_format((float) ($progress['earned'] ?? 0), 2, '.', ''),
            ':completed' => (string) ($progress['completed'] ?? 0),
            ':remaining' => (string) ($progress['remaining'] ?? 0),
            ':verified_referrals' => (string) ($progress['verified_referrals_count'] ?? 0),
            ':total_unlocked' => (string) ($progress['total_unlocked_tasks'] ?? 0),
            ':task_quota' => (string) ($progress['max_tasks'] ?? 0),
        ]);
    }
}
