'use client'

import { useState, useEffect } from 'react'

export default function AdminCategories() {
  const [categories, setCategories] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [page, setPage] = useState(1)
  const [totalPages, setTotalPages] = useState(1)
  const [search, setSearch] = useState('')
  const [editingId, setEditingId] = useState<string | null>(null)
  const [editForm, setEditForm] = useState<any>({ name: '', thumbnail: '', isActive: true, fieldConfig: null })
  const [configModal, setConfigModal] = useState<any>(null)

  const fetchCategories = () => {
    setLoading(true)
    fetch(`/api/admin/categories?page=${page}&limit=20&search=${search}`)
      .then(r => r.json())
      .then(d => { setCategories(d.categories || []); setTotalPages(d.pages || 1); setLoading(false) })
  }

  useEffect(() => {
    const delay = setTimeout(fetchCategories, 300)
    return () => clearTimeout(delay)
  }, [page, search])

  const handleEdit = (cat: any) => {
    setEditingId(cat.id)
    setEditForm({ name: cat.name, thumbnail: cat.thumbnail || '', isActive: cat.isActive, fieldConfig: cat.fieldConfig || {} })
  }

  const handleSave = async (id: string) => {
    try {
      const res = await fetch(`/api/admin/categories/${id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(editForm)
      })
      if (!res.ok) {
        const errorData = await res.json()
        throw new Error(errorData.error || 'Failed to update')
      }
      setEditingId(null)
      fetchCategories()
    } catch (err: any) {
      alert(err.message)
    }
  }

  const handleDelete = async (id: string) => {
    if (!confirm('Yakin ingin menghapus kategori ini?')) return
    try {
      const res = await fetch(`/api/admin/categories/${id}`, { method: 'DELETE' })
      if (!res.ok) {
        const errorData = await res.json()
        throw new Error(errorData.error || 'Failed to delete')
      }
      fetchCategories()
    } catch (err: any) {
      alert(err.message)
    }
  }

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
        <h1 className="font-game" style={{ fontSize: '24px', color: '#f8fafc', margin: 0 }}>Kelola Kategori Game</h1>
      </div>

      <div className="card glass-panel" style={{ padding: '24px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '16px' }}>
          <input 
            type="text" 
            placeholder="Cari kategori..." 
            value={search}
            onChange={e => setSearch(e.target.value)}
            className="input"
            style={{ width: '300px' }}
          />
        </div>

        {loading ? (
          <div style={{ textAlign: 'center', padding: '40px' }}>Loading...</div>
        ) : (
          <div style={{ overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', textAlign: 'left', fontSize: '14px' }}>
              <thead>
                <tr style={{ borderBottom: '1px solid rgba(255,255,255,0.1)', color: '#94a3b8' }}>
                  <th style={{ padding: '12px 16px', fontWeight: 600 }}>Gambar</th>
                  <th style={{ padding: '12px 16px', fontWeight: 600 }}>Nama Kategori</th>
                  <th style={{ padding: '12px 16px', fontWeight: 600 }}>Slug</th>
                  <th style={{ padding: '12px 16px', fontWeight: 600 }}>Status</th>
                  <th style={{ padding: '12px 16px', fontWeight: 600, textAlign: 'right' }}>Aksi</th>
                </tr>
              </thead>
              <tbody>
                {categories.map((cat) => (
                  <tr key={cat.id} style={{ borderBottom: '1px solid rgba(255,255,255,0.05)' }}>
                    <td style={{ padding: '12px 16px' }}>
                      {editingId === cat.id ? (
                        <input 
                          type="text" 
                          value={editForm.thumbnail} 
                          onChange={e => setEditForm({ ...editForm, thumbnail: e.target.value })} 
                          placeholder="URL Gambar"
                          className="input"
                          style={{ width: '200px', padding: '6px 10px', fontSize: '13px' }}
                        />
                      ) : (
                        cat.thumbnail ? <img src={cat.thumbnail} alt={cat.name} style={{ width: 40, height: 40, borderRadius: 8, objectFit: 'cover' }} /> : <span style={{ color: '#64748b' }}>-</span>
                      )}
                    </td>
                    <td style={{ padding: '12px 16px', color: '#f1f5f9' }}>
                      {editingId === cat.id ? (
                        <input 
                          type="text" 
                          value={editForm.name} 
                          onChange={e => setEditForm({ ...editForm, name: e.target.value })} 
                          className="input"
                          style={{ padding: '6px 10px', fontSize: '13px' }}
                        />
                      ) : (
                        cat.name
                      )}
                    </td>
                    <td style={{ padding: '12px 16px', color: '#64748b' }}>{cat.slug}</td>
                    <td style={{ padding: '12px 16px' }}>
                      {editingId === cat.id ? (
                        <select 
                          value={editForm.isActive ? '1' : '0'} 
                          onChange={e => setEditForm({ ...editForm, isActive: e.target.value === '1' })}
                          className="input"
                          style={{ padding: '6px 10px', fontSize: '13px' }}
                        >
                          <option value="1">Aktif</option>
                          <option value="0">Nonaktif</option>
                        </select>
                      ) : (
                        <span style={{ 
                          background: cat.isActive ? 'rgba(16, 185, 129, 0.1)' : 'rgba(239, 68, 68, 0.1)',
                          color: cat.isActive ? '#10b981' : '#ef4444',
                          padding: '4px 8px', borderRadius: '4px', fontSize: '12px', fontWeight: 600
                        }}>
                          {cat.isActive ? 'Aktif' : 'Nonaktif'}
                        </span>
                      )}
                    </td>
                    <td style={{ padding: '12px 16px', textAlign: 'right' }}>
                      {editingId === cat.id ? (
                        <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end', flexDirection: 'column' }}>
                          <button onClick={() => setConfigModal(cat)} className="btn btn-secondary" style={{ padding: '6px 12px', fontSize: '12px' }}>⚙️ Atur Kolom Input</button>
                          <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end' }}>
                            <button onClick={() => setEditingId(null)} className="btn btn-secondary" style={{ padding: '6px 12px', fontSize: '13px' }}>Batal</button>
                            <button onClick={() => handleSave(cat.id)} className="btn btn-primary" style={{ padding: '6px 12px', fontSize: '13px' }}>Simpan</button>
                          </div>
                        </div>
                      ) : (
                        <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end' }}>
                          <button onClick={() => handleEdit(cat)} className="btn btn-secondary" style={{ padding: '6px 12px', fontSize: '13px' }}>Edit</button>
                          <button onClick={() => handleDelete(cat.id)} className="btn btn-secondary" style={{ padding: '6px 12px', fontSize: '13px', color: '#ef4444', borderColor: 'rgba(239,68,68,0.2)' }}>Hapus</button>
                        </div>
                      )}
                    </td>
                  </tr>
                ))}
                {categories.length === 0 && (
                  <tr>
                    <td colSpan={5} style={{ padding: '24px', textAlign: 'center', color: '#64748b' }}>Tidak ada kategori ditemukan.</td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        )}

        {/* Pagination */}
        {totalPages > 1 && (
          <div style={{ display: 'flex', justifyContent: 'center', gap: '8px', marginTop: '24px' }}>
            <button 
              disabled={page === 1} 
              onClick={() => setPage(p => p - 1)}
              className="btn btn-secondary"
              style={{ padding: '6px 12px' }}
            >
              &lt; Prev
            </button>
            <span style={{ display: 'flex', alignItems: 'center', color: '#94a3b8', fontSize: '14px' }}>
              {page} / {totalPages}
            </span>
            <button 
              disabled={page === totalPages} 
              onClick={() => setPage(p => p + 1)}
              className="btn btn-secondary"
              style={{ padding: '6px 12px' }}
            >
              Next &gt;
            </button>
          </div>
        )}
      </div>

      {/* Modal Pengaturan Kolom Input */}
      {configModal && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.8)', zIndex: 100, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <div className="card glass-panel" style={{ width: '400px', padding: '24px', background: '#111118' }}>
            <h3 style={{ fontSize: '18px', fontWeight: 600, color: '#f1f5f9', marginBottom: '16px' }}>Konfigurasi Input Form ({configModal.name})</h3>
            <p style={{ color: '#94a3b8', fontSize: '13px', marginBottom: '24px' }}>Atur field apa saja yang diminta ke pelanggan saat order.</p>
            
            <div style={{ marginBottom: '16px' }}>
              <label style={{ display: 'block', fontSize: '13px', marginBottom: '6px', color: '#cbd5e1' }}>Target Label (Wajib)</label>
              <input type="text" className="input" value={editForm.fieldConfig?.targetLabel || ''} onChange={e => setEditForm({...editForm, fieldConfig: {...editForm.fieldConfig, targetLabel: e.target.value}})} placeholder="Cth: User ID / Email" />
            </div>

            <div style={{ marginBottom: '16px', display: 'flex', alignItems: 'center', gap: '10px' }}>
              <input type="checkbox" id="hasZone" checked={editForm.fieldConfig?.hasZone || false} onChange={e => setEditForm({...editForm, fieldConfig: {...editForm.fieldConfig, hasZone: e.target.checked}})} />
              <label htmlFor="hasZone" style={{ fontSize: '13px', color: '#cbd5e1' }}>Gunakan Kolom Ke-2 (Zone/Server/Password)</label>
            </div>

            {editForm.fieldConfig?.hasZone && (
              <div style={{ marginBottom: '16px', paddingLeft: '24px', borderLeft: '2px solid #333' }}>
                <div style={{ marginBottom: '12px' }}>
                  <label style={{ display: 'block', fontSize: '13px', marginBottom: '6px', color: '#cbd5e1' }}>Zone Label</label>
                  <input type="text" className="input" value={editForm.fieldConfig?.zoneLabel || ''} onChange={e => setEditForm({...editForm, fieldConfig: {...editForm.fieldConfig, zoneLabel: e.target.value}})} placeholder="Cth: Zone ID / Password / Pilih Server" />
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: '13px', marginBottom: '6px', color: '#cbd5e1' }}>Tipe Input Zone</label>
                  <select className="input" value={editForm.fieldConfig?.zoneType || 'text'} onChange={e => setEditForm({...editForm, fieldConfig: {...editForm.fieldConfig, zoneType: e.target.value}})}>
                    <option value="text">Teks Bebas (Misal: Zone ID)</option>
                    <option value="server">Dropdown Pilihan Server</option>
                  </select>
                </div>
              </div>
            )}

            <div style={{ marginBottom: '16px', display: 'flex', alignItems: 'center', gap: '10px' }}>
              <input type="checkbox" id="hasExtra" checked={editForm.fieldConfig?.hasExtra || false} onChange={e => setEditForm({...editForm, fieldConfig: {...editForm.fieldConfig, hasExtra: e.target.checked}})} />
              <label htmlFor="hasExtra" style={{ fontSize: '13px', color: '#cbd5e1' }}>Gunakan Kolom Ke-3 (Additional Data VIP)</label>
            </div>

            {editForm.fieldConfig?.hasExtra && (
              <div style={{ marginBottom: '24px', paddingLeft: '24px', borderLeft: '2px solid #333' }}>
                <label style={{ display: 'block', fontSize: '13px', marginBottom: '6px', color: '#cbd5e1' }}>Label Kolom Ekstra</label>
                <input type="text" className="input" value={editForm.fieldConfig?.extraLabel || ''} onChange={e => setEditForm({...editForm, fieldConfig: {...editForm.fieldConfig, extraLabel: e.target.value}})} placeholder="Cth: Kode Keamanan" />
              </div>
            )}

            <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '12px', marginTop: '24px' }}>
              <button onClick={() => setConfigModal(null)} className="btn btn-primary" style={{ padding: '8px 16px' }}>Selesai</button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
