<?php

use App\Models\User;
use App\Services\OtpService;
use App\Services\LoginService;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Livewire\Component;

new class extends Component {
    public string $email = '';
    public string $password = '';
    public bool $remember = false;
    public bool $usePassword = true; // default to password login
    public bool $otpEnabled = true;

    // Make nullable and initialize lazily
    protected ?LoginService $loginService = null;

    public function mount()
    {
        // Load OTP setting from authenticated user or default to true
        $this->otpEnabled = Auth::user()?->otpEnabled() ?? true;

        // If OTP is disabled, force password login
        $this->usePassword = true;
    }

    /**
     * Get LoginService instance (lazy)
     */
    protected function loginService(): LoginService
    {
        return $this->loginService ??= app(LoginService::class);
    }

    /**
     * Validation rules
     */
    protected function rules(): array
    {
        return [
            'email' => 'required|email|exists:users,email',
            'password' => 'required|string|min:8',
        ];
    }

    /**
     * Handle OTP login flow
     */
    protected function handleOtpLogin(User $user)
    {
        if (!$this->otpEnabled || !$user->otpEnabled()) {
            return null;
        }

        // 1️⃣ Attempt fast-login via trusted device
        if ($this->loginService()->loginWithTrustedDevice($user, $this->remember)) {
            return redirect()->route(
                $user->isProfileComplete() ? 'user.dashboard' : 'onboarding'
            );
        }

        // 2️⃣ Prepare OTP session
        session([
            'auth_email' => $this->email,
            'remember_login' => $this->remember,
            'otp_action' => 'login',
            'otp_expires_at' => now()->addMinutes(10),
        ]);

        // 3️⃣ Generate & send OTP
        try {
            app(OtpService::class)->generateAndSendOtp($this->email);
            Log::info('Login OTP sent.', ['email' => $this->email]);
        } catch (\Throwable $e) {
            session()->forget([
                'auth_email',
                'remember_login',
                'otp_action',
                'otp_expires_at',
            ]);

            Log::error('OTP send failed.', [
                'email' => $this->email,
                'error' => $e->getMessage(),
            ]);

            $this->addError('email', 'Failed to send verification code. Please try again.');
            return;
        }

        return $this->redirectRoute('user.verify.otp');
    }

    /**
     * Login using password
     */
    public function loginWithPassword()
    {
        $this->validate($this->rules());

        $user = User::where('email', $this->email)->firstOrFail();

        // OTP enabled? handle OTP flow
        if ($this->otpEnabled && $user->otpEnabled()) {
            return $this->handleOtpLogin($user);
        }

        // 1️⃣ Normal password login
        if (!Auth::attempt(['email' => $this->email, 'password' => $this->password], $this->remember)) {
            $this->addError('email', 'Invalid login credentials.');
            return;
        }

        // 2️⃣ Record login & trusted device (optional: false here)
        $this->loginService()->recordLogin($user, false, $this->remember);

        // 3️⃣ Redirect based on profile completeness
        return redirect()->route(
            $user->isProfileComplete() ? 'user.dashboard' : 'onboarding'
        );
    }

    /**
     * Form submit handler
     */
    public function submit()
    {
        $this->loginWithPassword();
    }
};