import React from 'react'
import { useParams, useSearchParams } from 'react-router-dom'
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'
import { CountdownRedirect } from '../components/CountdownRedirect'

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

  const statusText = data?.status ?? 'pending'
  const isFinal = ['settlement', 'capture', 'expire', 'cancel', 'deny', 'refund', 'chargeback'].includes(statusText)
  const isSuccess = statusText === 'settlement' || statusText === 'capture'
  function sanitizeUrl(u?: string) {
    return (u || '').replace(/[`\s]+$/g, '').replace(/^\s+|\s+$/g, '').replace(/`/g, '')
  }
  function pickQrFromCache(id?: string) {
    try {
      const raw = localStorage.getItem('qrisCache')
      if (!raw) return ''
      const map = JSON.parse(raw) as Record<string, { url?: string }>
      return sanitizeUrl(map[id || '']?.url)
    } catch { return '' }
  }
  function qrFromData(d?: PaymentStatusResponse) {
    if (!d) return ''
    const img = sanitizeUrl(d.imageUrl)
    if (img) return img
    const s = d.qrString
    if (typeof s === 'string' && s.length > 0) {
      return `https://api.qrserver.com/v1/create-qr-code/?size=220x220&data=${encodeURIComponent(s)}`
    }
    return ''
  }
  function collectQrActionUrls(acts: Array<{ name?: string; method?: string; url: string }> | undefined) {
    const list = Array.isArray(acts) ? acts : []
    const urls = list
      .filter((a) => /qr/i.test(a.name ?? '') || /qr-code/i.test(a.name ?? ''))
      .map((a) => sanitizeUrl(a.url))
      .filter((u) => !!u)
    urls.sort((x, y) => {
      const xv4 = x.includes('/v4/') ? 1 : 0
      const yv4 = y.includes('/v4/') ? 1 : 0
      return yv4 - xv4
    })
    return urls
  }
  const qrCandidates = [qrFromData(data), ...collectQrActionUrls(data?.actions), pickQrFromCache(orderId || undefined)].filter((u) => !!u)
  const [qrSrc, setQrSrc] = React.useState<string>('')
  React.useEffect(() => { setQrSrc(qrCandidates[0] || '') }, [statusText, method, orderId, data, qrCandidates])

  function handleRedirect() {
    nav.toHistory()
  }

  // 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>
        {isSuccess ? (
          <div className="mt-4">
            <div className="text-lg font-semibold">✅ Pembayaran Berhasil!</div>
            <CountdownRedirect seconds={5} destination="dashboard" onComplete={handleRedirect} />
          </div>
        ) : null}
        {/* Method-specific details */}
        {!isLoading && !error && data ? (
          <div className="mt-3 space-y-2 text-sm">
            {(!method || method === 'bank_transfer') && 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}
            {(!method || method === 'cstore') && (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}
            {(!method || method === 'gopay' || method === 'qris') && (qrSrc || (Array.isArray(data?.actions) && data.actions.length > 0)) ? (
              <div className="rounded border border-gray-200 p-2">
                <div className="font-medium">QR / Deeplink</div>
                {qrSrc ? (
                  <div className="mt-2 grid place-items-center">
                    <img src={qrSrc} alt="QR untuk pembayaran" className="aspect-square w-full max-w-[260px] mx-auto rounded border border-black/10" onError={(e) => {
                      const next = qrCandidates.find((u) => u !== e.currentTarget.src)
                      if (next) setQrSrc(next)
                    }} />
                  </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">
                  {(Array.isArray(data?.actions) ? 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}
            {(!method || method === 'credit_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}
        {/* Aksi bawah dihilangkan sesuai permintaan */}
      </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>
  )
}