<?php

namespace App\Http\Controllers\Research;

use App\Http\Controllers\Controller;
use App\Models\RPublication;
use App\Services\ReviewWorkflowService;
use App\Http\Requests\Research\ReviewPublicationRequest;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\JsonResponse;

/**
 * Controller: RReviewController
 * 
 * Handles the peer review workflow for research publications.
 * Manager and Super Manager access only.
 * 
 * @author SSHIA Development Team
 * @version 1.0.0
 */
class RReviewController extends Controller
{
    /**
     * Create a new controller instance.
     */
    public function __construct(
        protected ReviewWorkflowService $reviewService
    ) {}

    /**
     * Display the review queue.
     */
    public function index(Request $request): View
    {
        abort_unless(auth()->user()->can('review publications'), 403);

        $queue = $this->reviewService->getReviewQueue(
            $request->only(['category', 'submitted_from', 'submitted_to', 'per_page'])
        );

        $stats = $this->reviewService->getReviewStats(auth()->id());

        return view('research.review-queue', [
            'queue' => $queue,
            'stats' => $stats,
            'filters' => $request->only(['category', 'submitted_from', 'submitted_to']),
        ]);
    }

    /**
     * Display publication for review.
     */
    public function show(RPublication $publication): View
    {
        abort_unless(auth()->user()->can('review publications'), 403);

        if (!$publication->canReview()) {
            return redirect()
                ->route('research.review.index')
                ->with('error', 'This publication is not available for review.');
        }

        // Check if already reviewed by this user
        if ($this->reviewService->hasReviewed($publication->id, auth()->id())) {
            return redirect()
                ->route('research.review.index')
                ->with('info', 'You have already reviewed this publication.');
        }

        $publication->load(['user', 'files', 'reviews.reviewer']);

        // Get criteria for evaluation form
        $criteria = \App\Models\RReviewFeedback::CRITERIA;

        return view('research.review', [
            'publication' => $publication,
            'criteria' => $criteria,
        ]);
    }

    /**
     * Submit review feedback.
     */
    public function store(ReviewPublicationRequest $request, RPublication $publication): mixed
    {
        abort_unless(auth()->user()->can('review publications'), 403);

        if (!$publication->canReview()) {
            return back()->with('error', 'This publication is not available for review.');
        }

        // Check if already reviewed
        if ($this->reviewService->hasReviewed($publication->id, auth()->id())) {
            return redirect()
                ->route('research.review.index')
                ->with('error', 'You have already reviewed this publication.');
        }

        try {
            $feedback = $this->reviewService->submitReview(
                $publication,
                auth()->id(),
                $request->validated()
            );

            return redirect()
                ->route('research.review.index')
                ->with('success', 'Review submitted successfully!');

        } catch (\Exception $e) {
            return back()
                ->withInput()
                ->with('error', 'Failed to submit review: ' . $e->getMessage());
        }
    }

    /**
     * Feature a publication (Super Manager only).
     */
    public function feature(RPublication $publication): JsonResponse
    {
        abort_unless(auth()->user()->can('feature publications'), 403);

        try {
            $this->reviewService->featurePublication($publication, auth()->id());

            return response()->json([
                'success' => true,
                'message' => 'Publication featured successfully!',
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], 400);
        }
    }

    /**
     * Remove featured status.
     */
    public function unfeature(RPublication $publication): JsonResponse
    {
        abort_unless(auth()->user()->can('feature publications'), 403);

        try {
            $this->reviewService->unfeaturePublication($publication);

            return response()->json([
                'success' => true,
                'message' => 'Featured status removed.',
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], 400);
        }
    }

    /**
     * Get review history for publication.
     */
    public function history(RPublication $publication): JsonResponse
    {
        abort_unless(auth()->user()->can('view review history'), 403);

        $history = $this->reviewService->getReviewHistory($publication);

        return response()->json([
            'success' => true,
            'data' => $history,
        ]);
    }

    /**
     * Get average scores for publication.
     */
    public function scores(RPublication $publication): JsonResponse
    {
        abort_unless(auth()->user()->can('view review scores'), 403);

        $scores = $this->reviewService->calculateAverageScores($publication);

        return response()->json([
            'success' => true,
            'data' => $scores,
        ]);
    }

    /**
     * Get pending publications count for dashboard widget.
     */
    public function pendingCount(): JsonResponse
    {
        $count = RPublication::underReview()->count();

        return response()->json([
            'success' => true,
            'count' => $count,
        ]);
    }

    /**
     * Quick approve action (Super Manager only).
     */
    public function quickApprove(RPublication $publication): JsonResponse
    {
        abort_unless(auth()->user()->hasRole('Super Manager'), 403);

        if (!$publication->canReview()) {
            return response()->json([
                'success' => false,
                'message' => 'Publication cannot be approved in its current status.',
            ], 400);
        }

        try {
            $this->reviewService->submitReview($publication, auth()->id(), [
                'decision' => 'approve',
                'comments' => 'Quick approval by Super Manager.',
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Publication approved successfully!',
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], 400);
        }
    }
}
