import { useEffect, useMemo, useState } from 'react'
import { useParams } from 'react-router-dom'
import { PaymentSheet } from '../features/payments/components/PaymentSheet'
import { PaymentMethodList } from '../features/payments/components/PaymentMethodList'
import type { PaymentMethod } from '../features/payments/components/PaymentMethodList'
import { BankTransferPanel } from '../features/payments/components/BankTransferPanel'
import { CardPanel } from '../features/payments/components/CardPanel'
import { GoPayPanel } from '../features/payments/components/GoPayPanel'
import { CStorePanel } from '../features/payments/components/CStorePanel'
import { BankLogo, type BankKey, LogoAlfamart, LogoIndomaret } from '../features/payments/components/PaymentLogos'
import { usePaymentConfig } from '../features/payments/lib/usePaymentConfig'
import { Alert } from '../components/alert/Alert'
import { Button } from '../components/ui/button'
import { getPaymentLinkPayload } from '../services/api'
import { isOrderLocked, lockOrder } from '../features/payments/lib/chargeLock'
import { usePaymentNavigation } from '../features/payments/lib/navigation'

type Method = PaymentMethod | null

export function PayPage() {
  const { token } = useParams()
  const nav = usePaymentNavigation()
  const [orderId, setOrderId] = useState<string>('')
  const [amount, setAmount] = useState<number>(0)
  const [expireAt, setExpireAt] = useState<number>(Date.now() + 24 * 60 * 60 * 1000)
  const [selectedMethod, setSelectedMethod] = useState<Method>(null)
  const [locked, setLocked] = useState<boolean>(false)
  const [selectedBank, setSelectedBank] = useState<BankKey | null>(null)
  const [selectedStore, setSelectedStore] = useState<'alfamart' | 'indomaret' | null>(null)
  const [allowedMethods, setAllowedMethods] = useState<string[] | undefined>(undefined)
  const [error, setError] = useState<{ code?: string; message?: string } | null>(null)
  const { data: runtimeCfg } = usePaymentConfig()
  const [currentStep, setCurrentStep] = useState<2 | 3>(2)
  const [isBusy, setIsBusy] = useState(false)

  useEffect(() => {
    let cancelled = false
    async function resolve() {
      if (!token) return
      try {
        const payload = await getPaymentLinkPayload(token)
        if (cancelled) return
        setOrderId(payload.order_id)
        setAmount(payload.nominal)
        setExpireAt(payload.expire_at ?? Date.now() + 24 * 60 * 60 * 1000)
        setAllowedMethods(payload.allowed_methods)
        setError(null)
        if (isOrderLocked(payload.order_id)) setLocked(true)
      } catch {
        if (cancelled) return
        setError({ code: 'TOKEN_RESOLVE_ERROR' })
      }
    }
    resolve()
    return () => {
      cancelled = true
    }
  }, [token])

  const merchantName = useMemo(() => '', [])

  const isExpired = expireAt ? Date.now() > expireAt : false
  const enabledMap: Record<PaymentMethod, boolean> = useMemo(() => {
    const base = runtimeCfg?.paymentToggles
    const allow = allowedMethods
    const all: Record<PaymentMethod, boolean> = {
      bank_transfer: base?.bank_transfer ?? true,
      credit_card: base?.credit_card ?? true,
      gopay: base?.gopay ?? true,
      cstore: base?.cstore ?? true,
      cpay: base?.cpay ?? false,
    }
    if (allow && Array.isArray(allow)) {
      for (const k of (Object.keys(all) as PaymentMethod[])) {
        if (k === 'cpay') continue
        all[k] = allow.includes(k) && all[k]
      }
    }
    return all
  }, [runtimeCfg, allowedMethods])

  if (error || isExpired) {
    const title = isExpired ? 'Link pembayaran telah kedaluwarsa' : 'Link pembayaran tidak valid'
    const msg = isExpired ? 'Silakan minta link baru dari admin atau ERP.' : 'Token tidak dapat diverifikasi. Hubungi admin untuk bantuan.'
    return (
      <PaymentSheet
        merchantName={merchantName}
        orderId={orderId || (token ?? '')}
        amount={amount}
        expireAt={expireAt}
        showStatusCTA={false}
      >
        <div className="space-y-4 px-4 py-6">
          <Alert title={title}>{msg}</Alert>
          <div className="flex flex-col gap-2 sm:flex-row">
            <Button
              variant="secondary"
              onClick={() => { try { window.location.reload() } catch { void 0 } }}
              className="w-full sm:w-auto"
            >
              Muat ulang
            </Button>
            <a
              href="mailto:retailimaya@gmail.com?subject=Permintaan%20Link%20Pembayaran&body=Order%20ID:%20"
              className="inline-flex items-center px-3 py-2 rounded border bg-gray-800 !text-white hover:!text-white focus:!text-white visited:!text-white active:!text-white w-full sm:w-auto justify-center"
            >
              Hubungi Admin
            </a>
          </div>
        </div>
      </PaymentSheet>
    )
  }

  return (
    <PaymentSheet
      merchantName={merchantName}
      orderId={orderId}
      amount={amount}
      expireAt={expireAt}
      showStatusCTA={currentStep === 3}
    >
      <div className="space-y-4 px-4 py-6">
        {locked && currentStep === 2 && (
          <Alert title="Pembayaran sudah dibuat">
            Kode/QR telah digenerate untuk order ini. Buka halaman status untuk melanjutkan.
            <div className="mt-2">
              <Button variant="primary" onClick={() => nav.toStatus(orderId)}>
                Buka status
              </Button>
            </div>
          </Alert>
        )}
        {currentStep === 2 && (
          <div className="space-y-3">
            <PaymentMethodList
              selected={selectedMethod ?? undefined}
              onSelect={(m) => {
                setSelectedMethod(m as Method)
                if (m === 'bank_transfer' || m === 'cstore') {
                  void 0
                } else if (m === 'cpay') {
                  try {
                    window.open('https://play.google.com/store/apps/details?id=com.cifo.walanja', '_blank')
                  } catch { void 0 }
                } else {
                  setIsBusy(true)
                  setTimeout(() => { setCurrentStep(3); setIsBusy(false) }, 300)
                }
              }}
              disabled={locked}
              enabled={enabledMap}
              renderPanel={(m) => {
                const enabled = enabledMap[m]
                if (!enabled) {
                  return (
                    <div className="p-2">
                      <Alert title="Metode nonaktif">Metode pembayaran ini dinonaktifkan di konfigurasi lingkungan.</Alert>
                    </div>
                  )
                }
                if (m === 'bank_transfer') {
                  return (
                    <div className="space-y-2" aria-live="polite">
                      <div className="text-xs text-gray-600">Pilih bank untuk membuat Virtual Account</div>
                      <div className={`grid grid-cols-2 md:grid-cols-3 gap-2 ${isBusy ? 'pointer-events-none opacity-60' : ''}`}>
                        {(['bca', 'bni', 'bri', 'cimb', 'mandiri', 'permata'] as BankKey[]).map((bk) => (
                          <button
                            key={bk}
                            type="button"
                            onClick={() => {
                              setSelectedBank(bk)
                              setIsBusy(true)
                              setTimeout(() => { setCurrentStep(3); setIsBusy(false) }, 300)
                            }}
                            className="rounded border border-gray-300 bg-white p-3 md:p-2 w-full flex items-center justify-center overflow-hidden hover:bg-gray-100"
                            aria-label={`Pilih bank ${bk.toUpperCase()}`}
                          >
                            <BankLogo bank={bk} />
                          </button>
                        ))}
                      </div>
                      {isBusy && (
                        <div className="text-xs text-gray-600 inline-flex items-center gap-2">
                          <span className="h-3 w-3 animate-spin rounded-full border-2 border-gray-400 border-t-transparent" aria-hidden />
                          Menyiapkan VA…
                        </div>
                      )}
                    </div>
                  )
                }
                if (m === 'cstore') {
                  return (
                    <div className="space-y-2" aria-live="polite">
                      <div className="text-xs text-gray-600">Pilih toko untuk membuat kode pembayaran</div>
                      <div className={`grid grid-cols-2 gap-2 ${isBusy ? 'pointer-events-none opacity-60' : ''}`}>
                        {/* {(['alfamart', 'indomaret'] as const).map((st) => ( */}
                          {(['alfamart'] as const).map((st) => (
                          <button
                            key={st}
                            type="button"
                            onClick={() => {
                              setSelectedStore(st)
                              setIsBusy(true)
                              setTimeout(() => { setCurrentStep(3); setIsBusy(false) }, 300)
                            }}
                            className="rounded border border-gray-300 bg-white p-3 md:p-2 w-full flex items-center justify-center hover:bg-gray-100"
                            aria-label={`Pilih toko ${st.toUpperCase()}`}
                          >
                            {st === 'alfamart' ? <LogoAlfamart /> : <LogoIndomaret />}
                          </button>
                        ))}
                      </div>
                    </div>
                  )
                }
                return null
              }}
            />
          </div>
        )}

        {currentStep === 3 && (
          <div className="space-y-3" aria-live="polite">
            {selectedMethod === 'bank_transfer' && (
              <BankTransferPanel
                locked={locked}
                onChargeInitiated={() => { lockOrder(orderId); setLocked(true) }}
                orderId={orderId}
                amount={amount}
                defaultBank={(selectedBank ?? 'bca')}
              />
            )}
            {selectedMethod === 'credit_card' && (
              <CardPanel
                locked={locked}
                onChargeInitiated={() => { lockOrder(orderId); setLocked(true) }}
                orderId={orderId}
                amount={amount}
              />
            )}
            {selectedMethod === 'gopay' && (
              <GoPayPanel
                locked={locked}
                onChargeInitiated={() => { lockOrder(orderId); setLocked(true) }}
                orderId={orderId}
                amount={amount}
              />
            )}
            {selectedMethod === 'cstore' && (
              <CStorePanel
                locked={locked}
                onChargeInitiated={() => { lockOrder(orderId); setLocked(true) }}
                orderId={orderId}
                amount={amount}
                defaultStore={selectedStore ?? undefined}
              />
            )}
          </div>
        )}
      </div>
    </PaymentSheet>
  )
}
