<?php

namespace App\Http\Controllers;

use App\Http\Resources\JobExperienceResource;
use App\Models\JobExperience;
use App\Repositories\JobExperienceRepository;
use App\Services\SalaryMarketComparisonService;
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

class JobExperienceController extends Controller
{
    public function __construct(
        private JobExperienceRepository $jobExperienceRepository
    ) {}

    public function index(Request $request): View
    {

        // return $this->getActiveJob()
        $filters = $request->only(['search', 'work_status', 'is_published']);
        $experiences = $this->jobExperienceRepository->getAllForUser(auth()->id(), $filters);

        return view('dashboard.job-experiences.index', compact('experiences'));
    }

    public function create(): View
    {


        return view('dashboard.job-experiences.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'job_title' => 'required|string|max:255',
            'company_name' => 'required|string|max:255',
            'level' => 'required|string|max:255',
            'work_status' => 'required|in:new_offer,current_employee,former_employee',
            // 'still_employed' => 'boolean',
            'employment_month' => 'required|integer|between:1,12',
            'employment_year' => 'required|integer|min:1900|max:' . date('Y'),
            'end_month' => 'nullable|integer|between:1,12',
            'end_year' => 'nullable|integer|min:1900|max:' . date('Y'),
            'number_of_years_as_employee' => 'nullable|numeric|min:0',
            'years_of_experience' => 'nullable|numeric|min:0',
            'years_in_level' => 'nullable|numeric|min:0',
            'country' => 'required|string|max:255',
            'city' => 'nullable|string|max:255',
            'state' => 'nullable|string|max:255',
            'post_code' => 'nullable|string|max:255',
            'work_arrangement' => 'required|in:onsite,remote,hybrid',
            'employment_type' => 'required|in:full_time,part_time,contract,freelance,internship',
            'annual_base_salary' => 'nullable|numeric|min:0',
            'bonus_commission' => 'nullable|numeric|min:0',
            'overtime_pay' => 'nullable|numeric|min:0',
            'equity' => 'nullable|numeric|min:0',
            'currency' => 'required|string|size:3',
            'benefits' => 'nullable|string',
            'job_description' => 'nullable|string',
            'industry' => 'nullable|string|max:255',
            'company_size' => 'nullable|string|max:255',
        ]);

        // Combine country, state, city into location
        $locationParts = array_filter([
            $validated['city'] ?? null,
            $validated['state'] ?? null,
            $validated['country'] ?? null,
        ]);

        $validated['location'] = implode(', ', $locationParts);
        $validated['user_id'] = auth()->id();
        $validated['still_employed'] = $request->has('still_employed');

