<?php

use Livewire\Component;
use Livewire\Attributes\Validate;
use Livewire\Attributes\Url;
use Illuminate\Support\Facades\RateLimiter;
use App\Models\TaxRefund;

new class extends Component {
    #[Url]
    #[Validate('required', message: 'Please provide a filing number')]
    #[Validate('regex:/^TR-\d{8}-\d{6}-[A-Z0-9]{4}$/', message: 'Invalid filing number format. Example: TR-12345678-123456-ABCD')]
    public string $filing_number;

    public ?int $blockedUntil = null; // UNIX timestamp when user can retry

    public function mount()
    {
        $user = auth()->user();
        $key = 'track-tax:' . $user->id;

        // Check existing rate limit
        if (RateLimiter::tooManyAttempts($key, 5)) {
            $seconds = max(1, RateLimiter::availableIn($key)); // Ensure at least 1 second
            $this->blockedUntil = now()->addSeconds($seconds)->timestamp;
            $this->dispatch('blocked-updated', blockedUntil: $this->blockedUntil);
        }

        if (!TaxRefund::where('user_id', $user->id)->exists()) {
            return redirect()
                ->route('user.tax.refund.index')
                ->with([
                    'message' => 'You do not have any tax refund records yet. Please start a new request.',
                    'type' => 'info',
                ]);
        }
    }

    public function trackTax()
    {
        $this->validate();
        $user = auth()->user();
        $refund = $user->taxRefund;

        if (!$refund) {
            $this->addError('filing_number', 'No tax refund found.');
            return;
        }

        $key = 'track-tax:' . $user->id;
        $maxAttempts = 5;
        $decaySeconds = 5 * 60; // 5 minutes

        // Check if blocked
        if (RateLimiter::tooManyAttempts($key, $maxAttempts)) {
            $seconds = max(1, RateLimiter::availableIn($key)); // Minimum 1 second
            $this->blockedUntil = now()->addSeconds($seconds)->timestamp;
            $this->dispatch('blocked-updated', blockedUntil: $this->blockedUntil);
            return;
        }

        // Hit rate limiter
        RateLimiter::hit($key, $decaySeconds);

        // Validate filing number
        if (strtoupper(trim($this->filing_number)) !== strtoupper($refund->filing_number)) {
            $this->addError('filing_number', 'Invalid Filing Number.');
            return;
        }

        // Success: clear rate limiter
        RateLimiter::clear($key);
        $this->blockedUntil = null;

        return redirect()->route('user.tax.refund.view', [
            'filing_number' => $refund->filing_number,
        ]);
    }
};
?>

<x-slot:title>
    {{ config('app.name') }} || Track Tax Refund
</x-slot:title>

