<?php

namespace App\Http\Controllers;

use App\Models\MentorStudent;
use App\Models\MentorSetting;
use App\Models\Trade;
use App\Models\TradeComment;
use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\View\View;

class MentorDashboardController extends Controller
{
    public function index(Request $request): View
    {
        abort_unless(MentorSetting::enabled(), 404);

        $mentor = $request->user();
        $students = MentorStudent::query()
            ->with('student')
            ->where('mentor_id', $mentor->id)
            ->latest()
            ->get();

        $activeStudentIds = $students->where('status', 'active')->pluck('student_id')->filter();
        $submittedTrades = Trade::query()
            ->whereIn('user_id', $activeStudentIds)
            ->where('review_status', 'submitted')
            ->count();

        return view('mentor.dashboard', [
            'students' => $students,
            'totalStudents' => $activeStudentIds->count(),
            'pendingInvites' => $students->where('status', 'invited')->count(),
            'submittedTrades' => $submittedTrades,
        ]);
    }

    public function invite(Request $request): RedirectResponse
    {
        abort_unless(MentorSetting::enabled(), 404);

        $data = $request->validate([
            'student_email' => ['nullable', 'email', 'max:255'],
        ]);

        $activeStudents = MentorStudent::query()
            ->where('mentor_id', $request->user()->id)
            ->where('status', 'active')
            ->count();

        if ($activeStudents >= MentorSetting::current()->max_students_per_plan) {
            return back()->with('error', 'You have reached the current maximum students allowed by the mentor plan.');
        }

        do {
            $code = 'MENTOR-'.Str::upper(Str::random(8));
        } while (MentorStudent::where('invite_code', $code)->exists());

        MentorStudent::create([
            'mentor_id' => $request->user()->id,
            'student_email' => $data['student_email'] ?? null,
            'invite_code' => $code,
            'status' => 'invited',
        ]);

        return redirect()->route('mentor.dashboard')->with('success', 'Student invite code created.');
    }

    public function student(User $student, Request $request): View
    {
        abort_unless(MentorSetting::enabled(), 404);
        $this->authorizeMentorStudent($request->user(), $student);

        $trades = Trade::query()
            ->where('user_id', $student->id)
            ->latest()
            ->paginate(10);

        $wins = Trade::query()
            ->where('user_id', $student->id)
            ->where('profit_loss', '>', 0)
            ->count();
        $losses = Trade::query()
            ->where('user_id', $student->id)
            ->where('profit_loss', '<', 0)
            ->count();
        $completed = $wins + $losses;

        return view('mentor.student', [
            'student' => $student,
            'trades' => $trades,
            'totalTrades' => Trade::query()->where('user_id', $student->id)->count(),
            'wins' => $wins,
            'losses' => $losses,
            'winRate' => $completed > 0 ? round(($wins / $completed) * 100, 1) : 0,
            'profitLoss' => (float) Trade::query()->where('user_id', $student->id)->sum('profit_loss'),
        ]);
    }

    public function trade(User $student, Trade $trade, Request $request): View
    {
        abort_unless(MentorSetting::enabled(), 404);
        $this->authorizeMentorStudent($request->user(), $student);
        abort_unless($trade->user_id === $student->id, 403);

        $trade->load('comments.mentor', 'mistakeTags');

        return view('mentor.trade', compact('student', 'trade'));
    }

    public function comment(User $student, Trade $trade, Request $request): RedirectResponse
    {
        abort_unless(MentorSetting::enabled(), 404);
        $this->authorizeMentorStudent($request->user(), $student);
        abort_unless($trade->user_id === $student->id, 403);

        $data = $request->validate([
            'comment' => ['required', 'string', 'max:5000'],
        ]);

        TradeComment::create([
            'trade_id' => $trade->id,
            'mentor_id' => $request->user()->id,
            'student_id' => $student->id,
            'comment' => $data['comment'],
        ]);

        $trade->update(['review_status' => 'reviewed']);

        return redirect()->route('mentor.students.trades.show', [$student, $trade])->with('success', 'Comment added for student.');
    }

    private function authorizeMentorStudent(User $mentor, User $student): void
    {
        abort_unless(
            MentorStudent::query()
                ->where('mentor_id', $mentor->id)
                ->where('student_id', $student->id)
                ->where('status', 'active')
                ->exists(),
            403
        );
    }
}
