'use client'

import { useState, useEffect } from 'react'
import { formatRupiah, getOrderStatusConfig, formatDate } from '@/lib/utils'
import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer } from 'recharts'

export default function AdminDashboard() {
  const [data, setData] = useState<any>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    fetch('/api/admin/stats')
      .then(r => r.json())
      .then(d => { setData(d); setLoading(false) })
      .catch(() => setLoading(false))
  }, [])

  if (loading) return <div className="spinner" style={{ margin: '100px auto', display: 'block' }} />
  if (!data?.stats) return <div>Gagal memuat data</div>

  const stats = [
    { label: 'Total Pendapatan', value: formatRupiah(data.stats.totalRevenue), icon: '💰', color: '#10b981' },
    { label: 'Pendapatan Hari Ini', value: formatRupiah(data.stats.todayRevenue), icon: '📈', color: '#f59e0b' },
    { label: 'Total Pesanan', value: data.stats.totalOrders, icon: '📦', color: '#3b82f6' },
    { label: 'Pesanan Pending', value: data.stats.pendingOrders, icon: '⏳', color: '#8b5cf6' },
    { label: 'Total Pengguna', value: data.stats.totalUsers, icon: '👥', color: '#ec4899' },
  ]

  return (
    <div>
      <div style={{ marginBottom: '32px' }}>
        <h1 className="font-game" style={{ fontSize: '32px', fontWeight: 700, color: '#f1f5f9', marginBottom: '8px' }}>
          Overview Dashboard
        </h1>
        <p style={{ color: '#64748b' }}>Ringkasan performa platform AmaneNime Store</p>
      </div>

      {/* Stats Grid */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: '20px', marginBottom: '32px' }}>
        {stats.map(s => (
          <div key={s.label} className="card" style={{ padding: '24px', display: 'flex', alignItems: 'center', gap: '16px' }}>
            <div style={{ width: 48, height: 48, borderRadius: '12px', background: `${s.color}15`, color: s.color, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '24px' }}>
              {s.icon}
            </div>
            <div>
              <div style={{ fontSize: '13px', color: '#94a3b8', marginBottom: '4px' }}>{s.label}</div>
              <div style={{ fontSize: '20px', fontWeight: 700, color: '#f1f5f9' }}>{s.value}</div>
            </div>
          </div>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: '24px' }}>
        {/* Chart */}
        <div className="card" style={{ padding: '24px' }}>
          <h2 style={{ fontSize: '16px', fontWeight: 600, marginBottom: '24px' }}>Pendapatan 7 Hari Terakhir</h2>
          <div style={{ height: 300 }}>
            <ResponsiveContainer width="100%" height="100%">
              <BarChart data={data.dailyRevenue}>
                <XAxis dataKey="date" stroke="#64748b" fontSize={12} tickLine={false} axisLine={false} />
                <YAxis stroke="#64748b" fontSize={12} tickLine={false} axisLine={false} tickFormatter={(val) => `Rp${val/1000}k`} />
                <Tooltip 
                  cursor={{ fill: 'rgba(255,255,255,0.05)' }}
                  contentStyle={{ background: '#16161f', border: '1px solid rgba(255,255,255,0.1)', borderRadius: '8px' }}
                  formatter={(val: number) => formatRupiah(val)}
                />
                <Bar dataKey="revenue" fill="#f59e0b" radius={[4, 4, 0, 0]} />
              </BarChart>
            </ResponsiveContainer>
          </div>
        </div>

        {/* Recent Orders */}
        <div className="card" style={{ padding: '24px' }}>
          <h2 style={{ fontSize: '16px', fontWeight: 600, marginBottom: '24px' }}>Pesanan Terbaru</h2>
          <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
            {data.recentOrders?.map((order: any) => {
              const statusConfig = getOrderStatusConfig(order.status)
              return (
                <div key={order.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingBottom: '16px', borderBottom: '1px solid rgba(255,255,255,0.05)' }}>
                  <div>
                    <div style={{ fontSize: '14px', fontWeight: 500, color: '#e2e8f0', marginBottom: '4px' }}>
                      {order.vipProduct?.productName || order.digitalProduct?.name || order.smmProduct?.name || '(Produk dihapus)'}
                    </div>
                    <div style={{ fontSize: '12px', color: '#64748b' }}>
                      {order.user?.name} • {formatDate(order.createdAt)}
                    </div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div style={{ fontSize: '14px', fontWeight: 600, color: '#f59e0b', marginBottom: '4px' }}>{formatRupiah(order.price)}</div>
                    <span className="badge" style={{ background: statusConfig.bg, color: statusConfig.color, fontSize: '10px' }}>{statusConfig.label}</span>
                  </div>
                </div>
              )
            })}
          </div>
        </div>
      </div>
    </div>
  )
}
