<?php

namespace App\Livewire\Auth;

use App\Enum\UserRole;
use App\Models\User;
use Livewire\Component;
use App\Enum\UserStatus;
use Illuminate\Support\Str;
use App\Enum\UserTwoFactorEnabled;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;
use App\Mail\TwoFactorAuthenticationCode;
use Illuminate\Support\Facades\RateLimiter;

class Login extends Component
{
    public $email, $password, $remember = false;

    public function login()
    {
        $credentials = $this->validate([
            'email' => ['required', 'email', 'max:255'],
            'password' => ['required'],
        ]);

        // Unique key for rate limiting
        $key = Str::lower($this->email) . '|' . request()->ip();

        if (RateLimiter::tooManyAttempts($key, 5)) {
            $seconds = RateLimiter::availableIn($key);
            session()->flash('error', "Too many login attempts. Please try again in {$seconds} seconds.");
            return;
        }

        try {
            if (Auth::attempt($credentials, $this->remember)) {
                // Successful login → Clear attempts
                RateLimiter::clear($key);

                $user = Auth::user();

                if ($user->role->value === UserRole::USER->value) {
                    if ($user->status->value === UserStatus::INACTIVE->value) {
                        Auth::logout();

                        session()->flash('error', 'Your account has been temporarily blocked for security reasons. Please contact support to verify your identity and reactivate your account.');
                        return;
                    }

                    // Two Factor Authentication
                    if ($user->two_factor_enabled->value === UserTwoFactorEnabled::ENABLED->value) {
                        User::where('id', $user->id)->update([
                            'email_code' => getRandomNumber(6),
                            'email_code_expires_at' => now()->addMinutes(10),
                        ]);

                        Mail::to($user->email)->queue(new TwoFactorAuthenticationCode($user));

                        Auth::logout();

                        return redirect()->route('two_factor_authentication', ['id' => $user->uuid])->with('success', 'Please enter the code sent to your email to log in.');
                    }
                    // End Two Factor Authentication

                    User::where('id', $user->id)->update([
                        'last_login_at' => now(),
                        'last_login_ip' => request()->ip(),
                    ]);

                    request()->session()->regenerate();

                    return redirect()->intended(route('user.dashboard'))->with('success', 'Logged in successfully.');
                }

                if ($user->role->value === UserRole::ADMIN->value) {
                    if ($user->status->value === UserStatus::INACTIVE->value) {
                        Auth::logout();

                        session()->flash('error', 'Your account has been temporarily blocked for security reasons. Please contact support to verify your identity and reactivate your account.');
                        return;
                    }

                    request()->session()->regenerate();

                    return redirect()->route('admin.dashboard')->with('success', 'Logged in successfully.');
                }

                if ($user->role->value === UserRole::MASTER->value) {
                    request()->session()->regenerate();

                    return redirect()->route('master.dashboard')->with('success', 'Logged in successfully.');
                }
            }

            // Failed login → Record attempt and throttle for 120 seconds
            RateLimiter::hit($key, 120);

            session()->flash('error', "Invalid email or password. Please try again.");
            return;
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            session()->flash('error', config('app.messages.error'));
            return;
        }
    }
    public function render()
    {
        return view('livewire.auth.login');
    }
}
