'use client'

import { useState, useEffect } from 'react'
import { formatRupiah } from '@/lib/utils'

export default function AdminSmmPage() {
  const [products, setProducts] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [isSyncing, setIsSyncing] = useState(false)
  const [filterCategory, setFilterCategory] = useState('')

  useEffect(() => {
    fetchProducts()
  }, [])

  const fetchProducts = async () => {
    setLoading(true)
    try {
      const res = await fetch('/api/admin/smm/products')
      setProducts(await res.json())
    } catch (e) {
      console.error(e)
    }
    setLoading(false)
  }

  const handleSync = async () => {
    if (!confirm('Proses ini akan mengambil data terbaru dari Zaynflazz dan memperbarui harga/layanan di database. Lanjutkan?')) return
    setIsSyncing(true)
    try {
      const res = await fetch('/api/admin/smm/sync', { method: 'POST' })
      const data = await res.json()
      if (!res.ok) throw new Error(data.error)
      alert(`Sinkronisasi berhasil! ${data.count} layanan tersimpan/terupdate.`)
      fetchProducts()
    } catch (e: any) {
      alert(`Gagal: ${e.message}`)
    }
    setIsSyncing(false)
  }

  const handleUpdateProduct = async (id: string, field: string, value: any) => {
    try {
      const res = await fetch('/api/admin/smm/products', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id, [field]: value })
      })
      if (!res.ok) throw new Error('Gagal update')
      
      // Update local state for fast UI
      setProducts(products.map(p => {
        if (p.id === id) {
          const updated = { ...p, [field]: value }
          if (field === 'margin') {
            updated.sellPrice = Number(p.price) + (Number(p.price) * Number(value) / 100)
          }
          return updated
        }
        return p
      }))
    } catch (e: any) {
      alert(e.message)
      fetchProducts() // Revert
    }
  }

  const categories = Array.from(new Set(products.map(p => p.category))).sort()
  const filteredProducts = filterCategory ? products.filter(p => p.category === filterCategory) : products

  if (loading) return <div className="spinner" style={{ margin: '100px auto', display: 'block' }} />

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px', flexWrap: 'wrap', gap: '16px' }}>
        <div>
          <h1 style={{ fontSize: '28px', fontWeight: 700, color: '#f1f5f9', marginBottom: '8px' }}>📱 SMM Panel (Zaynflazz)</h1>
          <p style={{ color: '#94a3b8' }}>Kelola layanan social media dari Zaynflazz</p>
        </div>
        
        <button 
          onClick={handleSync}
          disabled={isSyncing}
          style={{ background: '#ec4899', color: '#fff', border: 'none', padding: '10px 20px', borderRadius: '8px', fontWeight: 600, cursor: isSyncing ? 'not-allowed' : 'pointer', opacity: isSyncing ? 0.7 : 1 }}
        >
          {isSyncing ? 'Menyinkronkan...' : '🔄 Sinkronkan Zaynflazz'}
        </button>
      </div>

      <div className="card" style={{ padding: '24px' }}>
        <div style={{ marginBottom: '20px' }}>
          <select 
            value={filterCategory} 
            onChange={e => setFilterCategory(e.target.value)}
            style={{ padding: '8px 12px', background: '#0a0a0f', border: '1px solid rgba(255,255,255,0.1)', color: '#f1f5f9', borderRadius: '6px' }}
          >
            <option value="">Semua Kategori</option>
            {categories.map((c: any) => <option key={c} value={c}>{c}</option>)}
          </select>
        </div>

        <div style={{ overflowX: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '14px' }}>
            <thead>
              <tr style={{ background: 'rgba(255,255,255,0.02)', color: '#94a3b8', textAlign: 'left' }}>
                <th style={{ padding: '12px' }}>ID / Layanan</th>
                <th style={{ padding: '12px' }}>Kategori</th>
                <th style={{ padding: '12px' }}>Harga Asli</th>
                <th style={{ padding: '12px' }}>Margin (%)</th>
                <th style={{ padding: '12px' }}>Harga Jual</th>
                <th style={{ padding: '12px', textAlign: 'center' }}>Status</th>
              </tr>
            </thead>
            <tbody>
              {filteredProducts.map(p => (
                <tr key={p.id} style={{ borderBottom: '1px solid rgba(255,255,255,0.05)' }}>
                  <td style={{ padding: '12px' }}>
                    <div style={{ color: '#64748b', fontSize: '12px', marginBottom: '4px' }}>Service ID: {p.serviceId}</div>
                    <div style={{ color: '#f1f5f9', fontWeight: 500 }}>{p.name}</div>
                  </td>
                  <td style={{ padding: '12px', color: '#94a3b8' }}>{p.category}</td>
                  <td style={{ padding: '12px', color: '#94a3b8' }}>{formatRupiah(p.price)}</td>
                  <td style={{ padding: '12px' }}>
                    <input 
                      type="number" 
                      defaultValue={p.margin} 
                      onBlur={e => {
                        if (Number(e.target.value) !== p.margin) {
                          handleUpdateProduct(p.id, 'margin', e.target.value)
                        }
                      }}
                      style={{ width: '60px', padding: '6px', background: '#0a0a0f', border: '1px solid rgba(255,255,255,0.1)', color: '#fff', borderRadius: '4px', textAlign: 'center' }}
                    />
                  </td>
                  <td style={{ padding: '12px', color: '#10b981', fontWeight: 600 }}>{formatRupiah(p.sellPrice)}</td>
                  <td style={{ padding: '12px', textAlign: 'center' }}>
                    <label style={{ position: 'relative', display: 'inline-block', width: '40px', height: '24px' }}>
                      <input 
                        type="checkbox" 
                        checked={p.isActive} 
                        onChange={e => handleUpdateProduct(p.id, 'isActive', e.target.checked)}
                        style={{ opacity: 0, width: 0, height: 0 }} 
                      />
                      <span style={{ 
                        position: 'absolute', cursor: 'pointer', top: 0, left: 0, right: 0, bottom: 0, 
                        background: p.isActive ? '#10b981' : '#334155', borderRadius: '24px', transition: '0.4s' 
                      }}>
                        <span style={{
                          position: 'absolute', content: '""', height: '16px', width: '16px', left: '4px', bottom: '4px',
                          background: 'white', borderRadius: '50%', transition: '0.4s',
                          transform: p.isActive ? 'translateX(16px)' : 'none'
                        }} />
                      </span>
                    </label>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  )
}
