<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\Applicant;
use App\Models\Interview;
use App\Models\User;
use App\Notifications\InterviewAssignedNotification;
use App\Services\Recruitment\RecruitmentNavService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;

class InterviewController extends Controller
{
    public function index(RecruitmentNavService $nav)
    {
        $user = Auth::user();
        abort_unless($user instanceof User, 403);

        $isHrSchedule = $nav->hasHrAccess($user);
        abort_unless($isHrSchedule || $nav->canViewAssignedInterviews($user), 403);

        if (! $isHrSchedule) {
            return redirect()->route('recruitment.my-interviews');
        }

        $today = now()->toDateString();
        $todayEnd = now()->copy()->endOfDay();

        $todayInterviews = $this->scheduleQuery($user, $isHrSchedule)
            ->whereDate('scheduled_at', $today)
            ->where('status', 'scheduled')
            ->orderBy('scheduled_at')
            ->get();

        $upcomingQuery = $this->scheduleQuery($user, $isHrSchedule)
            ->whereDate('scheduled_at', '>', $today)
            ->where('status', 'scheduled');

        if ($isHrSchedule) {
            $upcomingQuery->where('scheduled_at', '<=', now()->addDays(14)->endOfDay());
        }

        $upcomingInterviews = $upcomingQuery->orderBy('scheduled_at')->get();

        $followUpsDue = $isHrSchedule
            ? $this->scheduleQuery($user, true)
                ->where('status', 'scheduled')
                ->whereNotNull('follow_up_at')
                ->where('follow_up_at', '<=', $todayEnd)
                ->orderBy('follow_up_at')
                ->get()
            : collect();

        $completedInterviews = $this->scheduleQuery($user, $isHrSchedule)
            ->where('status', 'completed')
            ->orderByDesc('scheduled_at')
            ->paginate(10);

        return view('recruitment.interviews.index', compact(
            'todayInterviews',
            'upcomingInterviews',
            'followUpsDue',
            'completedInterviews',
            'isHrSchedule'
        ));
    }

    public function create()
    {
        $applicants = Applicant::orderBy('name')->get();
        $interviewers = $this->interviewers();

        return view('recruitment.interviews.create', compact('applicants', 'interviewers'));
    }

    public function store(Request $request)
    {
        $companyId = Auth::user()?->company_id;
        $request->merge([
            'follow_up_at' => $request->filled('follow_up_at') ? $request->input('follow_up_at') : null,
            'meeting_link' => $request->filled('meeting_link') ? $request->input('meeting_link') : null,
        ]);
        $validated = $request->validate([
            'applicant_id' => ['required', 'exists:applicants,id'],
            'interviewer_id' => ['nullable', 'exists:users,id'],
            'interview_type' => ['required', Rule::in(['video', 'in-person', 'phone'])],
            'meeting_link' => ['nullable', 'url', 'max:500'],
            'scheduled_at' => ['required', 'date'],
            'status' => ['required', Rule::in(['scheduled', 'completed', 'cancelled'])],
            'feedback' => ['nullable', 'string'],
            'follow_up_at' => ['nullable', 'date'],
            'follow_up_notes' => ['nullable', 'string', 'max:2000'],
        ]);
        $validated['follow_up_at'] = ! empty($validated['follow_up_at']) ? $validated['follow_up_at'] : null;
        $validated['meeting_link'] = ! empty($validated['meeting_link']) ? $validated['meeting_link'] : null;

        $interview = Interview::create(array_merge($validated, [
            'company_id' => $companyId,
        ]));

        $this->notifyAssignedInterviewer($interview);

        return redirect()->route('interviews.index')->with('success', 'Interview scheduled successfully.');
    }

    public function edit(Interview $interview)
    {
        $applicants = Applicant::orderBy('name')->get();
        $interviewers = $this->interviewers();

        return view('recruitment.interviews.edit', compact('interview', 'applicants', 'interviewers'));
    }

    public function update(Request $request, Interview $interview)
    {
        $request->merge([
            'follow_up_at' => $request->filled('follow_up_at') ? $request->input('follow_up_at') : null,
            'meeting_link' => $request->filled('meeting_link') ? $request->input('meeting_link') : null,
        ]);
        $validated = $request->validate([
            'applicant_id' => ['required', 'exists:applicants,id'],
            'interviewer_id' => ['nullable', 'exists:users,id'],
            'interview_type' => ['required', Rule::in(['video', 'in-person', 'phone'])],
            'meeting_link' => ['nullable', 'url', 'max:500'],
            'scheduled_at' => ['required', 'date'],
            'status' => ['required', Rule::in(['scheduled', 'completed', 'cancelled'])],
            'feedback' => ['nullable', 'string'],
            'follow_up_at' => ['nullable', 'date'],
            'follow_up_notes' => ['nullable', 'string', 'max:2000'],
        ]);
        $validated['follow_up_at'] = ! empty($validated['follow_up_at']) ? $validated['follow_up_at'] : null;
        $validated['meeting_link'] = ! empty($validated['meeting_link']) ? $validated['meeting_link'] : null;

        $interview->update($validated);

        if ($interview->wasChanged(['interviewer_id', 'scheduled_at', 'status', 'interview_type', 'meeting_link'])) {
            $this->notifyAssignedInterviewer($interview);
        }

        return redirect()->route('interviews.index')->with('success', 'Interview updated successfully.');
    }

    public function destroy(Interview $interview)
    {
        $interview->delete();

        return redirect()->route('interviews.index')->with('success', 'Interview deleted successfully.');
    }

    private function scheduleQuery(User $user, bool $isHrSchedule): Builder
    {
        $query = Interview::query()->with(['applicant.jobPosting', 'interviewer']);

        if (! $isHrSchedule) {
            $query->where('interviewer_id', $user->id);
        }

        return $query;
    }

    private function notifyAssignedInterviewer(Interview $interview): void
    {
        if (! $interview->interviewer_id || (int) $interview->interviewer_id === (int) Auth::id()) {
            return;
        }

        $interview->loadMissing(['applicant.jobPosting', 'interviewer']);
        $interview->interviewer?->notify(new InterviewAssignedNotification($interview));
    }

    private function interviewers()
    {
        $currentUser = Auth::user();
        $users = User::query()->forActiveDirectory();

        if ($currentUser?->company_id) {
            $users->where('company_id', $currentUser->company_id);
        }

        return $users->orderBy('name')->get();
    }
}
