import React from 'react'
import { useParams, useSearchParams } from 'react-router-dom'
import { Button } from '../components/ui/button'
import { Alert } from '../components/alert/Alert'
import { usePaymentNavigation } from '../features/payments/lib/navigation'
import { usePaymentStatus } from '../features/payments/lib/usePaymentStatus'
import { Env } from '../lib/env'
import type { PaymentStatusResponse } from '../features/payments/lib/midtrans'
import { Logger } from '../lib/logger'

export function PaymentStatusPage() {
  const { orderId } = useParams()
  const nav = usePaymentNavigation()
  const [search] = useSearchParams()
  const method = search.get('m') ?? undefined
  const { data, isLoading, error } = usePaymentStatus(orderId)

  const statusText = data?.status ?? 'pending'
  const isFinal = ['settlement', 'capture', 'expire', 'cancel', 'deny', 'refund', 'chargeback'].includes(statusText)

  // Logs for debugging status lifecycle
  React.useEffect(() => {
    Logger.info('status.init', { orderId, method })
  }, [])

  React.useEffect(() => {
    if (!isLoading && !error && data) {
      Logger.info('status.update', { orderId: data.orderId, status: data.status })
    }
  }, [isLoading, error, data])

  function statusBadgeClass(s: PaymentStatusResponse['status']) {
    switch (s) {
      case 'pending':
        return 'inline-block rounded px-2 py-0.5 text-xs bg-yellow-100 text-yellow-800'
      case 'settlement':
      case 'capture':
        return 'inline-block rounded px-2 py-0.5 text-xs bg-green-100 text-green-800'
      case 'deny':
      case 'cancel':
      case 'expire':
      case 'refund':
      case 'chargeback':
        return 'inline-block rounded px-2 py-0.5 text-xs bg-red-100 text-red-800'
      default:
        return 'inline-block rounded px-2 py-0.5 text-xs bg-gray-100 text-gray-800'
    }
  }

  return (
    <div className="space-y-4">
      <h1 className="text-xl font-semibold">Status Pembayaran</h1>
      <div className="card p-4">
        <div className="text-sm">Order ID: {orderId}</div>
        {method || data?.method ? (
          <div className="text-xs text-gray-600">Metode: {data?.method ?? method}</div>
        ) : null}
        <div className="mt-2">Status: {isLoading ? (
          <span className="font-medium">memuat…</span>
        ) : error ? (
          <span className="font-medium text-brand-600">gagal memuat</span>
        ) : (
          <span className={statusBadgeClass(statusText)}>{statusText}</span>
        )}</div>
        <div className="mt-1 text-xs text-gray-600">
          {isFinal ? 'Status final — polling dihentikan.' : 'Polling setiap 3 detik hingga status final.'}
        </div>
        {/* Method-specific details */}
        {!isLoading && !error && data ? (
          <div className="mt-3 space-y-2 text-sm">
            {/* Bank Transfer / VA */}
            {data.vaNumber ? (
              <div className="rounded border border-gray-200 p-2">
                <div className="font-medium">Virtual Account</div>
                <div>VA Number: <span className="font-mono">{data.vaNumber}</span></div>
                {data.bank ? <div>Bank: {data.bank.toUpperCase()}</div> : null}
                {data.billKey && data.billerCode ? (
                  <div className="mt-1 text-xs text-gray-600">Mandiri E-Channel — Bill Key: {data.billKey}, Biller: {data.billerCode}</div>
                ) : null}
              </div>
            ) : null}
            {/* C-store */}
            {data.store || data.paymentCode ? (
              <div className="rounded border border-gray-200 p-2">
                <div className="font-medium">Convenience Store</div>
                {data.store ? <div>Store: {data.store}</div> : null}
                {data.paymentCode ? <div>Payment Code: <span className="font-mono">{data.paymentCode}</span></div> : null}
              </div>
            ) : null}
            {/* E-money (GoPay/QRIS) */}
            {data.actions && data.actions.length > 0 ? (
              <div className="rounded border border-gray-200 p-2">
                <div className="font-medium">QR / Deeplink</div>
                <div className="text-xs text-gray-600">Gunakan link berikut untuk membuka aplikasi pembayaran.</div>
                <div className="mt-1 flex flex-wrap gap-2">
                  {data.actions.map((a, i) => (
                    <a key={i} href={a.url} target="_blank" rel="noreferrer" className="underline text-brand-600">
                      {a.name || a.method || 'Buka'}
                    </a>
                  ))}
                </div>
              </div>
            ) : null}
            {/* Card */}
            {data.maskedCard ? (
              <div className="rounded border border-gray-200 p-2">
                <div className="font-medium">Kartu</div>
                <div>Masked Card: <span className="font-mono">{data.maskedCard}</span></div>
              </div>
            ) : null}
          </div>
        ) : null}
        <div className="mt-4 flex gap-2">
          <Button onClick={() => nav.toHistory()}>Lihat Riwayat</Button>
          <Button variant="secondary" onClick={() => nav.toCheckout()}>Kembali ke Checkout</Button>
        </div>
      </div>
      {!Env.API_BASE_URL && (
        <Alert title="API Base belum diatur">
          Tambahkan <code>VITE_API_BASE_URL</code> di env agar status memuat dari backend; saat ini menggunakan stub.
        </Alert>
      )}
    </div>
  )
}