import React from 'react'
import { Alert } from '../components/alert/Alert'
import { Button } from '../components/ui/button'
import { Env } from '../lib/env'
import { Logger } from '../lib/logger'
import { loadSnapScript } from '../lib/snapLoader'
import { PaymentSheet } from '../features/payments/components/PaymentSheet'
import { usePaymentConfig } from '../features/payments/lib/usePaymentConfig'
import type { PaymentMethod } from '../features/payments/components/PaymentMethodList'
import { SnapTokenService } from '../features/payments/snap/SnapTokenService'
interface AutoSnapPaymentProps {
  orderId: string
  amount: number
  customer?: { name?: string; phone?: string; email?: string }
  onChargeInitiated?: () => void
  onSuccess?: (result: any) => void
  onError?: (error: any) => void
  onModalClosed?: () => void
}

function AutoSnapPayment({ orderId, amount, customer, onSuccess, onError, onModalClosed }: Omit<AutoSnapPaymentProps, 'onChargeInitiated'>) {
  const [loading, setLoading] = React.useState(false)
  const [error, setError] = React.useState('')
  const [paymentTriggered, setPaymentTriggered] = React.useState(false)

  // Debug log immediately on component mount
  console.log('AutoSnapPayment mounted with:', { orderId, amount, customer })
  Logger.info('autosnapPayment.mount', { orderId, amount, hasCustomer: !!customer })

  React.useEffect(() => {
    console.log('AutoSnapPayment useEffect triggered', { orderId, amount, paymentTriggered })
    // Only trigger when we have valid orderId and amount and not already triggered
    if (!orderId || !amount || paymentTriggered) {
      console.log('AutoSnapPayment useEffect early return', { hasOrderId: !!orderId, hasAmount: !!amount, alreadyTriggered: paymentTriggered })
      return
    }

    const triggerPayment = async () => {
      console.log('triggerPayment function called!')
      setPaymentTriggered(true) // Mark as triggered immediately
      try {
        setLoading(true)
        setError('')

        Logger.paymentInfo('checkout.auto.snap.init', { orderId, amount, customer })

        // Load Snap.js first
        Logger.paymentInfo('checkout.auto.snap.loading_script', { orderId })
        await loadSnapScript()
        Logger.paymentInfo('checkout.auto.snap.script_loaded', { orderId, hasSnap: !!window.snap })

        // Create Snap transaction token
        Logger.paymentInfo('checkout.auto.snap.calling_api', { orderId, amount })
        const token = await SnapTokenService.createToken({
          transaction_details: {
            order_id: orderId,
            gross_amount: amount
          },
          customer_details: customer ? {
            first_name: customer.name,
            email: customer.email,
            phone: customer.phone
          } : undefined,
          item_details: [{
            id: orderId,
            name: 'Payment',
            price: amount,
            quantity: 1
          }]
        })

        Logger.paymentInfo('checkout.auto.snap.token.received', { orderId, token: token.substring(0, 10) + '...' })
        console.log('Token berhasil dibuat:', token)

        // Verify Snap.js is loaded
        console.log('window.snap:', window.snap)
        console.log('window.snap.pay:', window.snap?.pay)
        console.log('typeof window.snap?.pay:', typeof window.snap?.pay)
        
        if (!window.snap || typeof window.snap.pay !== 'function') {
          const errorMsg = `Snap.js not properly loaded: hasSnap=${!!window.snap}, hasPay=${typeof window.snap?.pay}`
          console.error(errorMsg)
          throw new Error(errorMsg)
        }

        // Auto-trigger Snap payment popup
        console.log('Memanggil window.snap.pay dengan token:', token.substring(0, 20) + '...')
        console.log('Full token:', token)
        setLoading(false) // Stop loading indicator before showing modal
        
        window.snap.pay(token, {
          onSuccess: (result: any) => {
            Logger.paymentInfo('checkout.auto.snap.payment.success', { orderId, transactionId: result.transaction_id })
            onSuccess?.(result)
          },
          onPending: (result: any) => {
            Logger.paymentInfo('checkout.auto.snap.payment.pending', { orderId, transactionId: result.transaction_id })
          },
          onError: (result: any) => {
            Logger.paymentError('checkout.auto.snap.payment.error', { orderId, error: result })
            const message = 'Pembayaran gagal. Silakan coba lagi.'
            setError(message)
            setLoading(false)
            onError?.(result)
          },
          onClose: () => {
            Logger.paymentInfo('checkout.auto.snap.popup.closed', { orderId })
            setLoading(false)
            onModalClosed?.() // Enable status button when modal closed
          }
        })

      } catch (e: any) {
        Logger.paymentError('checkout.auto.snap.payment.error', { orderId, error: e.message, stack: e.stack })
        console.error('Error membuat token Snap:', e)
        
        // Handle specific error: order_id already taken
        const errorMessage = e.response?.data?.message || e.message || ''
        const isOrderTaken = errorMessage.includes('already been taken') || 
                            errorMessage.includes('order_id has already been taken')
        
        if (isOrderTaken) {
          const message = 'Order ID sudah digunakan. Pembayaran untuk order ini sudah dibuat. Silakan cek halaman status pembayaran.'
          setError(message)
        } else {
          const message = e.response?.data?.message || e.message || 'Gagal memuat pembayaran. Silakan refresh halaman.'
          setError(message)
        }
        
        onError?.(e)
        setLoading(false)
      }
    }

    // Small delay to ensure UI is rendered
    console.log('Setting timeout to call triggerPayment in 500ms...')
    const timer = setTimeout(triggerPayment, 500)
    return () => {
      console.log('Cleanup: clearing timeout')
      clearTimeout(timer)
    }
  }, [orderId, amount, customer, paymentTriggered, onSuccess, onError, onModalClosed])

  // Don't render anything until we have valid data
  if (!orderId || !amount) {
    return (
      <div className="text-center">
        <div className="space-y-2">
          <div className="h-8 w-8 animate-spin rounded-full border-4 border-blue-600 border-t-transparent mx-auto"></div>
          <p className="text-sm text-gray-600">Memuat data pembayaran...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-4">
      {error && (
        <Alert title="Pembayaran Gagal">
          <div className="space-y-2">
            <p>{error}</p>
            <details className="text-xs">
              <summary className="cursor-pointer">Detail Error</summary>
              <pre className="mt-2 bg-gray-100 p-2 rounded overflow-auto">{JSON.stringify({ orderId, amount, customer }, null, 2)}</pre>
            </details>
          </div>
        </Alert>
      )}

      <div className="text-center">
        {loading ? (
          <div className="space-y-2">
            <div className="h-8 w-8 animate-spin rounded-full border-4 border-blue-600 border-t-transparent mx-auto"></div>
            <p className="text-sm text-gray-600">Menyiapkan pembayaran...</p>
          </div>
        ) : error ? (
          <div className="space-y-2">
            <p className="text-sm text-red-600">Gagal memuat pembayaran</p>
            <button 
              onClick={() => window.location.reload()} 
              className="text-sm text-blue-600 underline"
            >
              Coba lagi
            </button>
          </div>
        ) : null}
      </div>
    </div>
  )
}

export function CheckoutPage() {
  const apiBase = Env.API_BASE_URL
  const clientKey = Env.MIDTRANS_CLIENT_KEY
  const { data: runtimeCfg } = usePaymentConfig()
  // Generate unique order id per checkout session to avoid Midtrans 406 conflicts
  const orderIdRef = React.useRef<string>('')
  if (!orderIdRef.current) {
    const ts = Date.now()
    const rand = Math.floor(Math.random() * 100000).toString().padStart(5, '0')
    orderIdRef.current = `order-${ts}-${rand}`
  }
  const orderId = orderIdRef.current
  const amount = 3500000
  const expireAt = Date.now() + 59 * 60 * 1000 + 32 * 1000 // 00:59:32
  const [selected, setSelected] = React.useState<PaymentMethod | null>(null)
  const [currentStep, setCurrentStep] = React.useState<1 | 2>(1)
  const [isBusy, setIsBusy] = React.useState(false)
  const [modalClosed, setModalClosed] = React.useState(false)
  const [form, setForm] = React.useState<{ name: string; contact: string; address: string; notes: string }>({
    name: 'Demo User',
    contact: 'demo@example.com',
    address: 'Jl. Contoh No. 1',
    notes: '',
  })

  const configMissing = !clientKey || !apiBase

  React.useEffect(() => {
    Logger.info('checkout.init', { apiBase, hasClientKey: !!clientKey })
  }, [])

  React.useEffect(() => {
    if (runtimeCfg) {
      Logger.info('runtime.config.applied', runtimeCfg.paymentToggles)
    }
  }, [runtimeCfg])

  React.useEffect(() => {
    if (selected) Logger.info('checkout.method.selected', { method: selected })
  }, [selected])

  const prevStep = React.useRef(currentStep)
  React.useEffect(() => {
    if (prevStep.current !== currentStep) {
      Logger.info('checkout.step', { from: prevStep.current, to: currentStep })
      prevStep.current = currentStep
    }
  }, [currentStep])

  return (
    <div className="space-y-6">
      {configMissing && (
        <Alert title="Konfigurasi belum lengkap">
          Set <code>VITE_MIDTRANS_CLIENT_KEY</code> untuk tokenisasi kartu dan <code>VITE_API_BASE_URL</code> ke server backend (contoh: <code>http://localhost:8000</code>). Tanpa API base, pembayaran tidak dapat diproses.
        </Alert>
      )}

      <PaymentSheet merchantName="Simaya" orderId={orderId} amount={amount} expireAt={expireAt} customerName={form.name} showStatusCTA={modalClosed}>
        {/* Wizard 2 langkah: Step 1 (Form Dummy) → Step 2 (Payment - Snap/Core auto-detect) */}
        {currentStep === 1 && (
          <div className="space-y-3">
            <div className="text-sm font-medium">Konfirmasi data checkout</div>
            <label className="block">
              <div className="text-xs text-gray-600">Nama</div>
              <input
                type="text"
                className="w-full rounded border px-3 py-2"
                value={form.name}
                onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
              />
            </label>
            <label className="block">
              <div className="text-xs text-gray-600">Email atau HP</div>
              <input
                type="text"
                className="w-full rounded border px-3 py-2"
                value={form.contact}
                onChange={(e) => setForm((f) => ({ ...f, contact: e.target.value }))}
              />
            </label>
            <label className="block">
              <div className="text-xs text-gray-600">Alamat</div>
              <input
                type="text"
                className="w-full rounded border px-3 py-2"
                value={form.address}
                onChange={(e) => setForm((f) => ({ ...f, address: e.target.value }))}
              />
            </label>
            <label className="block">
              <div className="text-xs text-gray-600">Catatan</div>
              <textarea
                className="w-full rounded border px-3 py-2"
                value={form.notes}
                onChange={(e) => setForm((f) => ({ ...f, notes: e.target.value }))}
              />
            </label>
            <div className="pt-2 flex gap-2">
              <Button
                variant="primary"
                className="w-full"
                aria-busy={isBusy}
                disabled={isBusy}
                onClick={() => {
                  setIsBusy(true)
                  // Set default payment method (bank_transfer for demo)
                  setSelected('bank_transfer')
                  setTimeout(() => { setCurrentStep(2); setIsBusy(false) }, 400)
                }}
              >
                {isBusy ? (
                  <span className="inline-flex items-center gap-2">
                    <span className="h-4 w-4 animate-spin rounded-full border-2 border-white/70 border-t-transparent" aria-hidden />
                    Memuat…
                  </span>
                ) : 'Lanjut ke Pembayaran'}
              </Button>
            </div>
          </div>
        )}

        {currentStep === 2 && (
          <div className="space-y-3" aria-live="polite">
            {(() => {
              console.log('Rendering step 2 - AutoSnapPayment', { orderId, amount, currentStep })
              Logger.info('checkout.step2.render', { orderId, amount })
              return null
            })()}
            <AutoSnapPayment
              orderId={orderId}
              amount={amount}
              customer={{
                name: form.name,
                email: form.contact.includes('@') ? form.contact : undefined,
                phone: !form.contact.includes('@') ? form.contact : undefined
              }}
              onSuccess={(result) => {
                Logger.info('checkout.payment.success', { orderId, result })
                // Handle successful payment
              }}
              onError={(error) => {
                Logger.error('checkout.payment.error', { orderId, error })
                setModalClosed(true) // Enable status button on error
                // Handle payment error
              }}
              onModalClosed={() => {
                setModalClosed(true) // Enable status button when modal closed
              }}
            />
          </div>
        )}
      </PaymentSheet>

      <div className="text-xs text-gray-600">
        API Base: {apiBase ?? '—'} | Client Key: {clientKey ? 'OK' : '—'}
      </div>
    </div>
  )
}