'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 Footer from '@/components/Footer'
import { formatRupiah } from '@/lib/utils'

const POPULAR_SERVICES = [
  { id: 13, name: 'WhatsApp', icon: '💬', color: '#25d366' },
  { id: 1, name: 'Telegram', icon: '✈️', color: '#2aabee' },
  { id: 2, name: 'Gmail/Google', icon: '📧', color: '#ea4335' },
  { id: 3, name: 'Facebook', icon: '👤', color: '#1877f2' },
  { id: 4, name: 'Instagram', icon: '📸', color: '#e1306c' },
  { id: 7, name: 'TikTok', icon: '🎵', color: '#010101' },
  { id: 8, name: 'Twitter/X', icon: '🐦', color: '#1da1f2' },
  { id: 9, name: 'Discord', icon: '🎮', color: '#5865f2' },
]

export default function OtpPage() {
  const { data: session } = useSession()
  const router = useRouter()

  const [step, setStep] = useState(1)
  const [selectedService, setSelectedService] = useState<any>(null)
  const [countries, setCountries] = useState<any[]>([])
  const [markup, setMarkup] = useState(10)
  const [loadingCountries, setLoadingCountries] = useState(false)
  const [selectedCountry, setSelectedCountry] = useState<any>(null)
  const [selectedProvider, setSelectedProvider] = useState<any>(null)
  const [operators, setOperators] = useState<any[]>([])
  const [loadingOperators, setLoadingOperators] = useState(false)
  const [selectedOperator, setSelectedOperator] = useState<any>(null)
  const [ordering, setOrdering] = useState(false)
  const [error, setError] = useState('')
  const [searchCountry, setSearchCountry] = useState('')

  const handleSelectService = async (service: any) => {
    setSelectedService(service)
    setStep(2)
    setLoadingCountries(true)
    setError('')
    try {
      const res = await fetch(`/api/otp/countries?service_id=${service.id}`)
      const data = await res.json()
      if (!res.ok || data.error) {
        throw new Error(data.error || 'Gagal memuat daftar negara dari server')
      }
      
      // Some APIs might return `{ result: false, message: "..." }` in data.countries
      if (data.countries && data.countries.result === false) {
        throw new Error(data.countries.message || 'Gagal mengambil data dari provider')
      }

      // Ensure countries is an array
      const countriesData = Array.isArray(data.countries) ? data.countries : (data.countries?.data || []);
      setCountries(countriesData);
      setMarkup(data.markup || 10)
    } catch (err: any) {
      setError(err.message || 'Gagal memuat daftar negara')
    }
    setLoadingCountries(false)
  }

  const handleSelectProvider = async (country: any, provider: any) => {
    setSelectedCountry(country)
    setSelectedProvider(provider)
    setStep(3)
    setLoadingOperators(true)
    setError('')
    try {
      const res = await fetch(`/api/otp/operators?country=${encodeURIComponent(country.name.toLowerCase())}&provider_id=${provider.provider_id}`)
      const data = await res.json()
      if (!res.ok || data.error) {
        throw new Error(data.error || 'Gagal memuat daftar operator')
      }
      
      if (data.operators && data.operators.result === false) {
        throw new Error(data.operators.message || 'Gagal mengambil data dari provider')
      }

      const operatorsData = Array.isArray(data.operators) ? data.operators : (data.operators?.data || []);
      setOperators(operatorsData)
    } catch (err: any) {
      setError(err.message || 'Gagal memuat operator')
    }
    setLoadingOperators(false)
  }

  const handleOrder = async () => {
    if (!session) { router.push('/auth/login'); return }
    if (!selectedOperator) { setError('Pilih operator terlebih dahulu'); return }

    setOrdering(true)
    setError('')
    try {
      const sellPrice = Math.ceil(selectedProvider.price * (1 + markup / 100))
      const res = await fetch('/api/otp/orders', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          serviceId: selectedService.id,
          serviceName: selectedService.name,
          countryName: selectedCountry.name,
          numberId: selectedProvider.provider_id,
          providerId: selectedProvider.provider_id,
          operatorId: selectedOperator.id,
          basePrice: selectedProvider.price,
        }),
      })
      const data = await res.json()
      if (!res.ok) throw new Error(data.error || 'Gagal membuat pesanan')
      router.push(`/otp/${data.orderId}`)
    } catch (err: any) {
      setError(err.message)
    }
    setOrdering(false)
  }

  const filteredCountries = Array.isArray(countries) ? countries.filter(c =>
    c?.name?.toLowerCase().includes(searchCountry.toLowerCase())
  ) : []

  const stepLabels = ['Pilih Layanan', 'Pilih Negara & Harga', 'Pilih Operator', 'Konfirmasi']

  return (
    <main style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column', background: '#0a0a0f' }}>
      <Navbar />
      <div style={{ paddingTop: '80px', flex: 1, maxWidth: '900px', margin: '0 auto', padding: '80px 24px 60px', width: '100%' }}>
        
        {/* Header */}
        <div style={{ marginBottom: '32px' }}>
          <h1 className="font-game" style={{ fontSize: '32px', fontWeight: 700, color: '#f1f5f9', marginBottom: '8px' }}>
            📱 Nomor OTP Virtual
          </h1>
          <p style={{ color: '#64748b' }}>Beli nomor virtual untuk verifikasi OTP berbagai layanan</p>
        </div>

        {/* Step Indicator */}
        <div style={{ display: 'flex', gap: '8px', marginBottom: '32px', overflowX: 'auto' }}>
          {stepLabels.map((label, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: '8px', flexShrink: 0 }}>
              <div style={{
                width: 28, height: 28, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center',
                background: step > i + 1 ? '#10b981' : step === i + 1 ? '#f59e0b' : 'rgba(255,255,255,0.06)',
                color: step >= i + 1 ? '#000' : '#64748b', fontSize: '13px', fontWeight: 700,
              }}>
                {step > i + 1 ? '✓' : i + 1}
              </div>
              <span style={{ fontSize: '13px', color: step === i + 1 ? '#f59e0b' : '#64748b', fontWeight: step === i + 1 ? 600 : 400 }}>{label}</span>
              {i < stepLabels.length - 1 && <div style={{ width: 24, height: 1, background: 'rgba(255,255,255,0.1)' }} />}
            </div>
          ))}
        </div>

        {error && (
          <div style={{ padding: '12px 16px', background: 'rgba(239,68,68,0.1)', border: '1px solid rgba(239,68,68,0.2)', borderRadius: '10px', color: '#ef4444', fontSize: '14px', marginBottom: '20px' }}>
            ❌ {error}
          </div>
        )}

        {/* Step 1: Service Selection */}
        {step === 1 && (
          <div>
            <h2 style={{ fontSize: '16px', fontWeight: 600, color: '#94a3b8', marginBottom: '20px' }}>Pilih Layanan</h2>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(160px, 1fr))', gap: '12px' }}>
              {POPULAR_SERVICES.map(svc => (
                <button
                  key={svc.id}
                  onClick={() => handleSelectService(svc)}
                  style={{
                    padding: '20px 16px', borderRadius: '14px', border: '1px solid rgba(255,255,255,0.08)',
                    background: '#16161f', cursor: 'pointer', textAlign: 'center', transition: 'all 0.2s',
                  }}
                  onMouseEnter={e => { (e.currentTarget as HTMLElement).style.borderColor = svc.color; (e.currentTarget as HTMLElement).style.background = `${svc.color}15` }}
                  onMouseLeave={e => { (e.currentTarget as HTMLElement).style.borderColor = 'rgba(255,255,255,0.08)'; (e.currentTarget as HTMLElement).style.background = '#16161f' }}
                >
                  <div style={{ fontSize: '36px', marginBottom: '8px' }}>{svc.icon}</div>
                  <div style={{ fontSize: '14px', fontWeight: 600, color: '#e2e8f0' }}>{svc.name}</div>
                </button>
              ))}
            </div>
          </div>
        )}

        {/* Step 2: Country Selection */}
        {step === 2 && (
          <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px' }}>
              <h2 style={{ fontSize: '16px', fontWeight: 600, color: '#94a3b8' }}>Pilih Negara & Harga — {selectedService?.name}</h2>
              <button onClick={() => { setStep(1); setSelectedService(null) }} style={{ background: 'transparent', border: '1px solid rgba(255,255,255,0.1)', borderRadius: '8px', color: '#64748b', padding: '6px 12px', cursor: 'pointer', fontSize: '13px' }}>← Kembali</button>
            </div>
            <input
              className="input" placeholder="🔍 Cari negara..."
              value={searchCountry} onChange={e => setSearchCountry(e.target.value)}
              style={{ marginBottom: '16px' }}
            />
            {loadingCountries ? (
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: '12px' }}>
                {Array(6).fill(0).map((_, i) => <div key={i} className="skeleton" style={{ height: 80, borderRadius: 12 }} />)}
              </div>
            ) : (
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: '12px', maxHeight: '500px', overflowY: 'auto' }}>
                {filteredCountries.length === 0 ? (
                  <div style={{ textAlign: 'center', padding: '40px', color: '#64748b', gridColumn: '1 / -1' }}>
                    Tidak ada data negara ditemukan. (Pastikan koneksi API RumahOTP berfungsi)
                  </div>
                ) : (
                  filteredCountries.map((country: any) => {
                    const prices = country.pricelist || country.price_list || country.prices || [];
                    
                    if (!prices || prices.length === 0) {
                      return null; // Skip if no prices
                    }
                    
                    return prices.map((provider: any, pi: number) => {
                      const sellPrice = Math.ceil(provider.price * (1 + markup / 100))
                      return (
                        <button
                          key={`${country.name}-${pi}`}
                          onClick={() => handleSelectProvider(country, provider)}
                          style={{
                            padding: '16px', borderRadius: '12px', border: '1px solid rgba(255,255,255,0.08)',
                            background: '#16161f', cursor: 'pointer', textAlign: 'left', transition: 'all 0.2s', display: 'flex', alignItems: 'center', gap: '12px',
                          }}
                          onMouseEnter={e => { (e.currentTarget as HTMLElement).style.borderColor = '#f59e0b'; (e.currentTarget as HTMLElement).style.background = 'rgba(245,158,11,0.08)' }}
                          onMouseLeave={e => { (e.currentTarget as HTMLElement).style.borderColor = 'rgba(255,255,255,0.08)'; (e.currentTarget as HTMLElement).style.background = '#16161f' }}
                        >
                          {country.img && <img src={country.img} alt={country.name} style={{ width: 32, height: 24, objectFit: 'cover', borderRadius: 4 }} />}
                          <div style={{ flex: 1 }}>
                            <div style={{ fontSize: '14px', fontWeight: 600, color: '#e2e8f0' }}>{country.name}</div>
                            <div style={{ fontSize: '12px', color: '#64748b', marginTop: '2px' }}>Stok: {provider.stock} • Success: {provider.success_rate}%</div>
                          </div>
                          <div style={{ fontSize: '14px', fontWeight: 700, color: '#f59e0b' }}>{formatRupiah(sellPrice)}</div>
                        </button>
                      )
                    })
                  })
                )}
              </div>
            )}
          </div>
        )}

        {/* Step 3: Operator Selection */}
        {step === 3 && (
          <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px' }}>
              <h2 style={{ fontSize: '16px', fontWeight: 600, color: '#94a3b8' }}>Pilih Operator — {selectedCountry?.name}</h2>
              <button onClick={() => { setStep(2); setSelectedCountry(null); setSelectedProvider(null) }} style={{ background: 'transparent', border: '1px solid rgba(255,255,255,0.1)', borderRadius: '8px', color: '#64748b', padding: '6px 12px', cursor: 'pointer', fontSize: '13px' }}>← Kembali</button>
            </div>
            {loadingOperators ? (
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))', gap: '12px' }}>
                {Array(4).fill(0).map((_, i) => <div key={i} className="skeleton" style={{ height: 70, borderRadius: 12 }} />)}
              </div>
            ) : operators.length === 0 ? (
              <div style={{ textAlign: 'center', padding: '60px', color: '#475569' }}>
                <div style={{ fontSize: '40px', marginBottom: '12px' }}>📡</div>
                <p>Tidak ada operator tersedia untuk kombinasi ini</p>
              </div>
            ) : (
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))', gap: '12px' }}>
                {operators.map((op: any) => (
                  <button
                    key={op.id}
                    onClick={() => { setSelectedOperator(op); setStep(4) }}
                    style={{
                      padding: '16px', borderRadius: '12px',
                      border: `2px solid ${selectedOperator?.id === op.id ? '#f59e0b' : 'rgba(255,255,255,0.08)'}`,
                      background: selectedOperator?.id === op.id ? 'rgba(245,158,11,0.1)' : '#16161f',
                      cursor: 'pointer', textAlign: 'center', transition: 'all 0.2s',
                    }}
                  >
                    {op.img && <img src={op.img} alt={op.name} style={{ width: 40, height: 40, objectFit: 'contain', marginBottom: '8px' }} />}
                    <div style={{ fontSize: '14px', fontWeight: 600, color: '#e2e8f0' }}>{op.name}</div>
                  </button>
                ))}
              </div>
            )}
          </div>
        )}

        {/* Step 4: Confirm */}
        {step === 4 && (
          <div className="card" style={{ padding: '32px', maxWidth: '480px', margin: '0 auto' }}>
            <h2 style={{ fontSize: '18px', fontWeight: 700, color: '#f1f5f9', marginBottom: '24px', textAlign: 'center' }}>📋 Ringkasan Pesanan</h2>
            <div style={{ display: 'flex', flexDirection: 'column', gap: '12px', marginBottom: '24px' }}>
              {[
                { label: 'Layanan', value: selectedService?.name },
                { label: 'Negara', value: selectedCountry?.name },
                { label: 'Operator', value: selectedOperator?.name },
                { label: 'Harga', value: formatRupiah(Math.ceil(selectedProvider?.price * (1 + markup / 100))) },
                { label: 'Pembayaran', value: 'Saldo Akun' },
              ].map(row => (
                <div key={row.label} style={{ display: 'flex', justifyContent: 'space-between', padding: '10px 0', borderBottom: '1px solid rgba(255,255,255,0.05)' }}>
                  <span style={{ color: '#64748b', fontSize: '14px' }}>{row.label}</span>
                  <span style={{ color: '#e2e8f0', fontWeight: 600, fontSize: '14px' }}>{row.value}</span>
                </div>
              ))}
            </div>
            <p style={{ fontSize: '12px', color: '#475569', marginBottom: '20px', textAlign: 'center' }}>
              ⚠️ Pembayaran menggunakan Saldo Akun. Pastikan saldo mencukupi.
            </p>
            <div style={{ display: 'flex', gap: '12px' }}>
              <button onClick={() => setStep(3)} style={{ flex: 1, padding: '12px', background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.1)', borderRadius: '10px', color: '#94a3b8', cursor: 'pointer', fontWeight: 600 }}>Kembali</button>
              <button onClick={handleOrder} disabled={ordering} className="btn btn-primary" style={{ flex: 2, padding: '12px' }}>
                {ordering ? <><span className="spinner" /> Memproses...</> : '✅ Pesan Sekarang'}
              </button>
            </div>
          </div>
        )}
      </div>
      <Footer />
    </main>
  )
}