        // return $validated;
        try {
            $jobExperience = $this->jobExperienceRepository->create($validated);

            return redirect()->route('dashboard.job-experiences.index')
                ->with('success', 'Job experience added successfully!');

        } catch (\Exception $e) {
            return [$validated, $e->getMessage()];
            // return back()->withErrors(['error' => 'Failed to create job experience: ' . $e->getMessage()]);
        }
    }

    public function toggle($id)
    {
        $exp = JobExperience::findOrFail($id);

        $exp->is_published = !$exp->is_published;
        $exp->published_at = $exp->is_published ? now() : null;

        $exp->save();

        return back()->with('success', $exp->is_published ? 'Experience is now published.' : 'Experience is now unpublished.');
    }


    public function show(JobExperience $jobExperience, SalaryMarketComparisonService $service): View
    {
        $experience = $jobExperience;

        $job = $experience;

        $marketComparison = null;
        $chart = null;

        if ($job) {
            $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 = $service->compare($payload);

            if (
                is_array($marketComparison) &&
                isset($marketComparison['percentiles'], $marketComparison['market_comparison'])
            ) {
                $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'],
                ];
            }
        }
        return view('dashboard.job-experiences.show', compact('experience', 'marketComparison', 'chart', 'job'));
    }



    public function destroy(JobExperience $jobExperience): RedirectResponse
    {

        try {
            $this->jobExperienceRepository->delete($jobExperience);

            return redirect()->route('dashboard.job-experiences.index')
                ->with('success', 'Job experience deleted successfully!');

        } catch (\Exception $e) {
            return back()->withErrors(['error' => 'Failed to delete job experience: ' . $e->getMessage()]);
        }
    }

    public function getActiveJob(): View
    {
        $activeJob = $this->jobExperienceRepository->getActiveJobForUser(auth()->id());

        return view('job-experiences.active', compact('activeJob'));
    }

    public function publish(JobExperience $jobExperience): RedirectResponse
    {
        // $this->authorize('update', $jobExperience);

        try {
            $this->jobExperienceRepository->publish($jobExperience);

            return back()->with('success', 'Job experience published successfully!');

        } catch (\Exception $e) {
            return back()->withErrors(['error' => $e->getMessage()]);
        }
    }

    public function unpublish(JobExperience $jobExperience): RedirectResponse
    {
        $this->authorize('update', $jobExperience);

        try {
            $this->jobExperienceRepository->unpublish($jobExperience);

            return back()->with('success', 'Job experience unpublished successfully!');

        } catch (\Exception $e) {
            return back()->withErrors(['error' => 'Failed to unpublish job experience.']);
        }
    }

    public function setActive(JobExperience $jobExperience): RedirectResponse
    {
        $this->authorize('update', $jobExperience);

        try {
            $this->jobExperienceRepository->setAsActive($jobExperience);

            return back()->with('success', 'Job set as active successfully!');

        } catch (\Exception $e) {
            return back()->withErrors(['error' => 'Failed to set job as active.']);
        }
    }

    // API Methods (if needed for AJAX)
    public function apiIndex(Request $request)
    {
        $filters = $request->only(['search', 'work_status', 'is_published']);
        $jobExperiences = $this->jobExperienceRepository->getAllForUser(auth()->id(), $filters);

        return JobExperienceResource::collection($jobExperiences);
    }

    // public function apiShow(JobExperience $jobExperience)
    // {
    //     $this->authorize('view', $jobExperience);

    //     return new JobExperienceResource($jobExperience->load('user', 'ratings'));
    // }

    public function apiActiveJob()
    {
        $activeJob = $this->jobExperienceRepository->getActiveJobForUser(auth()->id());

        return $activeJob ? new JobExperienceResource($activeJob) : response()->json(['message' => 'No active job found'], 404);
    }

    public function edit(JobExperience $jobExperience): View
    {
      
        $experience = $jobExperience;
        return view('dashboard.job-experiences.edit', compact('experience'));
    }

    public function update(Request $request, JobExperience $jobExperience): RedirectResponse
    {
        $validated = $request->validate([
            'job_title' => 'sometimes|string|max:255',
            'company_name' => 'sometimes|string|max:255',
            'level' => 'sometimes|string|max:255',
            'work_status' => 'sometimes|in:new_offer,current_employee,former_employee',
            'employment_month' => 'sometimes|integer|between:1,12',
            'employment_year' => 'sometimes|integer|min:1900|max:' . date('Y'),
            'end_month' => 'nullable|integer|between:1,12',
            'end_year' => 'nullable|integer|min:1900|max:' . date('Y'),
            'number_of_years_as_employee' => 'nullable|numeric|min:0',
            'years_of_experience' => 'nullable|numeric|min:0',
            'years_in_level' => 'nullable|numeric|min:0',
            'country' => 'sometimes|string|max:255',
            'city' => 'nullable|string|max:255',
            'state' => 'nullable|string|max:255',
            'post_code' => 'nullable|string|max:255',
            'work_arrangement' => 'sometimes|in:onsite,remote,hybrid',
            'employment_type' => 'sometimes|in:full_time,part_time,contract,freelance,internship',
            'annual_base_salary' => 'nullable|numeric|min:0',
            'bonus_commission' => 'nullable|numeric|min:0',
            'overtime_pay' => 'nullable|numeric|min:0',
            'equity' => 'nullable|numeric|min:0',
            'currency' => 'sometimes|string|size:3',
            'benefits' => 'nullable|string',
            'job_description' => 'nullable|string',
            'industry' => 'nullable|string|max:255',
            'company_size' => 'nullable|string|max:255',
        ]);

        // Combine country, state, city into location
        $locationParts = array_filter([
            $validated['city'] ?? null,
            $validated['state'] ?? null,
            $validated['country'] ?? null,
        ]);

        $validated['location'] = implode(', ', $locationParts);
        $validated['still_employed'] = $request->has('still_employed');

        try {
            $this->jobExperienceRepository->update($jobExperience, $validated);

            return redirect()->route('dashboard.job-experiences.show', $jobExperience->id)
                ->with('success', 'Job experience updated successfully!');

        } catch (\Exception $e) {
            return back()->withErrors(['error' => 'Failed to update job experience: ' . $e->getMessage()]);
        }
    }
}
