<?php

namespace App\Livewire\Auth;

use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;

class OtpVerify extends Component
{
    public string $otp = '';

    public bool $loading = false;
    
    public string $formattedRemaining = '';

    public function mount(): void
    {
        // If user is already verified/active, redirect to home
        if (Auth::check() && Auth::user()->status !== User::STATUS_INACTIVE) {
            $this->redirectRoute('home', navigate: true);
        }

        // Initialize or retrieve the OTP sent timestamp
        if (! session()->has('otp_expires_at')) {
            session(['otp_expires_at' => now()->addMinutes(10)]);
        }

        $this->updateFormattedRemaining();
    }

    public function updateFormattedRemaining(): void
    {
        $otpExpiresAt = session('otp_expires_at', now()->addMinutes(10));
        $expiresAt = $otpExpiresAt instanceof \Carbon\Carbon
            ? $otpExpiresAt
            : \Carbon\Carbon::parse($otpExpiresAt);
        $remaining = $expiresAt->getTimestamp() - now()->getTimestamp();
        $seconds = max(0, (int) $remaining);

        if ($seconds == 0) {
            $this->formattedRemaining = '';
        } elseif ($seconds >= 60) {
            $minutes = (int) floor($seconds / 60);
            $secs = $seconds % 60;
            $this->formattedRemaining = sprintf('%d:%02d', $minutes, $secs);
        } else {
            $this->formattedRemaining = $seconds.' seconde'.($seconds != 1 ? 's' : '');
        }
    }

    public function verify(): void
    {
        $this->loading = true;
        $email = session('pending_user_email');
        $token = session('pending_user_token');

        if (! $email || ! $token) {
            $this->addError('verify', 'Session OTP invalide. Veuillez vous reconnecter.');
            $this->otp = '';
            $this->loading = false;
            return;
        }

        $this->validate([
            'otp' => ['required', 'string', 'min:4'],
        ]);
        
        $result = verifyToken($email, $this->otp, $token);

        if (! $result['success']) {
            $this->addError('verify', $result['message'] ?? 'Code OTP invalide.');
            $this->otp = '';
            return;
        }

        // Clear all OTP-related session data
        session()->forget(['otp_expires_at', 'pending_user_email', 'pending_user_token', 'pending_user_id']);
        $this->redirectRoute('home', navigate: true);
    }

    public function resend(): void
    {
        // if (! $this->canResend) {
        //     $this->addError('resend', 'Veuillez attendre avant de renvoyer le code.');
        //     return;
        // }
        $this->loading = true;
        $email = session('pending_user_email');
        $token = session('pending_user_token');
        if (! $email || ! $token) {
            $this->addError('resend', 'Session OTP invalide.');
            $this->loading = false;

            return;
        }
        $result = resendOtp($email, $token);
        $this->loading = false;
        if (! $result['success']) {
            $this->addError('resend', $result['message'] ?? 'Impossible de renvoyer le code OTP.');
        } else {
            // Reset the timer on successful resend
            session(['otp_expires_at' => now()->addMinutes(10)]);
            $this->updateFormattedRemaining();
            session()->flash('success', 'Code OTP renvoyé avec succès.');
        }
    }

    public function logout(): void
    {
        Auth::logout();
        session()->invalidate();
        session()->regenerateToken();
        $this->redirectRoute('login', navigate: true);
    }

    public function render()
    {
        return view('livewire.auth.otp-verify');
    }
}
