'use client'

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

// ── Star Rating Component ─────────────────────────────
function StarRating({ value, onChange }: { value: number; onChange?: (n: number) => void }) {
  const [hover, setHover] = useState(0)
  return (
    <div style={{ display: 'flex', gap: '4px' }}>
      {[1, 2, 3, 4, 5].map(star => (
        <span
          key={star}
          style={{
            fontSize: '22px', cursor: onChange ? 'pointer' : 'default',
            color: star <= (hover || value) ? '#f59e0b' : '#374151',
            transition: 'color 0.15s'
          }}
          onMouseEnter={() => onChange && setHover(star)}
          onMouseLeave={() => onChange && setHover(0)}
          onClick={() => onChange?.(star)}
        >★</span>
      ))}
    </div>
  )
}

// ── Review Modal ──────────────────────────────────────
function ReviewModal({ order, onClose, onSubmitted }: { order: any; onClose: () => void; onSubmitted: () => void }) {
  const [rating, setRating] = useState(5)
  const [comment, setComment] = useState('')
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')

  const productName = order.productType === 'VIP'
    ? `${order.vipProduct?.gameName} - ${order.vipProduct?.productName}`
    : order.digitalProduct?.name || 'Produk'

  const handleSubmit = async () => {
    setLoading(true)
    setError('')
    try {
      const res = await fetch('/api/reviews', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ orderId: order.id, rating, comment })
      })
      const data = await res.json()
      if (!res.ok) throw new Error(data.error)
      onSubmitted()
    } catch (e: any) {
      setError(e.message)
    } finally {
      setLoading(false)
    }
  }

  return (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.7)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '16px' }}>
      <div className="card" style={{ width: '100%', maxWidth: '460px', padding: '28px', position: 'relative' }}>
        <button onClick={onClose} style={{ position: 'absolute', top: '16px', right: '16px', background: 'none', border: 'none', color: '#64748b', fontSize: '20px', cursor: 'pointer' }}>✕</button>
        <h3 style={{ color: '#f1f5f9', fontWeight: 700, marginBottom: '4px', fontSize: '18px' }}>⭐ Beri Ulasan</h3>
        <p style={{ color: '#64748b', fontSize: '13px', marginBottom: '20px' }}>{productName}</p>

        <div style={{ marginBottom: '16px' }}>
          <label className="label">Rating</label>
          <StarRating value={rating} onChange={setRating} />
        </div>

        <div style={{ marginBottom: '20px' }}>
          <label className="label">Komentar (opsional)</label>
          <textarea
            className="input"
            rows={3}
            placeholder="Bagaimana pengalaman kamu?"
            value={comment}
            onChange={e => setComment(e.target.value)}
          />
        </div>

        {error && <div style={{ color: '#ef4444', fontSize: '13px', marginBottom: '12px' }}>{error}</div>}

        <button className="btn btn-primary" onClick={handleSubmit} disabled={loading} style={{ width: '100%' }}>
          {loading ? 'Mengirim...' : 'Kirim Ulasan'}
        </button>
      </div>
    </div>
  )
}

