'use client'

import { useState, useEffect } from 'react'
import { useSession } from 'next-auth/react'

const DEFAULT_THEME = {
  accent: '#f59e0b',
  accentDark: '#d97706',
  accentLight: '#fbbf24',
  bgPrimary: '#0a0a0f',
  bgSecondary: '#111118',
  bgCard: '#16161f',
  success: '#10b981',
  error: '#ef4444',
}

const THEME_LABELS: Record<string, string> = {
  accent: 'Warna Aksen Utama',
  accentDark: 'Aksen Gelap',
  accentLight: 'Aksen Terang',
  bgPrimary: 'Background Utama',
  bgSecondary: 'Background Sekunder',
  bgCard: 'Background Kartu',
  success: 'Warna Sukses',
  error: 'Warna Error',
}

export default function AdminSettingsPage() {
  const { data: session } = useSession()
  const [theme, setTheme] = useState({ ...DEFAULT_THEME })
  const [otpMarkup, setOtpMarkup] = useState('10')
  const [banners, setBanners] = useState([{ image: '', link: '' }])
  const [popup, setPopup] = useState({ active: false, title: '', content: '', image: '' })
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [saved, setSaved] = useState(false)

  useEffect(() => {
    fetch('/api/admin/settings')
      .then(r => r.json())
      .then(data => {
        const s = data.settings || {}
        setTheme({
          accent: s.theme_accent || DEFAULT_THEME.accent,
          accentDark: s.theme_accentDark || DEFAULT_THEME.accentDark,
          accentLight: s.theme_accentLight || DEFAULT_THEME.accentLight,
          bgPrimary: s.theme_bgPrimary || DEFAULT_THEME.bgPrimary,
          bgSecondary: s.theme_bgSecondary || DEFAULT_THEME.bgSecondary,
          bgCard: s.theme_bgCard || DEFAULT_THEME.bgCard,
          success: s.theme_success || DEFAULT_THEME.success,
          error: s.theme_error || DEFAULT_THEME.error,
        })
        setOtpMarkup(s.otp_markup || '10')
        try {
          if (s.frontend_banners) setBanners(JSON.parse(s.frontend_banners))
          if (s.frontend_popup) setPopup(JSON.parse(s.frontend_popup))
        } catch {}
        setLoading(false)
      })
      .catch(() => setLoading(false))
  }, [])

  const handleSave = async () => {
    setSaving(true)
    const payload: Record<string, string> = { 
      otp_markup: otpMarkup,
      frontend_banners: JSON.stringify(banners.filter(b => b.image)),
      frontend_popup: JSON.stringify(popup),
    }
    for (const [key, val] of Object.entries(theme)) {
      payload[`theme_${key}`] = val
    }

    await fetch('/api/admin/settings', {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
    })
    setSaving(false)
    setSaved(true)
    setTimeout(() => setSaved(false), 3000)
  }

  const handleReset = () => setTheme({ ...DEFAULT_THEME })

  return (
    <div>
      <div style={{ marginBottom: '32px' }}>
        <h1 className="font-game" style={{ fontSize: '28px', fontWeight: 700, color: '#f1f5f9' }}>⚙️ Pengaturan Tampilan</h1>
        <p style={{ color: '#64748b', fontSize: '14px', marginTop: '4px' }}>Ubah tema warna website dan konfigurasi sistem</p>
      </div>

      {loading ? (
        <div style={{ display: 'grid', gap: '16px' }}>
          {Array(4).fill(0).map((_, i) => <div key={i} className="skeleton" style={{ height: 60, borderRadius: 12 }} />)}
        </div>
      ) : (
        <div style={{ display: 'grid', gap: '24px' }}>
          
          {/* Theme Colors */}
          <div className="card" style={{ padding: '24px' }}>
            <h2 style={{ fontSize: '16px', fontWeight: 600, color: '#f1f5f9', marginBottom: '20px' }}>🎨 Tema Warna</h2>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: '16px' }}>
              {Object.entries(theme).map(([key, value]) => (
                <div key={key} style={{ display: 'flex', alignItems: 'center', gap: '12px', padding: '12px', background: 'rgba(255,255,255,0.03)', borderRadius: '10px', border: '1px solid rgba(255,255,255,0.06)' }}>
                  <input
                    type="color"
                    value={value}
                    onChange={e => setTheme(prev => ({ ...prev, [key]: e.target.value }))}
                    style={{ width: 48, height: 48, borderRadius: '10px', border: 'none', cursor: 'pointer', background: 'transparent', padding: 0 }}
                  />
                  <div>
                    <div style={{ fontSize: '14px', fontWeight: 500, color: '#e2e8f0' }}>{THEME_LABELS[key] || key}</div>
                    <div style={{ fontSize: '12px', color: '#64748b', fontFamily: 'monospace' }}>{value}</div>
                  </div>
                </div>
              ))}
            </div>

            {/* Live Preview */}
            <div style={{ marginTop: '20px', padding: '16px', background: theme.bgCard, borderRadius: '12px', border: `1px solid rgba(255,255,255,0.08)` }}>
              <div style={{ fontSize: '12px', color: '#64748b', marginBottom: '12px', fontWeight: 600 }}>LIVE PREVIEW</div>
              <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap', alignItems: 'center' }}>
                <button style={{ padding: '10px 20px', borderRadius: '10px', background: `linear-gradient(135deg, ${theme.accent}, ${theme.accentDark})`, color: '#000', fontWeight: 700, border: 'none', cursor: 'default' }}>Tombol Utama</button>
                <span style={{ padding: '4px 12px', borderRadius: '100px', background: `${theme.success}20`, color: theme.success, fontSize: '13px', fontWeight: 600 }}>● Sukses</span>
                <span style={{ padding: '4px 12px', borderRadius: '100px', background: `${theme.accent}20`, color: theme.accent, fontSize: '13px', fontWeight: 600 }}>● Aksen</span>
                <span style={{ padding: '4px 12px', borderRadius: '100px', background: `${theme.error}20`, color: theme.error, fontSize: '13px', fontWeight: 600 }}>● Error</span>
              </div>
            </div>
          </div>

          {/* OTP Settings */}
          <div className="card" style={{ padding: '24px' }}>
            <h2 style={{ fontSize: '16px', fontWeight: 600, color: '#f1f5f9', marginBottom: '20px' }}>📱 Pengaturan OTP</h2>
            <div style={{ maxWidth: '320px' }}>
              <label className="label">Markup Harga OTP (%)</label>
              <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                <input
                  className="input"
                  type="number"
                  min="0" max="200"
                  value={otpMarkup}
                  onChange={e => setOtpMarkup(e.target.value)}
                />
                <span style={{ color: '#94a3b8', fontSize: '14px' }}>%</span>
              </div>
              <p style={{ fontSize: '12px', color: '#64748b', marginTop: '6px' }}>
                Harga jual = Harga RumahOTP × (1 + {otpMarkup}%). 
                Contoh: Rp 2.000 → Rp {Math.ceil(2000 * (1 + Number(otpMarkup) / 100)).toLocaleString('id-ID')}
              </p>
            </div>
          </div>

          {/* Banner Slider */}
          <div className="card" style={{ padding: '24px' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px' }}>
              <h2 style={{ fontSize: '16px', fontWeight: 600, color: '#f1f5f9' }}>🖼️ Banner Slider (Homepage)</h2>
              <button onClick={() => setBanners([...banners, { image: '', link: '' }])} className="btn btn-secondary" style={{ fontSize: '12px', padding: '6px 12px' }}>
                + Tambah Banner
              </button>
            </div>
            <div style={{ display: 'grid', gap: '16px' }}>
              {banners.map((banner, index) => (
                <div key={index} style={{ display: 'flex', gap: '12px', alignItems: 'flex-start', background: 'rgba(255,255,255,0.03)', padding: '16px', borderRadius: '12px', border: '1px solid rgba(255,255,255,0.05)' }}>
                  <div style={{ flex: 1, display: 'grid', gap: '12px' }}>
                    <div>
                      <label className="label" style={{ fontSize: '12px' }}>URL Gambar / Thumbnail</label>
                      <input className="input" placeholder="https://..." value={banner.image} onChange={e => { const newB = [...banners]; newB[index].image = e.target.value; setBanners(newB) }} />
                    </div>
                    <div>
                      <label className="label" style={{ fontSize: '12px' }}>URL Link (Opsional)</label>
                      <input className="input" placeholder="/games/mobile-legends" value={banner.link} onChange={e => { const newB = [...banners]; newB[index].link = e.target.value; setBanners(newB) }} />
                    </div>
                  </div>
                  {banner.image && (
                    <div style={{ width: '120px', height: '60px', borderRadius: '8px', background: '#111', overflow: 'hidden', border: '1px solid rgba(255,255,255,0.1)' }}>
                      <img src={banner.image} alt="Preview" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                    </div>
                  )}
                  <button onClick={() => setBanners(banners.filter((_, i) => i !== index))} style={{ padding: '8px', background: 'rgba(239,68,68,0.1)', color: '#ef4444', border: 'none', borderRadius: '8px', cursor: 'pointer' }}>
                    ✕
                  </button>
                </div>
              ))}
              {banners.length === 0 && <div style={{ color: '#64748b', fontSize: '14px', textAlign: 'center' }}>Belum ada banner</div>}
            </div>
          </div>

          {/* Popup Info */}
          <div className="card" style={{ padding: '24px' }}>
            <h2 style={{ fontSize: '16px', fontWeight: 600, color: '#f1f5f9', marginBottom: '20px' }}>📢 Popup Info</h2>
            <div style={{ display: 'grid', gap: '16px' }}>
              <label style={{ display: 'flex', alignItems: 'center', gap: '12px', cursor: 'pointer' }}>
                <input type="checkbox" checked={popup.active} onChange={e => setPopup({ ...popup, active: e.target.checked })} style={{ width: 18, height: 18 }} />
                <span style={{ fontSize: '14px', color: '#e2e8f0', fontWeight: 600 }}>Tampilkan Popup saat pengguna membuka website</span>
              </label>

              {popup.active && (
                <div style={{ display: 'grid', gap: '16px', padding: '16px', background: 'rgba(255,255,255,0.02)', borderRadius: '12px', border: '1px solid rgba(255,255,255,0.05)' }}>
                  <div>
                    <label className="label">Judul Popup</label>
                    <input className="input" placeholder="Promo Spesial!" value={popup.title} onChange={e => setPopup({ ...popup, title: e.target.value })} />
                  </div>
                  <div>
                    <label className="label">URL Gambar (Opsional)</label>
                    <input className="input" placeholder="https://..." value={popup.image} onChange={e => setPopup({ ...popup, image: e.target.value })} />
                  </div>
                  <div>
                    <label className="label">Konten Teks (Mendukung HTML)</label>
                    <textarea className="input" placeholder="Selamat datang di AmaneNime Store..." rows={4} value={popup.content} onChange={e => setPopup({ ...popup, content: e.target.value })} />
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* Save Button */}
          <div style={{ display: 'flex', gap: '12px' }}>
            <button onClick={handleSave} disabled={saving} className="btn btn-primary" style={{ padding: '12px 32px' }}>
              {saving ? <><span className="spinner" /> Menyimpan...</> : saved ? '✅ Tersimpan!' : '💾 Simpan Pengaturan'}
            </button>
            <button onClick={handleReset} className="btn btn-secondary" style={{ padding: '12px 20px' }}>
              🔄 Reset Default
            </button>
          </div>
        </div>
      )}
    </div>
  )
}
