import { Head, Link, router } from '@inertiajs/react';
import { useState, useEffect, useRef, useCallback } from 'react';
import UserLayout from '@/components/Layouts/UserLayout';

interface TopupCoinStatusProps {
    transaction: {
        id: number;
        reference_code: string;
        payment_channel: string;
        amount: number;
        coins: number;
        fee: number;
        status: string;
        payment_url?: string;
        qr_code_url?: string;
        paid_at?: string;
        expires_at?: string;
        created_at: string;
    };
    coin_name: string;
    coin_abbreviation: string;
}

export default function TopupCoinStatus({ transaction, coin_name, coin_abbreviation }: TopupCoinStatusProps) {
    const [isChecking, setIsChecking] = useState(false);
    const [lastChecked, setLastChecked] = useState<Date | null>(null);
    const intervalRef = useRef<NodeJS.Timeout | null>(null);
    const POLLING_INTERVAL = 5000; // 5 detik

    // Check if status should be polled
    const shouldPoll = transaction.status === 'pending' || transaction.status === 'processing';

    // Manual check function
    const checkStatus = useCallback(() => {
        setIsChecking(true);
        router.reload({
            only: ['transaction'],
            onFinish: () => {
                setIsChecking(false);
                setLastChecked(new Date());
            },
        });
    }, []);

    // Auto polling with setInterval
    useEffect(() => {
        if (shouldPoll) {
            // Start polling
            intervalRef.current = setInterval(() => {
                checkStatus();
            }, POLLING_INTERVAL);

            // Cleanup on unmount or when status changes
            return () => {
                if (intervalRef.current) {
                    clearInterval(intervalRef.current);
                }
            };
        } else {
            // Stop polling if status is final
            if (intervalRef.current) {
                clearInterval(intervalRef.current);
                intervalRef.current = null;
            }
        }
    }, [shouldPoll, checkStatus]);

    // Set initial lastChecked time
    useEffect(() => {
        if (shouldPoll && !lastChecked) {
            setLastChecked(new Date());
        }
    }, []);

    // Cleanup on unmount
    useEffect(() => {
        return () => {
            if (intervalRef.current) {
                clearInterval(intervalRef.current);
            }
        };
    }, []);

    const formatPrice = (price: number): string => {
        return new Intl.NumberFormat('id-ID', {
            style: 'currency',
            currency: 'IDR',
            minimumFractionDigits: 0,
        }).format(price);
    };

    const getStatusConfig = () => {
        switch (transaction.status) {
            case 'success':
                return {
                    icon: CheckCircleIcon,
                    color: 'text-green-600 dark:text-green-400',
                    bgColor: 'bg-green-100 dark:bg-green-900/30',
                    title: 'Pembayaran Berhasil',
                    message: `Anda telah berhasil topup ${transaction.coins.toLocaleString('id-ID')} ${coin_abbreviation}`,
                };
            case 'processing':
                return {
                    icon: ClockIcon,
                    color: 'text-yellow-600 dark:text-yellow-400',
                    bgColor: 'bg-yellow-100 dark:bg-yellow-900/30',
                    title: 'Pembayaran Sedang Diproses',
                    message: 'Pembayaran Anda sedang diproses. Silakan tunggu konfirmasi.',
                };
            case 'failed':
                return {
                    icon: XCircleIcon,
                    color: 'text-red-600 dark:text-red-400',
                    bgColor: 'bg-red-100 dark:bg-red-900/30',
                    title: 'Pembayaran Gagal',
                    message: 'Pembayaran Anda gagal. Silakan coba lagi.',
                };
            case 'cancelled':
                return {
                    icon: XCircleIcon,
                    color: 'text-gray-600 dark:text-gray-400',
                    bgColor: 'bg-gray-100 dark:bg-gray-800',
                    title: 'Pembayaran Dibatalkan',
                    message: 'Pembayaran Anda telah dibatalkan atau kedaluwarsa.',
                };
            default:
                return {
                    icon: ClockIcon,
                    color: 'text-gray-600 dark:text-gray-400',
                    bgColor: 'bg-gray-100 dark:bg-gray-800',
                    title: 'Menunggu Pembayaran',
                    message: 'Silakan selesaikan pembayaran Anda.',
                };
        }
    };

    const statusConfig = getStatusConfig();
    const StatusIcon = statusConfig.icon;

    return (
        <UserLayout title="Status Topup Coin">
            <Head title="Status Topup Coin" />
            <div className="mx-auto max-w-2xl space-y-6">
                {/* Status Card */}
                <div className={`rounded-xl border-2 p-6 ${statusConfig.bgColor} border-current/20`}>
                    <div className="flex items-start gap-4">
                        <div className={`flex h-12 w-12 shrink-0 items-center justify-center rounded-full ${statusConfig.bgColor}`}>
                            <StatusIcon className={`h-6 w-6 ${statusConfig.color}`} />
                        </div>
                        <div className="flex-1">
                            <h1 className={`text-2xl font-bold ${statusConfig.color}`}>{statusConfig.title}</h1>
                            <p className="mt-2 text-sm text-gray-600 dark:text-gray-300">{statusConfig.message}</p>
                        </div>
                    </div>
                </div>

                {/* Transaction Details */}
                <div className="rounded-lg border border-gray-200 bg-white p-6 dark:border-gray-700 dark:bg-gray-800">
                    <h2 className="mb-4 text-lg font-semibold text-gray-900 dark:text-white">Detail Transaksi</h2>
                    <dl className="space-y-4">
                        <div className="flex justify-between">
                            <dt className="text-sm font-medium text-gray-500 dark:text-gray-400">Reference Code</dt>
                            <dd className="text-sm font-mono text-gray-900 dark:text-white">{transaction.reference_code}</dd>
                        </div>
                        <div className="flex justify-between">
                            <dt className="text-sm font-medium text-gray-500 dark:text-gray-400">Metode Pembayaran</dt>
                            <dd className="text-sm text-gray-900 dark:text-white">{transaction.payment_channel}</dd>
                        </div>
                        <div className="flex justify-between">
                            <dt className="text-sm font-medium text-gray-500 dark:text-gray-400">Jumlah Pembayaran</dt>
                            <dd className="text-sm font-semibold text-gray-900 dark:text-white">{formatPrice(transaction.amount)}</dd>
                        </div>
                        {transaction.fee > 0 && (
                            <div className="flex justify-between">
                                <dt className="text-sm font-medium text-gray-500 dark:text-gray-400">Biaya Admin</dt>
                                <dd className="text-sm text-gray-900 dark:text-white">{formatPrice(transaction.fee)}</dd>
                            </div>
                        )}
                        <div className="flex justify-between border-t border-gray-200 pt-4 dark:border-gray-700">
                            <dt className="text-sm font-semibold text-gray-900 dark:text-white">Total {coin_name}</dt>
                            <dd className="text-lg font-bold text-[#d4af37] dark:text-[#b8941f]">
                                {transaction.coins.toLocaleString('id-ID')} {coin_abbreviation}
                            </dd>
                        </div>
                        <div className="flex justify-between">
                            <dt className="text-sm font-medium text-gray-500 dark:text-gray-400">Status</dt>
                            <dd className="flex items-center gap-2">
                                <span className="text-sm font-semibold capitalize text-gray-900 dark:text-white">{transaction.status}</span>
                                {shouldPoll && (
                                    <span className="inline-flex h-2 w-2 animate-pulse rounded-full bg-yellow-500"></span>
                                )}
                            </dd>
                        </div>
                        {shouldPoll && lastChecked && (
                            <div className="flex justify-between border-t border-gray-200 pt-2 dark:border-gray-700">
                                <dt className="text-xs font-medium text-gray-400 dark:text-gray-500">Terakhir dicek</dt>
                                <dd className="text-xs text-gray-500 dark:text-gray-400">
                                    {lastChecked.toLocaleTimeString('id-ID')}
                                </dd>
                            </div>
                        )}
                        {transaction.paid_at && (
                            <div className="flex justify-between">
                                <dt className="text-sm font-medium text-gray-500 dark:text-gray-400">Waktu Pembayaran</dt>
                                <dd className="text-sm text-gray-900 dark:text-white">
                                    {new Date(transaction.paid_at).toLocaleString('id-ID')}
                                </dd>
                            </div>
                        )}
                        <div className="flex justify-between">
                            <dt className="text-sm font-medium text-gray-500 dark:text-gray-400">Waktu Transaksi</dt>
                            <dd className="text-sm text-gray-900 dark:text-white">
                                {new Date(transaction.created_at).toLocaleString('id-ID')}
                            </dd>
                        </div>
                    </dl>
                </div>

                {/* QR Code Display for QRIS */}
                {transaction.payment_channel === 'QRIS' && transaction.qr_code_url && (transaction.status === 'pending' || transaction.status === 'processing') && (
                    <div className="rounded-lg border border-gray-200 bg-white p-6 dark:border-gray-700 dark:bg-gray-800">
                        <div className="text-center">
                            <h2 className="mb-2 text-lg font-semibold text-gray-900 dark:text-white">
                                Scan QR Code untuk Membayar
                            </h2>
                            <p className="mb-4 text-sm text-gray-600 dark:text-gray-400">
                                Gunakan aplikasi e-wallet atau mobile banking untuk scan QR code di bawah ini
                            </p>
                            
                            {/* QR Code Container */}
                            <div className="mx-auto mb-4 inline-block rounded-xl border-4 border-gray-200 bg-white p-4 shadow-lg dark:border-gray-700 dark:bg-gray-900">
                                <img
                                    src={transaction.qr_code_url}
                                    alt="QR Code Pembayaran"
                                    className="h-64 w-64 object-contain"
                                />
                            </div>

                            {/* Amount Display */}
                            <div className="rounded-lg bg-[#d4af37]/10 px-4 py-3 dark:bg-[#b8941f]/20">
                                <p className="text-xs font-medium text-gray-600 dark:text-gray-400">Total Pembayaran</p>
                                <p className="mt-1 text-xl font-bold text-[#d4af37] dark:text-[#b8941f]">
                                    {formatPrice(transaction.amount + transaction.fee)}
                                </p>
                            </div>

                            {/* Expiry Info */}
                            {transaction.expires_at && (
                                <p className="mt-4 text-xs text-gray-500 dark:text-gray-400">
                                    QR Code berlaku hingga:{' '}
                                    <span className="font-medium">
                                        {new Date(transaction.expires_at).toLocaleString('id-ID', {
                                            day: 'numeric',
                                            month: 'long',
                                            year: 'numeric',
                                            hour: '2-digit',
                                            minute: '2-digit',
                                        })}
                                    </span>
                                </p>
                            )}

                            {/* Instructions */}
                            <div className="mt-6 rounded-lg bg-blue-50 p-4 text-left dark:bg-blue-900/20">
                                <p className="mb-2 text-sm font-semibold text-blue-900 dark:text-blue-300">
                                    Cara Membayar:
                                </p>
                                <ol className="list-decimal space-y-1 pl-5 text-xs text-blue-800 dark:text-blue-200">
                                    <li>Buka aplikasi e-wallet atau mobile banking Anda</li>
                                    <li>Pilih fitur Scan QR Code</li>
                                    <li>Scan QR code di atas</li>
                                    <li>Konfirmasi pembayaran</li>
                                    <li>Tunggu konfirmasi otomatis (biasanya 1-2 menit)</li>
                                </ol>
                            </div>
                        </div>
                    </div>
                )}

                {/* Manual Check Button */}
                {shouldPoll && (
                    <div className="rounded-lg border border-gray-200 bg-white p-4 dark:border-gray-700 dark:bg-gray-800">
                        <div className="flex items-center justify-between">
                            <div>
                                <p className="text-sm font-medium text-gray-900 dark:text-white">
                                    Pengecekan Otomatis Aktif
                                </p>
                                <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                                    Status akan dicek setiap {POLLING_INTERVAL / 1000} detik
                                </p>
                            </div>
                            <button
                                onClick={checkStatus}
                                disabled={isChecking}
                                className="flex items-center gap-2 rounded-lg bg-[#d4af37] px-4 py-2 text-sm font-semibold text-white hover:bg-[#b8941f] disabled:opacity-50 disabled:cursor-not-allowed dark:bg-[#b8941f] dark:hover:bg-[#9a7d15]"
                            >
                                {isChecking ? (
                                    <>
                                        <RefreshIcon className="h-4 w-4 animate-spin" />
                                        <span>Mengecek...</span>
                                    </>
                                ) : (
                                    <>
                                        <RefreshIcon className="h-4 w-4" />
                                        <span>Cek Sekarang</span>
                                    </>
                                )}
                            </button>
                        </div>
                    </div>
                )}

                {/* Actions */}
                <div className="flex flex-col gap-3 sm:flex-row">
                    {transaction.status === 'pending' && transaction.payment_url && !transaction.qr_code_url && (
                        <a
                            href={transaction.payment_url}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="flex-1 rounded-lg bg-[#d4af37] px-4 py-3 text-center text-sm font-semibold text-white hover:bg-[#b8941f] dark:bg-[#b8941f] dark:hover:bg-[#9a7d15]"
                        >
                            Lanjutkan Pembayaran
                        </a>
                    )}
                    <Link
                        href="/topup-coin"
                        className="flex-1 rounded-lg border border-gray-300 bg-white px-4 py-3 text-center text-sm font-semibold text-gray-700 hover:bg-gray-50 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-300 dark:hover:bg-gray-700"
                    >
                        Topup Lagi
                    </Link>
                    <Link
                        href="/dashboard"
                        className="flex-1 rounded-lg border border-gray-300 bg-white px-4 py-3 text-center text-sm font-semibold text-gray-700 hover:bg-gray-50 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-300 dark:hover:bg-gray-700"
                    >
                        Kembali ke Dashboard
                    </Link>
                </div>
            </div>
        </UserLayout>
    );
}

// Icons
function CheckCircleIcon({ className }: { className?: string }) {
    return (
        <svg className={className} fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" d="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
        </svg>
    );
}

function ClockIcon({ className }: { className?: string }) {
    return (
        <svg className={className} fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" d="M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z" />
        </svg>
    );
}

function XCircleIcon({ className }: { className?: string }) {
    return (
        <svg className={className} fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" d="M9.75 9.75l4.5 4.5m0-4.5l-4.5 4.5M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
        </svg>
    );
}

function RefreshIcon({ className }: { className?: string }) {
    return (
        <svg className={className} fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M4.031 9.865a8.25 8.25 0 0113.803-3.7l3.181 3.182m0-4.991v4.99" />
        </svg>
    );
}