<div class="space-y-6">

    <!-- Header / Navigation -->
    <div class="flex items-end justify-end gap-2 mb-4">
        <a href="{{ route('user.tax.refund.index') }}"
            class="flex items-center gap-1 px-3 py-2 rounded-md text-gray-800 dark:text-gray-100 hover:bg-gray-100 dark:hover:bg-gray-700 transition shadow-sm">
            <x-flux::icon.arrow-left variant="solid" class="w-4 h-4" />
            <span class="text-sm font-medium">Enroll</span>
        </a>
    </div>

    <!-- Card Wrapper -->
    <div
        class="bg-white dark:bg-gray-800/80 backdrop-blur-md border border-gray-200/50 dark:border-gray-700/50 
                rounded-2xl shadow-md dark:shadow-lg p-6 sm:p-8">

        <!-- Header Icon + Title -->
        <div class="flex flex-col items-center text-center space-y-3 mb-6">
            <div
                class="flex items-center justify-center w-16 h-16 rounded-full bg-sky-500/15 dark:bg-sky-400/20 text-sky-600 dark:text-sky-400 mb-2">
                <x-flux::icon.receipt-percent variant="solid" class="w-6 h-6" />
            </div>
            <h2 class="text-2xl font-semibold text-gray-900 dark:text-white">Enter Your Filing ID</h2>
            <p class="text-sm text-gray-600 dark:text-gray-400 max-w-md">
                Enter the filing ID provided by our support team to track your tax refund request.
            </p>
        </div>

        <!-- Info Notice -->
        <div
            class="flex gap-3 items-start rounded-lg border border-sky-300/70 dark:border-sky-400/40 bg-sky-50 dark:bg-sky-900/20 p-4 mb-6 text-sm text-sky-900 dark:text-sky-200">
            <div class="shrink-0 flex items-center justify-center w-6 h-6 rounded-full bg-sky-200 dark:bg-sky-800">
                <x-flux::icon.exclamation-triangle variant="solid" class="w-4 h-4 text-sky-700 dark:text-sky-300" />
            </div>
            <div class="space-y-1">
                <p class="font-semibold uppercase tracking-wide">Need a Filing ID?</p>
                <p class="text-xs text-sky-900 dark:text-sky-200">
                    Please contact our support team to receive your filing ID. This ID is required to process your
                    refund request.
                </p>
                <a href="{{ route('user.loans') }}"
                    class="inline-flex items-center gap-1 px-3 py-1.5 rounded-md bg-sky-600 text-white hover:bg-sky-700 transition shadow-sm mt-1 text-xs font-medium">
                    <x-flux::icon.chat-bubble-left-right variant="solid" class="w-4 h-4" />
                    Contact Support
                </a>
            </div>
        </div>

        <!-- Filing ID Form -->
        <div x-data="{
            blockedUntil: null,
            seconds: 0,
            interval: null,
        
            formatTime(seconds) {
                const m = Math.floor(seconds / 60);
                const s = seconds % 60;
                return m > 0 ?
                    `${m} minute${m > 1 ? 's' : ''}${s ? ' and ' + s + ' second' + (s > 1 ? 's' : '') : ''}` :
                    `${s} second${s !== 1 ? 's' : ''}`;
            },
        
            // Start or restart countdown
            startTimer() {
                // Clear previous interval if exists
                if (this.interval) clearInterval(this.interval);
        
                // If blockedUntil is not set, reset seconds
                if (!this.blockedUntil) {
                    this.seconds = 0;
                    return;
                }
        
                // Compute initial remaining seconds
                this.seconds = Math.max(Math.floor((this.blockedUntil * 1000 - Date.now()) / 1000), 0);
        
                // Start interval countdown
                this.interval = setInterval(() => {
                    this.seconds = Math.max(Math.floor((this.blockedUntil * 1000 - Date.now()) / 1000), 0);
        
                    if (this.seconds <= 0) {
                        clearInterval(this.interval);
                        this.blockedUntil = null;
                    }
                }, 1000);
            }
        }" x-init="// Watch for changes from Livewire events
        $watch('blockedUntil', () => startTimer());
        
        // Start timer if blockedUntil is already set (optional, for Livewire initial mount)
        if (@js($blockedUntil)) {
            blockedUntil = @js($blockedUntil);
            startTimer();
        }"
            x-on:blocked-updated.window="blockedUntil = $event.detail.blockedUntil">
            <form wire:submit.prevent="trackTax" class="space-y-5">
                <section>
                    <flux:input icon:trailing="shield-check" label="Filing ID" wire:model.live.blur="filing_number"
                        placeholder="Enter your filing ID" required />
                </section>

                <div class="flex items-end justify-end">
                    <flux:button type="submit" variant="primary" color="sky" icon="send"
                        x-bind:disabled="seconds > 0">
                        Submit Filing ID
                    </flux:button>
                </div>

                <template x-if="seconds > 0">
                    <p class="mt-2 text-sm text-red-600 dark:text-red-400">
                        Too many attempts. Try again in <span x-text="formatTime(seconds)"></span>.
                    </p>
                </template>
            </form>
        </div>


    </div>
</div>
