'use client'

import { useEffect, useState, useCallback, useRef } from 'react'
import { useParams, useRouter } from 'next/navigation'
import { CheckCircle, Clock, Copy, XCircle, Loader2, QrCode, CreditCard, ArrowLeft, Crown, ClipboardList } from 'lucide-react'
import { QRCodeSVG } from 'qrcode.react'

function formatCurrency(amount: number | string): string {
  const num = typeof amount === 'string' ? parseFloat(amount) : amount
  return new Intl.NumberFormat('id-ID', { style: 'currency', currency: 'IDR', minimumFractionDigits: 0 }).format(num)
}

const CHANNEL_LABELS: Record<string, string> = {
  bca: 'BCA',
  bni: 'BNI',
  bri: 'BRI',
  mandiri: 'Mandiri',
  cimb: 'CIMB Niaga',
  permata: 'Permata',
  qris: 'QRIS',
}

export default function PaymentStatusPage() {
  const params = useParams()
  const router = useRouter()
  const referenceId = params.referenceId as string
  const [data, setData] = useState<any>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [copied, setCopied] = useState(false)
  const [timeLeft, setTimeLeft] = useState('')
  const [redirectCountdown, setRedirectCountdown] = useState(5)
  const hasRedirectedRef = useRef(false)

  const fetchStatus = useCallback(async () => {
    try {
      const res = await fetch(`/api/public/payment/status/${referenceId}`)
      const d = await res.json()
      if (!res.ok) throw new Error(d.error)
      setData(d)
      if (!loading) return // Don't reset loading after first fetch
    } catch (err: any) {
      setError(err.message || 'Gagal memuat status pembayaran')
    } finally {
      setLoading(false)
    }
  }, [referenceId, loading])

  useEffect(() => {
    fetchStatus()
  }, []) // eslint-disable-line react-hooks/exhaustive-deps

  // Poll every 3 seconds if pending
  useEffect(() => {
    if (!data || data.status !== 'pending') return
    const interval = setInterval(fetchStatus, 3000)
    return () => clearInterval(interval)
  }, [data?.status, fetchStatus])

  // Countdown timer
  useEffect(() => {
    if (!data?.expired || data.status !== 'pending') return
    const updateTimer = () => {
      const now = new Date().getTime()
      const exp = new Date(data.expired).getTime()
      const diff = exp - now
      if (diff <= 0) {
        setTimeLeft('Kedaluwarsa')
        return
      }
      const hours = Math.floor(diff / (1000 * 60 * 60))
      const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
      const seconds = Math.floor((diff % (1000 * 60)) / 1000)
      if (hours > 0) {
        setTimeLeft(`${hours}j ${minutes}m ${seconds}d`)
      } else {
        setTimeLeft(`${minutes}m ${seconds}d`)
      }
    }
    updateTimer()
    const interval = setInterval(updateTimer, 1000)
    return () => clearInterval(interval)
  }, [data?.expired, data?.status])

  // Auto-redirect to public menu orders tab after payment success (order only)
  useEffect(() => {
    if (!data || data.status !== 'paid' || data.type !== 'order') return
    if (!data.menuCode) return
    if (hasRedirectedRef.current) return

    const timer = setInterval(() => {
      setRedirectCountdown(prev => {
        if (prev <= 1) {
          clearInterval(timer)
          hasRedirectedRef.current = true
          const tablePath = data.order?.tableNumber ? `/${data.order.tableNumber}` : ''
          router.push(`/menu/${data.menuCode}${tablePath}?tab=orders`)
          return 0
        }
        return prev - 1
      })
    }, 1000)

    return () => clearInterval(timer)
  }, [data, router])

  const handleCopy = () => {
    if (data?.paymentNo) {
      navigator.clipboard.writeText(data.paymentNo)
      setCopied(true)
      setTimeout(() => setCopied(false), 2000)
    }
  }

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="text-center">
          <Loader2 className="w-10 h-10 animate-spin text-primary-600 mx-auto mb-3" />
          <p className="text-gray-500">Memuat status pembayaran...</p>
        </div>
      </div>
    )
  }

  if (error) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50 p-4">
        <div className="text-center max-w-sm">
          <XCircle className="w-16 h-16 text-red-400 mx-auto mb-4" />
          <h1 className="text-xl font-bold text-gray-900 mb-2">Pembayaran Tidak Ditemukan</h1>
          <p className="text-gray-600">{error}</p>
        </div>
      </div>
    )
  }

  // Payment Success
  if (data.status === 'paid') {
    // Subscription payment success
    if (data.type === 'subscription' && data.subscription) {
      return (
        <div className="min-h-screen flex items-center justify-center bg-green-50 p-4">
          <div className="text-center max-w-sm w-full">
            <div className="w-20 h-20 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4 animate-bounce">
              <Crown className="w-10 h-10 text-green-600" />
            </div>
            <h1 className="text-2xl font-bold text-green-900 mb-2">Langganan Berhasil!</h1>
            <p className="text-green-700 mb-6">Paket {data.subscription.planName} telah aktif.</p>
            <div className="bg-white rounded-xl p-5 shadow-sm text-left space-y-3">
              <div className="text-center">
                <p className="text-sm text-gray-500">Paket Langganan</p>
                <p className="text-2xl font-bold text-primary-600">{data.subscription.planName}</p>
              </div>
              <div className="flex justify-between text-sm">
                <span className="text-gray-500">Siklus</span>
                <span className="font-medium">{data.subscription.billingCycle === 'monthly' ? 'Bulanan' : 'Tahunan'}</span>
              </div>
              <div className="flex justify-between text-sm">
                <span className="text-gray-500">Total Dibayar</span>
                <span className="font-bold text-lg">{formatCurrency(data.amount)}</span>
              </div>
            </div>
            <a href="/dashboard/subscription" className="btn-primary w-full flex items-center justify-center gap-2 mt-4">
              Ke Dashboard
            </a>
          </div>
        </div>
      )
    }

    // Order payment success
    const menuUrl = data.menuCode
      ? `/menu/${data.menuCode}${data.order?.tableNumber ? `/${data.order.tableNumber}` : ''}?tab=orders`
      : null

    return (
      <div className="min-h-screen flex items-center justify-center bg-green-50 p-4">
        <div className="text-center max-w-sm w-full">
          <div className="w-20 h-20 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4 animate-bounce">
            <CheckCircle className="w-10 h-10 text-green-600" />
          </div>
          <h1 className="text-2xl font-bold text-green-900 mb-2">Pembayaran Berhasil!</h1>
          <p className="text-green-700 mb-6">Terima kasih, pesanan Anda sedang diproses.</p>
          <div className="bg-white rounded-xl p-5 shadow-sm text-left space-y-3">
            <div className="text-center">
              <p className="text-sm text-gray-500">Nomor Pesanan</p>
              <p className="text-2xl font-bold font-mono text-primary-600">{data.order?.orderNumber}</p>
            </div>
            <div className="flex justify-between text-sm">
              <span className="text-gray-500">Total Dibayar</span>
              <span className="font-bold text-lg">{formatCurrency(data.amount)}</span>
            </div>
            <div className="flex justify-between text-sm">
              <span className="text-gray-500">Via</span>
              <span className="font-medium">{CHANNEL_LABELS[data.paymentChannel] || data.paymentChannel}</span>
            </div>
          </div>
          {menuUrl && (
            <div className="mt-4 space-y-2">
              <a href={menuUrl} className="btn-primary w-full flex items-center justify-center gap-2">
                <ClipboardList className="w-4 h-4" /> Lacak Pesanan
              </a>
              <p className="text-xs text-gray-400">Redirect otomatis dalam {redirectCountdown} detik...</p>
            </div>
          )}
        </div>
      </div>
    )
  }

  // Payment Expired/Failed
  if (data.status === 'expired' || data.status === 'failed') {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50 p-4">
        <div className="text-center max-w-sm w-full">
          <div className="w-20 h-20 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
            <XCircle className="w-10 h-10 text-red-500" />
          </div>
          <h1 className="text-2xl font-bold text-gray-900 mb-2">
            {data.status === 'expired' ? 'Pembayaran Kedaluwarsa' : 'Pembayaran Gagal'}
          </h1>
          <p className="text-gray-600 mb-6">
            {data.type === 'subscription'
              ? 'Silakan coba upgrade paket kembali.'
              : 'Silakan buat pesanan baru atau bayar di kasir.'}
          </p>
          <button onClick={() => {
            if (data.type === 'subscription') {
              window.location.href = '/dashboard/subscription'
            } else {
              window.history.back()
            }
          }} className="btn-primary w-full flex items-center justify-center gap-2">
            <ArrowLeft className="w-4 h-4" /> {data.type === 'subscription' ? 'Ke Langganan' : 'Kembali'}
          </button>
        </div>
      </div>
    )
  }

  // Payment Pending
  return (
    <div className="min-h-screen bg-gray-50 p-4">
      <div className="max-w-sm mx-auto pt-6">
        {/* Header */}
        <div className="text-center mb-6">
          <div className="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-3">
            {data.paymentMethod === 'qris' ? <QrCode className="w-8 h-8 text-blue-600" /> : <CreditCard className="w-8 h-8 text-blue-600" />}
          </div>
          <h1 className="text-xl font-bold text-gray-900">Menunggu Pembayaran</h1>
          <p className="text-sm text-gray-500 mt-1">Selesaikan pembayaran sebelum waktu habis</p>
        </div>

        {/* Timer */}
        <div className="bg-red-50 border border-red-200 rounded-xl p-3 mb-4 text-center">
          <div className="flex items-center justify-center gap-2">
            <Clock className="w-4 h-4 text-red-600" />
            <span className="text-sm text-red-700 font-medium">Sisa waktu:</span>
            <span className="text-lg font-bold text-red-800 font-mono">{timeLeft || '...'}</span>
          </div>
        </div>

        {/* Order/Subscription Info */}
        <div className="bg-white rounded-xl p-4 shadow-sm mb-4">
          {data.type === 'subscription' && data.subscription ? (
            <>
              <div className="text-center mb-3">
                <p className="text-sm text-gray-500">Langganan Paket</p>
                <p className="text-lg font-bold text-primary-600">{data.subscription.planName}</p>
                <p className="text-xs text-gray-400">{data.subscription.billingCycle === 'monthly' ? 'Bulanan' : 'Tahunan'}</p>
              </div>
              <div className="flex justify-between text-sm">
                <span className="text-gray-500">Total Pembayaran</span>
                <span className="text-xl font-bold text-gray-900">{formatCurrency(data.amount)}</span>
              </div>
            </>
          ) : (
            <>
              <div className="text-center mb-3">
                <p className="text-sm text-gray-500">Nomor Pesanan</p>
                <p className="text-lg font-bold font-mono text-primary-600">{data.order?.orderNumber}</p>
              </div>
              <div className="flex justify-between text-sm">
                <span className="text-gray-500">Total Pembayaran</span>
                <span className="text-xl font-bold text-gray-900">{formatCurrency(data.amount)}</span>
              </div>
            </>
          )}
        </div>

        {/* Payment Info */}
        <div className="bg-white rounded-xl p-4 shadow-sm mb-4">
          {data.paymentMethod === 'qris' ? (
            // QRIS Display
            <div className="text-center">
              <p className="text-sm font-medium text-gray-700 mb-3">Scan QR Code untuk Membayar</p>
              {data.qrisUrl ? (
                <div className="bg-white border-2 border-gray-200 rounded-xl p-4 inline-block mb-3">
                  <img src={data.qrisUrl} alt="QRIS Code" className="w-48 h-48 mx-auto" />
                </div>
              ) : data.paymentNo ? (
                <div className="bg-white border-2 border-gray-200 rounded-xl p-4 inline-block mb-3">
                  <QRCodeSVG value={data.paymentNo} size={192} level="M" />
                </div>
              ) : null}
              <p className="text-xs text-gray-500">Gunakan aplikasi e-wallet atau mobile banking untuk scan</p>
            </div>
          ) : (
            // Virtual Account Display
            <div>
              <div className="flex items-center justify-between mb-3">
                <p className="text-sm font-medium text-gray-700">Transfer ke Virtual Account</p>
                <span className="text-xs font-medium bg-blue-100 text-blue-700 px-2 py-1 rounded-full">
                  {CHANNEL_LABELS[data.paymentChannel] || data.paymentChannel}
                </span>
              </div>
              <div className="bg-gray-50 border-2 border-dashed border-gray-300 rounded-xl p-4 text-center mb-3">
                <p className="text-xs text-gray-500 mb-1">Nomor Virtual Account</p>
                <p className="text-2xl font-bold font-mono tracking-wider text-gray-900">{data.paymentNo || '-'}</p>
              </div>
              <button
                onClick={handleCopy}
                className="w-full py-2.5 border border-gray-300 rounded-lg text-sm font-medium text-gray-700 hover:bg-gray-50 flex items-center justify-center gap-2 transition-colors"
              >
                <Copy className="w-4 h-4" />
                {copied ? 'Tersalin!' : 'Salin Nomor VA'}
              </button>
              <div className="mt-4 bg-blue-50 rounded-lg p-3">
                <p className="text-xs font-medium text-blue-800 mb-2">Cara Bayar:</p>
                <ol className="text-xs text-blue-700 space-y-1 list-decimal list-inside">
                  <li>Buka aplikasi mobile banking atau ATM</li>
                  <li>Pilih menu Transfer &gt; Virtual Account</li>
                  <li>Masukkan nomor VA di atas</li>
                  <li>Konfirmasi jumlah {formatCurrency(data.amount)}</li>
                  <li>Selesaikan pembayaran</li>
                </ol>
              </div>
            </div>
          )}
        </div>

        {/* Polling indicator */}
        <div className="text-center">
          <div className="inline-flex items-center gap-2 text-xs text-gray-400">
            <Loader2 className="w-3 h-3 animate-spin" />
            Status otomatis diperbarui...
          </div>
        </div>
      </div>
    </div>
  )
}
