'use client'

import { useState, useEffect, useCallback } from 'react'
import { useSession } from 'next-auth/react'
import { useRouter } from 'next/navigation'
import Navbar from '@/components/Navbar'
import { formatDate } from '@/lib/utils'

export default function OtpOrderPage({ params }: { params: { orderId: string } }) {
  const { data: session } = useSession()
  const router = useRouter()
  const [order, setOrder] = useState<any>(null)
  const [loading, setLoading] = useState(true)
  const [actionLoading, setActionLoading] = useState(false)
  const [copied, setCopied] = useState(false)

  const fetchOrder = useCallback(async () => {
    try {
      const res = await fetch(`/api/otp/orders/${params.orderId}`)
      const data = await res.json()
      if (data.order) setOrder(data.order)
    } catch {}
    setLoading(false)
  }, [params.orderId])

  useEffect(() => {
    fetchOrder()
    // Poll every 5 seconds if pending
    const interval = setInterval(() => {
      if (order?.status === 'pending') fetchOrder()
    }, 5000)
    return () => clearInterval(interval)
  }, [fetchOrder, order?.status])

  const handleAction = async (action: 'cancel' | 'done' | 'resend') => {
    setActionLoading(true)
    try {
      const res = await fetch(`/api/otp/orders/${params.orderId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action }),
      })
      const data = await res.json()
      if (data.order) setOrder(data.order)
      if (action === 'cancel') router.push('/dashboard/orders')
    } catch {}
    setActionLoading(false)
  }

  const copyCode = () => {
    if (order?.otpCode) {
      navigator.clipboard.writeText(order.otpCode)
      setCopied(true)
      setTimeout(() => setCopied(false), 2000)
    }
  }

  if (loading) return (
    <main style={{ minHeight: '100vh', background: '#0a0a0f', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <div className="spinner" style={{ width: 40, height: 40 }} />
    </main>
  )

  if (!order) return (
    <main style={{ minHeight: '100vh', background: '#0a0a0f', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <div style={{ textAlign: 'center', color: '#64748b' }}>
        <div style={{ fontSize: '48px', marginBottom: '16px' }}>😕</div>
        <p>Pesanan tidak ditemukan</p>
      </div>
    </main>
  )

  const statusConfig: Record<string, { label: string; color: string; bg: string; icon: string }> = {
    pending: { label: 'Menunggu OTP', color: '#f59e0b', bg: 'rgba(245,158,11,0.1)', icon: '⏳' },
    received: { label: 'OTP Diterima!', color: '#10b981', bg: 'rgba(16,185,129,0.1)', icon: '✅' },
    done: { label: 'Selesai', color: '#3b82f6', bg: 'rgba(59,130,246,0.1)', icon: '🏁' },
    cancel: { label: 'Dibatalkan', color: '#ef4444', bg: 'rgba(239,68,68,0.1)', icon: '❌' },
  }
  const sc = statusConfig[order.status] || statusConfig.pending

  return (
    <main style={{ minHeight: '100vh', background: '#0a0a0f', display: 'flex', flexDirection: 'column' }}>
      <Navbar />
      <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '100px 24px 60px' }}>
        <div style={{ width: '100%', maxWidth: '520px' }}>
          {/* Status Card */}
          <div className="card" style={{ padding: '32px', textAlign: 'center', marginBottom: '20px' }}>
            <div style={{ fontSize: '64px', marginBottom: '16px' }}>{sc.icon}</div>
            <div style={{ fontSize: '22px', fontWeight: 700, color: sc.color, marginBottom: '8px' }}>{sc.label}</div>
            
            <div style={{ fontSize: '13px', color: '#64748b', marginBottom: '24px' }}>
              {order.serviceName} • {order.countryName}
            </div>

            {/* Phone Number */}
            {order.phoneNumber && (
              <div style={{ padding: '16px', background: 'rgba(255,255,255,0.04)', borderRadius: '12px', marginBottom: '20px' }}>
                <div style={{ fontSize: '12px', color: '#64748b', marginBottom: '6px' }}>Nomor Telepon</div>
                <div style={{ fontSize: '22px', fontWeight: 700, color: '#f1f5f9', letterSpacing: '1px' }}>{order.phoneNumber}</div>
              </div>
            )}

            {/* OTP Code */}
            {order.otpCode && (
              <div style={{ padding: '20px', background: 'rgba(16,185,129,0.08)', border: '2px solid rgba(16,185,129,0.3)', borderRadius: '16px', marginBottom: '20px' }}>
                <div style={{ fontSize: '12px', color: '#10b981', marginBottom: '8px', fontWeight: 600 }}>🔐 KODE OTP</div>
                <div style={{ fontSize: '40px', fontWeight: 900, color: '#10b981', letterSpacing: '6px', fontFamily: 'monospace' }}>{order.otpCode}</div>
                {order.smsText && (
                  <div style={{ fontSize: '12px', color: '#64748b', marginTop: '10px', lineHeight: 1.5 }}>{order.smsText}</div>
                )}
                <button onClick={copyCode} className="btn btn-secondary" style={{ marginTop: '12px', fontSize: '13px' }}>
                  {copied ? '✅ Disalin!' : '📋 Salin Kode'}
                </button>
              </div>
            )}

            {/* Pending animation */}
            {order.status === 'pending' && (
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '10px', color: '#f59e0b', fontSize: '14px', marginBottom: '20px' }}>
                <span className="spinner" />
                Menunggu OTP... (auto refresh tiap 5 detik)
              </div>
            )}
          </div>

          {/* Actions */}
          {!['done', 'cancel'].includes(order.status) && (
            <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
              {order.status === 'received' && (
                <button onClick={() => handleAction('done')} disabled={actionLoading} className="btn btn-primary" style={{ flex: 1 }}>
                  ✅ Konfirmasi Selesai
                </button>
              )}
              {order.status === 'pending' && (
                <button onClick={() => handleAction('resend')} disabled={actionLoading} className="btn btn-secondary" style={{ flex: 1 }}>
                  🔄 Minta Ulang OTP
                </button>
              )}
              <button onClick={() => handleAction('cancel')} disabled={actionLoading} className="btn btn-danger" style={{ flex: 1 }}>
                ❌ Batalkan & Refund
              </button>
            </div>
          )}

          {/* Order Info */}
          <div className="card" style={{ padding: '16px', marginTop: '16px' }}>
            <div style={{ fontSize: '12px', color: '#64748b', marginBottom: '8px', fontWeight: 600 }}>INFO PESANAN</div>
            {[
              { label: 'ID Pesanan', value: `#${order.id.slice(-8).toUpperCase()}` },
              { label: 'RumahOTP ID', value: order.rumahOtpId || '-' },
              { label: 'Harga', value: `Rp ${Number(order.price).toLocaleString('id-ID')}` },
              { label: 'Waktu Pesan', value: formatDate(order.createdAt) },
            ].map(row => (
              <div key={row.label} style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', borderBottom: '1px solid rgba(255,255,255,0.04)', fontSize: '13px' }}>
                <span style={{ color: '#64748b' }}>{row.label}</span>
                <span style={{ color: '#e2e8f0', fontFamily: row.label.includes('ID') ? 'monospace' : undefined }}>{row.value}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </main>
  )
}
