<?php

declare(strict_types=1);

namespace App\Livewire\Admin\Auth;

use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Validation\ValidationException;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Rule;
use Livewire\Component;

#[Layout('layouts.admin-auth')]
final class Login extends Component
{
    #[Rule('required|email|max:255')]
    public string $email = '';

    #[Rule('required|string|min:8')]
    public string $password = '';

    public bool $remember = false;

    public function login(): void
    {
        $this->validate();

        // Rate limiting - stricter for admin (3 attempts per 5 minutes)
        $key = 'admin-login:'.$this->email;
        if (RateLimiter::tooManyAttempts($key, 3)) {
            $seconds = RateLimiter::availableIn($key);

            // Log failed attempt due to rate limiting
            $this->logLoginAttempt('rate_limited', null);

            throw ValidationException::withMessages([
                'email' => "Too many login attempts. Please try again in {$seconds} seconds.",
            ]);
        }

        // Find user
        $user = User::where('email', $this->email)
            ->where('status', 'active')
            ->first();

        // Check if user exists
        if (! $user) {
            RateLimiter::hit($key, 300); // 5 minutes
            $this->logLoginAttempt('user_not_found', null);

            throw ValidationException::withMessages([
                'email' => 'No account found with this email address.',
            ]);
        }

        // Check if user has admin role
        if (! $user->hasRole('admin')) {
            RateLimiter::hit($key, 300);
            $this->logLoginAttempt('not_admin', $user);

            throw ValidationException::withMessages([
                'email' => 'Access denied. Admin credentials required.',
            ]);
        }

        // Verify password
        if (! Hash::check($this->password, $user->password)) {
            RateLimiter::hit($key, 300);
            $this->logLoginAttempt('wrong_password', $user);

            throw ValidationException::withMessages([
                'password' => 'The provided password is incorrect.',
            ]);
        }

        // Clear rate limiting on successful login
        RateLimiter::clear($key);

        // Login the user
        Auth::login($user, $this->remember);

        // Log successful admin login
        $this->logLoginAttempt('success', $user);

        // Regenerate session for security
        session()->regenerate();

        // Redirect to admin dashboard
        $this->redirect(route('admin.dashboard'), navigate: true);
    }

    private function logLoginAttempt(string $status, ?User $user): void
    {
        activity()
            ->causedBy($user)
            ->withProperties([
                'email' => $this->email,
                'status' => $status,
                'ip_address' => request()->ip(),
                'user_agent' => request()->userAgent(),
            ])
            ->log('admin_login_attempt');
    }

    public function render()
    {
        return view('livewire.admin.auth.login');
    }
}
