'use client'

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

export default function AdminDigitalProducts() {
  const [products, setProducts] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [showModal, setShowModal] = useState(false)
  const [showStockModal, setShowStockModal] = useState(false)
  const [editingId, setEditingId] = useState<string | null>(null)
  const [activeProductId, setActiveProductId] = useState<string | null>(null)
  const [activeProductName, setActiveProductName] = useState('')
  const [stockAccounts, setStockAccounts] = useState<any[]>([])
  const [accountsText, setAccountsText] = useState('')
  const [formData, setFormData] = useState({ name: '', description: '', price: '', type: 'MANUAL', isActive: true })

  const fetchAccounts = async (productId: string) => {
    const res = await fetch(`/api/admin/products/digital/${productId}/accounts`)
    const data = await res.json()
    if (res.ok) setStockAccounts(data.accounts || [])
  }

  const openStockModal = (product: any) => {
    setActiveProductId(product.id)
    setActiveProductName(product.name)
    setAccountsText('')
    fetchAccounts(product.id)
    setShowStockModal(true)
  }

  const handleAddStock = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!activeProductId || !accountsText.trim()) return
    
    try {
      const res = await fetch(`/api/admin/products/digital/${activeProductId}/accounts`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ accountsText }),
      })
      const data = await res.json()
      if (!res.ok) throw new Error(data.error)
      alert(data.message)
      setAccountsText('')
      fetchAccounts(activeProductId)
      fetchProducts()
    } catch (err: any) {
      alert(err.message || 'Gagal menambah stok')
    }
  }

  const handleDeleteStock = async (accountId: string) => {
    if (!confirm('Hapus akun ini dari stok?')) return
    try {
      const res = await fetch(`/api/admin/products/digital/${activeProductId}/accounts?accountId=${accountId}`, { method: 'DELETE' })
      if (!res.ok) throw new Error('Gagal')
      fetchAccounts(activeProductId!)
      fetchProducts()
    } catch (err) {
      alert('Error menghapus akun')
    }
  }

  const openEditModal = (product: any) => {
    setEditingId(product.id)
    setFormData({
      name: product.name,
      description: product.description || '',
      price: product.price.toString(),
      type: product.type,
      isActive: product.isActive
    })
    setShowModal(true)
  }

  const openAddModal = () => {
    setEditingId(null)
    setFormData({ name: '', description: '', price: '', type: 'MANUAL', isActive: true })
    setShowModal(true)
  }

  const fetchProducts = () => {
    setLoading(true)
    fetch('/api/admin/products/digital')
      .then(r => r.json())
      .then(d => { setProducts(d.products || []); setLoading(false) })
  }

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

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    try {
      const res = await fetch('/api/admin/products/digital', {
        method: editingId ? 'PUT' : 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...formData, id: editingId, price: Number(formData.price) }),
      })
      if (!res.ok) throw new Error('Gagal menyimpan')
      setShowModal(false)
      fetchProducts()
    } catch (err) { alert('Error saving product') }
  }

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: '24px' }}>
        <div>
          <h1 className="font-game" style={{ fontSize: '28px', fontWeight: 700, color: '#f1f5f9', marginBottom: '8px' }}>App Premium / Digital</h1>
          <p style={{ color: '#64748b' }}>Kelola produk Netflix, Spotify, Canva dll</p>
        </div>
        <button className="btn btn-primary" onClick={openAddModal}>+ Tambah Produk</button>
      </div>

      <div className="card table-container">
        {loading ? <div className="spinner" style={{ margin: '40px auto', display: 'block' }} /> : (
          <table>
            <thead>
              <tr>
                <th>Nama Produk</th>
                <th>Harga</th>
                <th>Tipe</th>
                <th>Stok / Akun</th>
                <th>Status</th>
                <th>Aksi</th>
              </tr>
            </thead>
            <tbody>
              {products.map(p => (
                <tr key={p.id}>
                  <td style={{ fontWeight: 600 }}>{p.name}</td>
                  <td style={{ color: '#10b981', fontWeight: 600 }}>{formatRupiah(p.price)}</td>
                  <td>
                    <span className="badge badge-purple">{p.type}</span>
                  </td>
                  <td>{p.type === 'AUTO' ? `${p._count?.accounts || 0} Akun` : '- (Manual)'}</td>
                  <td>
                    <span className="badge" style={{ background: p.isActive ? 'rgba(16,185,129,0.1)' : 'rgba(239,68,68,0.1)', color: p.isActive ? '#10b981' : '#ef4444' }}>
                      {p.isActive ? 'Aktif' : 'Nonaktif'}
                    </span>
                  </td>
                  <td>
                    <button className="btn btn-secondary" style={{ padding: '6px 12px', fontSize: '12px' }} onClick={() => openEditModal(p)}>Edit</button>
                    {p.type === 'AUTO' && (
                      <button className="btn btn-primary" style={{ padding: '6px 12px', fontSize: '12px' }} onClick={() => openStockModal(p)}>
                        Kelola Stok
                      </button>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      {/* Modal Add Product */}
      {showModal && (
        <div style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, background: 'rgba(0,0,0,0.8)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 100 }}>
          <div className="card" style={{ width: '100%', maxWidth: '500px', padding: '24px' }}>
            <h2 style={{ fontSize: '20px', fontWeight: 600, marginBottom: '24px' }}>{editingId ? 'Edit Produk Digital' : 'Tambah Produk Digital'}</h2>
            <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
              <div>
                <label className="label">Nama Produk (contoh: Netflix Premium 1 Bulan)</label>
                <input className="input" value={formData.name} onChange={e => setFormData({...formData, name: e.target.value})} required />
              </div>
              <div>
                <label className="label">Harga Jual (Rp)</label>
                <input className="input" type="number" value={formData.price} onChange={e => setFormData({...formData, price: e.target.value})} required />
              </div>
              <div>
                <label className="label">Tipe Pengiriman</label>
                <select className="input" value={formData.type} onChange={e => setFormData({...formData, type: e.target.value})}>
                  <option value="MANUAL">MANUAL (Admin kirim manual di pesanan)</option>
                  <option value="AUTO">AUTO (Ambil dari stok database)</option>
                </select>
              </div>
              <div>
                <label className="label">Deskripsi</label>
                <textarea className="input" style={{ minHeight: '80px' }} value={formData.description} onChange={e => setFormData({...formData, description: e.target.value})} />
              </div>
              <div style={{ display: 'flex', gap: '12px', marginTop: '16px' }}>
                <button type="button" className="btn btn-secondary" style={{ flex: 1 }} onClick={() => setShowModal(false)}>Batal</button>
                <button type="submit" className="btn btn-primary" style={{ flex: 1 }}>Simpan</button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Modal Manage Stock */}
      {showStockModal && (
        <div style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, background: 'rgba(0,0,0,0.8)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 100 }}>
          <div className="card" style={{ width: '100%', maxWidth: '600px', padding: '24px', maxHeight: '90vh', overflowY: 'auto' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
              <h2 style={{ fontSize: '20px', fontWeight: 600 }}>Kelola Stok: {activeProductName}</h2>
              <button onClick={() => setShowStockModal(false)} style={{ background: 'transparent', border: 'none', color: '#94a3b8', fontSize: '20px', cursor: 'pointer' }}>×</button>
            </div>

            <form onSubmit={handleAddStock} style={{ marginBottom: '32px' }}>
              <label className="label">Tambah Stok Massal (Format: email:password)</label>
              <p style={{ fontSize: '12px', color: '#64748b', marginBottom: '8px' }}>
                Paste banyak akun sekaligus. Pisahkan tiap akun dengan enter (baris baru).
              </p>
              <textarea 
                className="input" 
                style={{ minHeight: '120px', fontFamily: 'monospace', marginBottom: '12px' }} 
                placeholder="email1@gmail.com:pass123&#10;email2@gmail.com:pass456"
                value={accountsText}
                onChange={e => setAccountsText(e.target.value)}
                required
              />
              <button type="submit" className="btn btn-primary" style={{ width: '100%' }}>+ Tambahkan ke Database</button>
            </form>

            <h3 style={{ fontSize: '16px', fontWeight: 600, marginBottom: '12px' }}>Stok Tersedia ({stockAccounts.length})</h3>
            <div style={{ background: 'rgba(255,255,255,0.02)', borderRadius: '12px', overflow: 'hidden' }}>
              {stockAccounts.length === 0 ? (
                <p style={{ padding: '24px', textAlign: 'center', color: '#64748b', margin: 0 }}>Belum ada stok tersedia.</p>
              ) : (
                <table style={{ width: '100%', fontSize: '13px' }}>
                  <tbody>
                    {stockAccounts.map(acc => (
                      <tr key={acc.id} style={{ borderBottom: '1px solid rgba(255,255,255,0.05)' }}>
                        <td style={{ padding: '12px' }}>{acc.email}</td>
                        <td style={{ padding: '12px', fontFamily: 'monospace', color: '#94a3b8' }}>{acc.password}</td>
                        <td style={{ padding: '12px', textAlign: 'right' }}>
                          <button onClick={() => handleDeleteStock(acc.id)} style={{ background: 'transparent', border: 'none', color: '#ef4444', cursor: 'pointer' }}>Hapus</button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
