<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Review;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;

class ReviewController extends Controller
{
    /**
     * Get reviews received by the authenticated user.
     */
    public function getReceivedReviews()
    {
        $user = Auth::user();
        
        $reviews = Review::with(['reviewer', 'ad'])
            ->where('reviewee_id', $user->id)
            ->orderBy('created_at', 'desc')
            ->get()
            ->map(function ($review) {
                return [
                    'id' => $review->id,
                    'reviewer_id' => $review->reviewer_id,
                    'reviewer_name' => $review->reviewer->name ?? 'Unknown',
                    'reviewer_image' => $review->reviewer->profile_image ?? null,
                    'reviewee_id' => $review->reviewee_id,
                    'ad_id' => $review->ad_id,
                    'ad_title' => $review->ad_title,
                    'ad_category' => $review->ad_category,
                    'rating' => $review->rating,
                    'review_text' => $review->review_text,
                    'transaction_type' => $review->transaction_type,
                    'is_verified_purchase' => $review->is_verified_purchase,
                    'created_at' => $review->created_at->toIso8601String(),
                    'time_ago' => $review->time_ago,
                    'has_ad_info' => $review->has_ad_info,
                ];
            });

        $stats = [
            'average_rating' => $user->average_rating,
            'total_reviews' => $user->total_reviews,
            'breakdown' => $user->review_breakdown,
            'rating_percentage' => $user->rating_percentage,
        ];

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

    /**
     * Get reviews given by the authenticated user.
     */
    public function getGivenReviews()
    {
        $user = Auth::user();
        
        $reviews = Review::with(['reviewee', 'ad'])
            ->where('reviewer_id', $user->id)
            ->orderBy('created_at', 'desc')
            ->get()
            ->map(function ($review) {
                return [
                    'id' => $review->id,
                    'reviewer_id' => $review->reviewer_id,
                    'reviewee_id' => $review->reviewee_id,
                    'reviewee_name' => $review->reviewee->name ?? 'Unknown',
                    'reviewee_image' => $review->reviewee->profile_image ?? null,
                    'ad_id' => $review->ad_id,
                    'ad_title' => $review->ad_title,
                    'ad_category' => $review->ad_category,
                    'rating' => $review->rating,
                    'review_text' => $review->review_text,
                    'transaction_type' => $review->transaction_type,
                    'is_verified_purchase' => $review->is_verified_purchase,
                    'created_at' => $review->created_at->toIso8601String(),
                    'time_ago' => $review->time_ago,
                    'has_ad_info' => $review->has_ad_info,
                ];
            });

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

    /**
     * Get review stats for a specific user.
     */
    public function getUserReviewStats($userId)
    {
        $user = User::findOrFail($userId);

        $stats = [
            'average_rating' => $user->average_rating,
            'total_reviews' => $user->total_reviews,
            'breakdown' => $user->review_breakdown,
            'rating_percentage' => $user->rating_percentage,
        ];

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

    /**
     * Submit a new review.
     */
    public function submitReview(Request $request)
    {
        $validated = $request->validate([
            'reviewee_id' => 'required|exists:users,id',
            'ad_id' => 'nullable|exists:ads,id',
            'rating' => 'required|integer|min:1|max:5',
            'review_text' => 'nullable|string|max:1000',
            'ad_title' => 'nullable|string|max:255',
            'ad_category' => 'nullable|string|max:255',
            'transaction_type' => ['required', Rule::in(['buyer', 'seller'])],
            'is_verified_purchase' => 'boolean',
        ]);

        // Prevent self-review
        if ($validated['reviewee_id'] == Auth::id()) {
            return response()->json([
                'success' => false,
                'message' => 'You cannot review yourself.',
            ], 400);
        }

        $validated['reviewer_id'] = Auth::id();

        try {
            $review = Review::create($validated);
            $review->load(['reviewer', 'reviewee', 'ad']);

            return response()->json([
                'success' => true,
                'message' => 'Review submitted successfully.',
                'review' => [
                    'id' => $review->id,
                    'reviewer_id' => $review->reviewer_id,
                    'reviewer_name' => $review->reviewer->name,
                    'reviewee_id' => $review->reviewee_id,
                    'reviewee_name' => $review->reviewee->name,
                    'rating' => $review->rating,
                    'review_text' => $review->review_text,
                    'created_at' => $review->created_at->toIso8601String(),
                ],
            ], 201);
        } catch (\Exception $e) {
            // Handle unique constraint violation
            if ($e->getCode() == 23000) {
                return response()->json([
                    'success' => false,
                    'message' => 'You have already reviewed this transaction.',
                ], 409);
            }

            return response()->json([
                'success' => false,
                'message' => 'Failed to submit review.',
            ], 500);
        }
    }

    /**
     * Update a review (only within 24 hours).
     */
    public function updateReview(Request $request, $id)
    {
        $review = Review::findOrFail($id);

        // Only the reviewer can update
        if ($review->reviewer_id != Auth::id()) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized.',
            ], 403);
        }

        // Check if within 24 hours
        if ($review->created_at->diffInHours(now()) > 24) {
            return response()->json([
                'success' => false,
                'message' => 'Reviews can only be edited within 24 hours.',
            ], 403);
        }

        $validated = $request->validate([
            'rating' => 'sometimes|integer|min:1|max:5',
            'review_text' => 'nullable|string|max:1000',
        ]);

        $review->update($validated);

        return response()->json([
            'success' => true,
            'message' => 'Review updated successfully.',
            'review' => $review,
        ]);
    }

    /**
     * Soft delete a review.
     */
    public function deleteReview($id)
    {
        $review = Review::findOrFail($id);

        // Only the reviewer can delete
        if ($review->reviewer_id != Auth::id()) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized.',
            ], 403);
        }

        $review->delete();

        return response()->json([
            'success' => true,
            'message' => 'Review deleted successfully.',
        ]);
    }
}