// ── Main Page ─────────────────────────────────────────
export default function UserOrders() {
  const { data: session } = useSession()
  const [orders, setOrders] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [page, setPage] = useState(1)
  const [totalPages, setTotalPages] = useState(1)
  const [statusFilter, setStatusFilter] = useState('')
  const [activeTab, setActiveTab] = useState<'regular' | 'otp'>('regular')
  const [otpOrders, setOtpOrders] = useState<any[]>([])
  const [reviewOrder, setReviewOrder] = useState<any>(null)
  const [reviewedIds, setReviewedIds] = useState<Set<string>>(new Set())

  const fetchOrders = () => {
    setLoading(true)
    if (activeTab === 'regular') {
      fetch(`/api/orders?page=${page}&limit=10${statusFilter ? `&status=${statusFilter}` : ''}`)
        .then(r => r.json())
        .then(d => {
          setOrders(d.orders || [])
          setTotalPages(d.pages || 1)
          setLoading(false)
        })
        .catch(() => setLoading(false))
    } else {
      fetch(`/api/otp/orders?page=${page}&limit=10`)
        .then(r => r.json())
        .then(d => {
          setOtpOrders(d.orders || [])
          setTotalPages(d.pages || 1)
          setLoading(false)
        })
        .catch(() => setLoading(false))
    }
  }

  useEffect(() => { fetchOrders() }, [page, statusFilter, activeTab])

  return (
    <main style={{ minHeight: '100vh', background: '#0a0a0f', display: 'flex', flexDirection: 'column' }}>
      <Navbar />

      {reviewOrder && (
        <ReviewModal
          order={reviewOrder}
          onClose={() => setReviewOrder(null)}
          onSubmitted={() => {
            setReviewedIds(prev => new Set([...prev, reviewOrder.id]))
            setReviewOrder(null)
          }}
        />
      )}

      <div style={{ paddingTop: '80px', maxWidth: '1000px', margin: '0 auto', padding: '80px 24px 60px', width: '100%' }}>
        {/* Tabs */}
        <div style={{ display: 'flex', gap: '8px', marginBottom: '24px' }}>
          <button
            onClick={() => { setActiveTab('regular'); setPage(1) }}
            style={{ padding: '8px 16px', borderRadius: '8px', background: activeTab === 'regular' ? '#f59e0b' : 'rgba(255,255,255,0.05)', color: activeTab === 'regular' ? '#000' : '#94a3b8', fontWeight: 600, border: 'none', cursor: 'pointer' }}
          >🎮 Topup &amp; App Premium</button>
          <button
            onClick={() => { setActiveTab('otp'); setPage(1) }}
            style={{ padding: '8px 16px', borderRadius: '8px', background: activeTab === 'otp' ? '#f59e0b' : 'rgba(255,255,255,0.05)', color: activeTab === 'otp' ? '#000' : '#94a3b8', fontWeight: 600, border: 'none', cursor: 'pointer' }}
          >📱 Nomor OTP Virtual</button>
        </div>

        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px', flexWrap: 'wrap', gap: '16px' }}>
          <div>
            <h1 className="font-game" style={{ fontSize: '28px', fontWeight: 700, color: '#f1f5f9', marginBottom: '4px' }}>
              {activeTab === 'regular' ? '📦 Riwayat Pesanan' : '📱 Riwayat OTP'}
            </h1>
            <p style={{ color: '#64748b', fontSize: '14px' }}>Pantau status semua transaksi kamu</p>
          </div>
          {activeTab === 'regular' && (
            <select className="input" style={{ width: 'auto', minWidth: '160px', cursor: 'pointer' }} value={statusFilter} onChange={e => { setStatusFilter(e.target.value); setPage(1) }}>
              <option value="">Semua Status</option>
              <option value="PENDING">Menunggu Pembayaran</option>
              <option value="PAID">Dibayar</option>
              <option value="PROCESSING">Diproses</option>
              <option value="SUCCESS">Sukses</option>
              <option value="FAILED">Gagal</option>
              <option value="CANCELLED">Dibatalkan</option>
            </select>
          )}
        </div>

        <div className="card" style={{ overflow: 'hidden' }}>
          {loading ? (
            <div style={{ padding: '24px' }}>
              {Array(5).fill(0).map((_, i) => <div key={i} className="skeleton" style={{ height: 80, borderRadius: 12, marginBottom: 16 }} />)}
            </div>
          ) : (activeTab === 'regular' ? orders : otpOrders).length === 0 ? (
            <div style={{ padding: '80px 24px', textAlign: 'center', color: '#475569' }}>
              <div style={{ fontSize: '48px', marginBottom: '16px' }}>📭</div>
              <p>Tidak ada pesanan ditemukan</p>
            </div>
          ) : activeTab === 'regular' ? (
            <div className="table-container">
              <table>
                <thead>
                  <tr>
                    <th>Order ID</th>
                    <th>Produk</th>
                    <th>Target</th>
                    <th>Harga</th>
                    <th>Status</th>
                    <th>Ulasan</th>
                  </tr>
                </thead>
                <tbody>
                  {orders.map(order => {
                    const statusConfig = getOrderStatusConfig(order.status)
                    const productName = order.productType === 'VIP'
                      ? `${order.vipProduct?.gameName || 'Game'} - ${order.vipProduct?.productName || 'Product'}`
                      : order.digitalProduct?.name || 'Produk Digital'
                    const canReview = order.status === 'SUCCESS' && !order.review && !reviewedIds.has(order.id)

                    return (
                      <tr key={order.id}>
                        <td style={{ fontFamily: 'monospace', color: '#f59e0b', fontWeight: 600 }}>
                          #{order.id.slice(-8).toUpperCase()}
                          <div style={{ fontSize: '11px', color: '#64748b', fontWeight: 400, marginTop: '4px' }}>{formatDate(order.createdAt)}</div>
                        </td>
                        <td style={{ fontWeight: 500, color: '#e2e8f0' }}>
                          {productName}
                          <div style={{ fontSize: '11px', color: '#64748b', marginTop: '4px' }}>{order.productType}</div>
                        </td>
                        <td style={{ color: '#94a3b8' }}>
                          {order.targetId || '-'}{order.zone ? ` (${order.zone})` : ''}
                        </td>
                        <td style={{ fontWeight: 600, color: '#e2e8f0' }}>{formatRupiah(order.price)}</td>
                        <td>
                          <span className="badge" style={{ background: statusConfig.bg, color: statusConfig.color }}>{statusConfig.label}</span>
                        </td>
                        <td>
                          {order.review || reviewedIds.has(order.id) ? (
                            <span style={{ fontSize: '12px', color: '#f59e0b' }}>⭐ Sudah diulas</span>
                          ) : canReview ? (
                            <button
                              onClick={() => setReviewOrder(order)}
                              className="btn btn-secondary"
                              style={{ padding: '5px 10px', fontSize: '11px', borderColor: 'rgba(245,158,11,0.3)', color: '#f59e0b' }}
                            >⭐ Beri Ulasan</button>
                          ) : (
                            <span style={{ fontSize: '12px', color: '#374151' }}>-</span>
                          )}
                        </td>
                      </tr>
                    )
                  })}
                </tbody>
              </table>
            </div>
          ) : (
            /* OTP Orders Table - unchanged */
            <div className="table-container">
              <table>
                <thead>
                  <tr>
                    <th>Order ID</th>
                    <th>Layanan &amp; Negara</th>
                    <th>Nomor &amp; OTP</th>
                    <th>Harga</th>
                    <th>Status</th>
                    <th>Aksi</th>
                  </tr>
                </thead>
                <tbody>
                  {otpOrders.map(order => {
                    const statusColors: Record<string, string> = { pending: '#f59e0b', received: '#10b981', done: '#3b82f6', cancel: '#ef4444' }
                    const c = statusColors[order.status] || '#64748b'
                    return (
                      <tr key={order.id}>
                        <td style={{ fontFamily: 'monospace', color: '#f59e0b', fontWeight: 600 }}>
                          #{order.id.slice(-8).toUpperCase()}
                          <div style={{ fontSize: '11px', color: '#64748b', fontWeight: 400, marginTop: '4px' }}>{formatDate(order.createdAt)}</div>
                        </td>
                        <td style={{ fontWeight: 500, color: '#e2e8f0' }}>
                          {order.serviceName}
                          <div style={{ fontSize: '11px', color: '#64748b', marginTop: '4px' }}>{order.countryName}</div>
                        </td>
                        <td style={{ color: '#e2e8f0' }}>
                          <div style={{ fontWeight: 600, letterSpacing: '0.5px' }}>{order.phoneNumber || '-'}</div>
                          {order.otpCode && <div style={{ fontSize: '14px', color: '#10b981', fontWeight: 800, marginTop: '4px', fontFamily: 'monospace' }}>{order.otpCode}</div>}
                        </td>
                        <td style={{ fontWeight: 600, color: '#e2e8f0' }}>{formatRupiah(order.price)}</td>
                        <td>
                          <span className="badge" style={{ background: `${c}20`, color: c, textTransform: 'uppercase' }}>{order.status}</span>
                        </td>
                        <td>
                          <button onClick={() => window.location.href = `/otp/${order.id}`} className="btn btn-secondary" style={{ padding: '6px 12px', fontSize: '11px' }}>Detail</button>
                        </td>
                      </tr>
                    )
                  })}
                </tbody>
              </table>
            </div>
          )}
        </div>

        {/* Pagination */}
        {totalPages > 1 && (
          <div style={{ display: 'flex', justifyContent: 'center', gap: '8px', marginTop: '24px' }}>
            <button className="btn btn-secondary" disabled={page === 1} onClick={() => setPage(p => p - 1)}>← Prev</button>
            <div style={{ display: 'flex', alignItems: 'center', padding: '0 16px', color: '#94a3b8', fontSize: '14px' }}>Hal {page} dari {totalPages}</div>
            <button className="btn btn-secondary" disabled={page === totalPages} onClick={() => setPage(p => p + 1)}>Next →</button>
          </div>
        )}
      </div>
    </main>
  )
}
