<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\Registration\StoreContributorRegistrationRequest;
use App\Http\Requests\Registration\StoreHealthMarketorRegistrationRequest;
use App\Http\Requests\Registration\StoreMemberRegistrationRequest;
use App\Http\Requests\Registration\StoreMenteeRegistrationRequest;
use App\Http\Requests\Registration\StoreMentorRegistrationRequest;
use App\Http\Requests\Registration\StorePartnerRegistrationRequest;
use App\Http\Requests\Registration\StoreTraineeRegistrationRequest;
use App\Http\Requests\Registration\StoreTrainerRegistrationRequest;
use App\Models\MembershipCategory;
use App\Models\Mentorship\Category as MentorshipCategory;
use App\Services\RoleRegistrationService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;

class RoleRegistrationController extends Controller
{
    public function __construct(
        protected RoleRegistrationService $service
    ) {}

    // =========================================================================
    // MEMBER
    // =========================================================================

    public function showMember(): View
    {
        $categories = MembershipCategory::active()->ordered()->get();
        return view('registration.member', compact('categories'));
    }

    public function storeMember(StoreMemberRegistrationRequest $request): RedirectResponse
    {
        try {
            $application = $this->service->registerMember($request->validated());

            return redirect()->route('register.role.success')->with([
                'role'            => 'Member',
                'referenceNumber' => $application->reference_number,
                'email'           => $application->email,
            ]);
        } catch (\Exception $e) {
            Log::error('Member registration failed', ['error' => $e->getMessage()]);
            return back()->withInput()->with('error', 'Registration failed. Please try again.');
        }
    }

    // =========================================================================
    // TRAINER
    // =========================================================================

    public function showTrainer(): View
    {
        return view('registration.trainer');
    }

    public function storeTrainer(StoreTrainerRegistrationRequest $request): RedirectResponse
    {
        try {
            $cvFile = $request->hasFile('cv') ? $request->file('cv') : null;
            $application = $this->service->registerTrainer($request->validated(), $cvFile);

            return redirect()->route('register.role.success')->with([
                'role'            => 'Trainer',
                'referenceNumber' => $application->reference_number,
                'email'           => $application->email,
            ]);
        } catch (\Exception $e) {
            Log::error('Trainer registration failed', ['error' => $e->getMessage()]);
            return back()->withInput()->with('error', 'Registration failed. Please try again.');
        }
    }

    // =========================================================================
    // TRAINEE (instant access)
    // =========================================================================

    public function showTrainee(): View
    {
        return view('registration.trainee');
    }

    public function storeTrainee(StoreTraineeRegistrationRequest $request): RedirectResponse
    {
        try {
            $user = $this->service->registerTrainee($request->validated());

            Auth::login($user);

            return redirect()->route('dashboard.trainees')
                ->with('success', 'Welcome! Your Trainee account has been created successfully.');
        } catch (\Exception $e) {
            Log::error('Trainee registration failed', ['error' => $e->getMessage()]);
            return back()->withInput()->with('error', 'Registration failed. Please try again.');
        }
    }

    // =========================================================================
    // MENTOR
    // =========================================================================

    public function showMentor(): View
    {
        $categories = MentorshipCategory::active()->ordered()->get();
        return view('registration.mentor', compact('categories'));
    }

    public function storeMentor(StoreMentorRegistrationRequest $request): RedirectResponse
    {
        try {
            $validated = $request->validated();
            $this->service->registerMentor($validated);

            return redirect()->route('register.role.success')->with([
                'role'  => 'Mentor',
                'email' => $validated['email'],
            ]);
        } catch (\Exception $e) {
            Log::error('Mentor registration failed', ['error' => $e->getMessage()]);
            return back()->withInput()->with('error', 'Registration failed. Please try again.');
        }
    }

    // =========================================================================
    // MENTEE
    // =========================================================================

    public function showMentee(): View
    {
        $categories = MentorshipCategory::active()->ordered()->get();
        return view('registration.mentee', compact('categories'));
    }

    public function storeMentee(StoreMenteeRegistrationRequest $request): RedirectResponse
    {
        try {
            $validated = $request->validated();
            $this->service->registerMentee($validated);

            return redirect()->route('register.role.success')->with([
                'role'  => 'Mentee',
                'email' => $validated['email'],
            ]);
        } catch (\Exception $e) {
            Log::error('Mentee registration failed', ['error' => $e->getMessage()]);
            return back()->withInput()->with('error', 'Registration failed. Please try again.');
        }
    }

    // =========================================================================
    // PARTNER
    // =========================================================================

    public function showPartner(): View
    {
        return view('registration.partner');
    }

    public function storePartner(StorePartnerRegistrationRequest $request): RedirectResponse
    {
        try {
            $validated = $request->validated();
            $this->service->registerPartner($validated);

            return redirect()->route('register.role.success')->with([
                'role'  => 'Partner',
                'email' => $validated['email'],
            ]);
        } catch (\Exception $e) {
            Log::error('Partner registration failed', ['error' => $e->getMessage()]);
            return back()->withInput()->with('error', 'Registration failed. Please try again.');
        }
    }

    // =========================================================================
    // CONTRIBUTOR (instant access)
    // =========================================================================

    public function showContributor(): View
    {
        return view('registration.contributor');
    }

    public function storeContributor(StoreContributorRegistrationRequest $request): RedirectResponse
    {
        try {
            $user = $this->service->registerContributor($request->validated());

            Auth::login($user);

            // If there is a pending publication from the public submit form, create the draft
            if (session('pending_publication')) {
                return redirect()->route('research.pending.create')
                    ->with('success', 'Welcome! Your Contributor account has been created. Your research submission has been saved as a draft.');
            }

            return redirect()->route('dashboard.contributor')
                ->with('success', 'Welcome! Your Contributor account has been created successfully.');
        } catch (\Exception $e) {
            Log::error('Contributor registration failed', ['error' => $e->getMessage()]);
            return back()->withInput()->with('error', 'Registration failed. Please try again.');
        }
    }

    // =========================================================================
    // HEALTH MARKETOR
    // =========================================================================

    public function showHealthMarketor(): View
    {
        return view('registration.health-marketor');
    }

    public function storeHealthMarketor(StoreHealthMarketorRegistrationRequest $request): RedirectResponse
    {
        try {
            $application = $this->service->registerHealthMarketor($request->validated());

            return redirect()->route('register.role.success')->with([
                'role'            => 'Health Marketor',
                'referenceNumber' => $application->reference_number,
                'email'           => $application->email,
            ]);
        } catch (\Exception $e) {
            Log::error('Health Marketor registration failed', ['error' => $e->getMessage()]);
            return back()->withInput()->with('error', 'Registration failed. Please try again.');
        }
    }

    // =========================================================================
    // SHARED SUCCESS PAGE
    // =========================================================================

    public function success(): View
    {
        // Retrieve flash data passed via ->with(...)
        return view('registration.success', [
            'role'            => session('role', 'Applicant'),
            'referenceNumber' => session('referenceNumber'),
            'email'           => session('email'),
        ]);
    }
}
