<?php

namespace App\Http\Controllers\Member;

use App\Http\Controllers\Controller;
use App\Http\Requests\Member\RespondFreelanceMatchRequest;
use App\Http\Requests\Member\SendInterestRequest;
use App\Http\Requests\Member\StoreFreelanceBriefRequest;
use App\Http\Requests\Member\StoreFreelanceProfileRequest;
use App\Http\Requests\Member\StoreReviewRequest;
use App\Models\FreelanceBrief;
use App\Models\FreelanceMatch;
use App\Models\FreelanceProfile;
use App\Services\Member\FreelanceService;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class FreelanceController extends Controller
{
    public function __construct(private readonly FreelanceService $service) {}

    // ── Landing Page ───────────────────────────────────────────

    public function index(Request $request): Response
    {
        return Inertia::render('Member/Freelance/Index', $this->service->index(
            $request->user(),
            $request->only(['hub_id', 'search', 'brief_search', 'availability'])
        ));
    }

    // ── Freelance Profile ──────────────────────────────────────

    public function createProfile(Request $request): Response
    {
        return Inertia::render('Member/Freelance/Profiles/Create',
            $this->service->profileForm($request->user())
        );
    }

    public function storeProfile(StoreFreelanceProfileRequest $request): \Illuminate\Http\RedirectResponse
    {
        $this->service->storeProfile($request->user(), $request->validated());

        return redirect()->route('member.freelance.index')
            ->with('success', __('freelance.profile_saved'));
    }

    public function editProfile(Request $request): Response
    {
        return Inertia::render('Member/Freelance/Profiles/Edit',
            $this->service->profileForm($request->user())
        );
    }

    public function updateProfile(StoreFreelanceProfileRequest $request, FreelanceProfile $profile): \Illuminate\Http\RedirectResponse
    {
        abort_if($profile->user_id !== $request->user()->id, 403);

        $this->service->updateProfile($profile, $request->validated());

        return redirect()->route('member.freelance.index')
            ->with('success', __('freelance.profile_updated'));
    }

    public function toggleProfile(Request $request, FreelanceProfile $profile): \Illuminate\Http\JsonResponse
    {
        abort_if($profile->user_id !== $request->user()->id, 403);

        $updated = $this->service->toggleProfile($profile);

        return response()->json(['is_active' => $updated->is_active]);
    }

    public function showProfile(Request $request, FreelanceProfile $profile): Response
    {
        return Inertia::render('Member/Freelance/Profiles/Show',
            $this->service->showProfile($profile, $request->user())
        );
    }

    // ── Freelance Briefs ───────────────────────────────────────

    public function createBrief(): Response
    {
        return Inertia::render('Member/Freelance/Briefs/Create',
            $this->service->briefForm()
        );
    }

    public function storeBrief(StoreFreelanceBriefRequest $request): \Illuminate\Http\RedirectResponse
    {
        $brief = $this->service->storeBrief($request->user(), $request->validated());

        return redirect()->route('member.freelance.briefs.show', $brief->id)
            ->with('success', __('freelance.brief_posted'));
    }

    public function showBrief(Request $request, FreelanceBrief $brief): Response
    {
        return Inertia::render('Member/Freelance/Briefs/Show',
            $this->service->showBrief($brief, $request->user())
        );
    }

    public function closeBrief(Request $request, FreelanceBrief $brief): \Illuminate\Http\RedirectResponse
    {
        abort_if($brief->user_id !== $request->user()->id, 403);

        $this->service->closeBrief($brief);

        return back()->with('success', __('freelance.brief_closed'));
    }

    // ── Matching Flow ──────────────────────────────────────────

    public function sendInterest(SendInterestRequest $request, FreelanceProfile $profile): \Illuminate\Http\JsonResponse
    {
        abort_if($profile->user_id === $request->user()->id, 403);

        $match = $this->service->sendInterest(
            $request->user(),
            $profile,
            $request->validated('message')
        );

        return response()->json([
            'status'   => $match->status,
            'match_id' => $match->id,
            'message'  => __('freelance.interest_sent'),
        ]);
    }

    public function respond(RespondFreelanceMatchRequest $request, FreelanceMatch $match): \Illuminate\Http\JsonResponse
    {
        abort_if($match->provider_user_id !== $request->user()->id, 403);

        $updated = $this->service->respond($match, $request->validated('response'));

        return response()->json([
            'status'  => $updated->status,
            'message' => __('freelance.response_saved'),
        ]);
    }

    public function consent(Request $request, FreelanceMatch $match): \Illuminate\Http\JsonResponse
    {
        abort_unless(
            in_array($request->user()->id, [$match->seeker_user_id, $match->provider_user_id]),
            403
        );

        $updated = $this->service->consent($match, $request->user());

        return response()->json([
            'status'         => $updated->status,
            'contact_shared' => $updated->isConnected(),
            'contact'        => $updated->contact_info ?? null,
            'message'        => $updated->isConnected()
                ? __('freelance.connected')
                : __('freelance.consent_recorded'),
        ]);
    }

    public function myMatches(Request $request): Response
    {
        return Inertia::render('Member/Freelance/MyMatches',
            $this->service->myMatches($request->user())
        );
    }

    // ── Reviews ────────────────────────────────────────────────

    public function storeReview(StoreReviewRequest $request, FreelanceMatch $match): \Illuminate\Http\JsonResponse
    {
        $review = $this->service->storeReview($match, $request->user(), $request->validated());

        return response()->json([
            'message' => __('freelance.review_posted'),
            'review'  => [
                'rating'  => $review->rating,
                'comment' => $review->comment,
                'author'  => $review->author_name,
            ],
        ]);
    }
}