<x-app-layout>

    <x-module-hero
        title="Payment Status"
        description="Track your payment processing in real time"
        icon="fa-hourglass-half">

        <x-slot name="backButton">
            @if($paymentType === 'institution')
            <a href="{{ route('dashboard.institutions.index') }}"
               class="inline-flex items-center gap-2 text-white/80 hover:text-white text-sm transition-colors">
                <i class="fas fa-arrow-left"></i> Back to Institutions
            </a>
            @else
            <a href="{{ route('dashboard.machines.index') }}"
               class="inline-flex items-center gap-2 text-white/80 hover:text-white text-sm transition-colors">
                <i class="fas fa-arrow-left"></i> Back to Machines
            </a>
            @endif
        </x-slot>

    </x-module-hero>

    <div class="p-6">
        <div class="max-w-5xl mx-auto">

            {{-- Status Card --}}
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden"
                 x-data="paymentStatusTracker({{ $payment->id }}, '{{ $paymentType }}', '{{ $payment->status }}')"
                 x-init="initPolling()">

                {{-- Status Display --}}
                <div class="p-8 text-center">

                    {{-- Processing --}}
                    <div x-show="status === 'pending' || status === 'processing'">
                        <div class="w-24 h-24 rounded-full bg-yellow-100 flex items-center justify-center mx-auto mb-4">
                            <i class="fas fa-mobile-alt text-yellow-600 text-4xl"></i>
                        </div>
                        <h3 class="text-xl font-semibold text-gray-800 mb-2">Waiting for Payment Approval</h3>
                        <p class="text-gray-600 mb-6">A payment request has been sent to your phone. Please check your phone and approve the MTN MoMo prompt.</p>
                        <div class="flex items-center justify-center gap-2 text-yellow-600">
                            <i class="fas fa-circle-notch fa-spin"></i>
                            <span class="text-sm">Checking payment status...</span>
                        </div>
                    </div>

                    {{-- Success --}}
                    <div x-show="status === 'successful'" x-transition>
                        <div class="w-24 h-24 rounded-full bg-green-100 flex items-center justify-center mx-auto mb-4">
                            <i class="fas fa-check text-green-600 text-4xl"></i>
                        </div>
                        <h3 class="text-xl font-semibold text-green-600 mb-2">Payment Successful!</h3>
                        <p class="text-gray-600 mb-6">Your payment has been processed successfully. Your listing is now active.</p>
                        <a :href="redirectUrl"
                           class="inline-flex items-center gap-2 px-6 py-3 text-white rounded-lg transition-colors"
                           style="background-color: var(--theme-bg-sidebar);">
                            <i class="fas fa-arrow-right"></i> Continue
                        </a>
                    </div>

                    {{-- Failed --}}
                    <div x-show="status === 'failed' || status === 'timeout' || status === 'cancelled'" x-transition>
                        <div class="w-24 h-24 rounded-full bg-red-100 flex items-center justify-center mx-auto mb-4">
                            <i class="fas fa-times text-red-600 text-4xl"></i>
                        </div>
                        <h3 class="text-xl font-semibold text-red-600 mb-2">Payment Failed</h3>
                        <p class="text-gray-600 mb-6" x-text="failMessage || 'Payment was not completed. Please try again.'"></p>
                        <a :href="retryUrl"
                           class="inline-flex items-center gap-2 px-6 py-3 bg-amber-500 text-white rounded-lg hover:bg-amber-600 transition-colors">
                            <i class="fas fa-redo"></i> Try Again
                        </a>
                    </div>

                </div>

                {{-- Payment Details --}}
                <div class="border-t border-gray-200 p-6">
                    <h4 class="font-semibold text-gray-800 mb-4 text-sm">Payment Details</h4>
                    <div class="grid grid-cols-2 gap-3 text-sm">
                        <div class="text-gray-500">Reference</div>
                        <div class="font-medium text-gray-800 font-mono text-xs">{{ $payment->reference }}</div>

                        <div class="text-gray-500">Amount</div>
                        <div class="font-semibold text-gray-800">{{ $payment->formatted_amount }}</div>

                        <div class="text-gray-500">Phone Number</div>
                        <div class="font-medium text-gray-800">{{ $payment->phone_number ?? '—' }}</div>

                        <div class="text-gray-500">Frequency</div>
                        <div class="font-medium text-gray-800">{{ $payment->frequency_label }}</div>

                        <div class="text-gray-500">Status</div>
                        <div class="font-medium text-gray-800 capitalize" x-text="status">{{ $payment->status }}</div>
                    </div>
                </div>

                {{-- Tips --}}
                <div class="bg-gray-50 border-t border-gray-200 p-6">
                    <h4 class="text-sm font-semibold text-gray-700 mb-3 flex items-center gap-2">
                        <i class="fas fa-info-circle text-blue-500"></i> Tips
                    </h4>
                    <ul class="text-sm text-gray-600 space-y-2">
                        <li class="flex items-center gap-2"><i class="fas fa-check text-green-500 w-4"></i> Keep this page open while completing payment</li>
                        <li class="flex items-center gap-2"><i class="fas fa-check text-green-500 w-4"></i> Check your phone for the MTN MoMo prompt</li>
                        <li class="flex items-center gap-2"><i class="fas fa-check text-green-500 w-4"></i> Enter your PIN to approve the payment</li>
                    </ul>
                </div>

            </div>
        </div>
    </div>

</x-app-layout>

<script>
function paymentStatusTracker(paymentId, paymentType, initialStatus) {
    return {
        paymentId: paymentId,
        paymentType: paymentType,
        status: initialStatus,
        failMessage: '',
        redirectUrl: paymentType === 'institution'
            ? '{{ route("dashboard.institutions.index") }}'
            : '{{ route("dashboard.machines.index") }}',
        retryUrl: paymentType === 'institution'
            ? '{{ route("dashboard.institutions.index") }}'
            : '{{ route("dashboard.machines.index") }}',
        pollInterval: null,

        initPolling() {
            if (this.status === 'pending' || this.status === 'processing') {
                this.pollInterval = setInterval(() => {
                    this.checkStatus();
                }, 5000);
            }
        },

        async checkStatus() {
            try {
                const response = await fetch(`/payments/check/${this.paymentId}?type=${this.paymentType}`);
                const data = await response.json();

                if (data.success) {
                    this.status = data.status;

                    if (this.status !== 'pending' && this.status !== 'processing') {
                        clearInterval(this.pollInterval);

                        if (this.status === 'failed' || this.status === 'timeout' || this.status === 'cancelled') {
                            this.failMessage = data.message || 'Payment was not completed. Please try again.';
                        }
                    }
                }
            } catch (error) {
                console.error('Error checking payment status:', error);
            }
        }
    }
}
</script>
