<?php

namespace App\Http\Controllers;

use App\Http\Requests\ProfileUpdateRequest;
use App\Models\JobExperience;
use App\Models\User;
use App\Services\SalaryMarketComparisonService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use Illuminate\View\View;

class ProfileController extends Controller
{
    /**
     * Show the user's profile index page.
     */
    public function index(SalaryMarketComparisonService $market_service)
    {
        $user = auth()->user()->load(['jobExperiences']);

        // Get Active/Latest Job
        $activeJob = $user->jobExperiences()->where('is_published', true)->latest()->first();

        // Fetch Tab Counts
        $counts = [
            'salary_data' => $user->rateMyPays()->count(),
            'ratings' => $user->ratings()->count(),
            'activity' => $user->rateMyPays()->count() + $user->postComments()->count() + $user->ratings()->count(),
        ];

        // Calculate Market Median for Chart
        // We compare based on the user's current job title
        $marketAvg = 0;
        $chart = [];
        $values = [];
        $job = [];
        $marketComparison = [];
        $marketAvg = null;
        if ($activeJob) {
            // $marketAvg = JobExperience::where('job_title', $activeJob->job_title)
            //     ->where('is_published', true)
            //     ->avg('annual_base_salary') ?? 0;
            $job = $activeJob;
            $payload = [
                'job_title' => $job->job_title,
                'level' => $job->level,
                'experience' => (int) ($job->years_of_experience ?? 0),
                'location' => [
                    'country' => $job->location ?? $job->country,
                    'state' => $job->state,
                    'city' => $job->city,
                ],
                'annual_base_salary' => $job->annual_base_salary,
                'company' => [
                    'size' => $job->company_size,
                    'industry' => $job->industry,
                ]
            ];
            $marketComparison = $market_service->compare($payload);
            $chart = null;
            if (
                is_array($marketComparison) &&
                isset($marketComparison['percentiles'], $marketComparison['market_comparison'])
            ) {
                $marketAvg = $marketComparison['market_comparison']['avg'];
                $values = [
                    'Lower Pay' => (int) $marketComparison['percentiles']['p25'],
                    'Average' => (int) $marketComparison['percentiles']['p50'],
                    'Your Pay' => (int) $job->total_compensation,
                    'Above Pay' => (int) $marketComparison['percentiles']['p75'],
                    'Top Pay' => (int) $marketComparison['percentiles']['p90'],
                ];
                asort($values);

                $chart = [
                    'values' => $values,
                    'max' => max($values),
                    'currency' => $marketComparison['currency'],
                ];
            }

        }

        $bonusPercentile = 0;
        if ($activeJob && $activeJob->bonus_commission > 0) {
            // Count total people in this role with a published job
            $totalInRole = JobExperience::where('job_title', $activeJob->job_title)
                ->where('is_published', true)
                ->count();

            // Count people in this role who earn LESS than the current user's bonus
            $lowerThanUser = JobExperience::where('job_title', $activeJob->job_title)
                ->where('is_published', true)
                ->where('bonus_commission', '<', $activeJob->bonus_commission)
                ->count();

            if ($totalInRole > 1) {
                // Calculate percentile: (Number of people below / Total people) * 100
                $bonusPercentile = ($lowerThanUser / ($totalInRole - 1)) * 100;
            }
        }

        // Fetch Recent Activity (Unified Feed)
        // This combines posts, comments, and ratings sorted by date
        $recentActivity = collect();

        $posts = $user->rateMyPays()->latest()->take(3)->get()->map(function ($item) {
            $item->activity_type = 'posted';
            return $item;
        });

        $comments = $user->postComments()->with('rateMyPay')->latest()->take(3)->get()->map(function ($item) {
            $item->activity_type = 'commented';
            return $item;
        });

        $ratings = $user->ratings()->with('rateMyPay')->latest()->take(3)->get()->map(function ($item) {
            $item->activity_type = 'rated';
            return $item;
        });

        $recentActivity = $recentActivity->concat($posts)->concat($comments)->concat($ratings)
            ->sortByDesc('created_at')
            ->take(5);

        // Connections (Accepted only)
        $connections = $user->sentConnections()->wherePivot('status', 'accepted')
            ->get()
            ->merge($user->receivedConnections()->wherePivot('status', 'accepted')->get())
            ->take(3);

        $lastUpdated = $user->jobExperiences()->latest('updated_at')->value('updated_at');

        // Fallback to user creation date if no job exists
        $lastUpdated = $lastUpdated ?? $user->created_at;

        // Get IDs of accepted connections
        $sentIds = $user->sentConnections()->wherePivot('status', 'accepted')->pluck('recipient_id');
        $receivedIds = $user->receivedConnections()->wherePivot('status', 'accepted')->pluck('requester_id');

        $connectionIds = $sentIds->merge($receivedIds);

        // Fetch the actual User models for these IDs
        $connections = User::whereIn('id', $connectionIds)
            ->with(['jobExperiences' => fn($q) => $q->where('still_employed', true)])
            ->limit(3)
            ->get();

        return view('profile.index', compact(
            'user',
            'activeJob',
            'job',
            'counts',
            'chart',
            'values',
            'marketComparison',
            'marketAvg',
            'bonusPercentile',
            'recentActivity',
            'connections',
            'lastUpdated',
            'connections',
        ));
    }

    /**
     * Display the user's profile form.
     */
    public function edit(Request $request): View
    {
        return view('profile.edit', [
            'user' => $request->user(),
        ]);
    }

    /**
     * Update the user's profile information.
     */
    public function update(ProfileUpdateRequest $request): RedirectResponse
    {
        $request->user()->fill($request->validated());

        if ($request->user()->isDirty('email')) {
            $request->user()->email_verified_at = null;
        }

        $request->user()->save();

        return Redirect::route('profile.edit')->with('status', 'profile-updated');
    }

    /**
     * Delete the user's account.
     */
    public function destroy(Request $request): RedirectResponse
    {
        $request->validateWithBag('userDeletion', [
            'password' => ['required', 'current_password'],
        ]);

        $user = $request->user();

        Auth::logout();

        $user->delete();

        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return Redirect::to('/');
    }
}
