import { useQuery } from '@tanstack/react-query'
import { apiClient } from '../../core/api/api-client'

const fetchDashboardStats = async () => {
  const res = await apiClient.get('/internal/sessions/dashboard/stats')
  return res.data.data
}

export default function DashboardPage() {
  const { data, isLoading } = useQuery({
    queryKey: ['dashboard-stats'],
    queryFn: fetchDashboardStats,
    refetchInterval: 10000,
  })

  if (isLoading) return <div>Loading...</div>

  return (
    <div>
      <h1>Dashboard</h1>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 32 }}>
        <div style={{ padding: 24, border: '1px solid #eee', borderRadius: 8 }}>
          <div style={{ fontSize: 32, fontWeight: 'bold', color: '#2563eb' }}>{data?.active_chats ?? 0}</div>
          <div style={{ color: '#666' }}>Chat Aktif</div>
        </div>
        <div style={{ padding: 24, border: '1px solid #eee', borderRadius: 8 }}>
          <div style={{ fontSize: 32, fontWeight: 'bold', color: '#16a34a' }}>{data?.online_mitras ?? 0}</div>
          <div style={{ color: '#666' }}>Mitra Online</div>
        </div>
        <div style={{ padding: 24, border: '1px solid #eee', borderRadius: 8 }}>
          <div style={{ fontSize: 32, fontWeight: 'bold', color: '#f59e0b' }}>{data?.pending_requests ?? 0}</div>
          <div style={{ color: '#666' }}>Request Pending</div>
        </div>
        <div style={{ padding: 24, border: '1px solid #eee', borderRadius: 8, background: '#FFF8DF' }}>
          <div style={{ fontSize: 32, fontWeight: 'bold', color: '#B88900' }}>
            {data?.sensitive?.last_30d_sensitive ?? 0}
            <span style={{ fontSize: 16, color: '#666', marginLeft: 8 }}>
              ({data?.sensitive?.last_30d_percent ?? 0}%)
            </span>
          </div>
          <div style={{ color: '#666' }}>Sesi Sensitif (30 hari)</div>
          <div style={{ color: '#888', fontSize: 12, marginTop: 4 }}>
            Total semua waktu: {data?.sensitive?.total ?? 0}
          </div>
        </div>
      </div>

      <h2>Customer per Mitra</h2>
      {data?.customers_per_mitra?.length > 0 ? (
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={{ textAlign: 'left', padding: 8, borderBottom: '1px solid #eee' }}>Mitra</th>
              <th style={{ textAlign: 'left', padding: 8, borderBottom: '1px solid #eee' }}>Sesi Aktif</th>
            </tr>
          </thead>
          <tbody>
            {data.customers_per_mitra.map((m) => (
              <tr key={m.id}>
                <td style={{ padding: 8 }}>{m.display_name}</td>
                <td style={{ padding: 8 }}>{m.active_session_count}</td>
              </tr>
            ))}
          </tbody>
        </table>
      ) : (
        <p style={{ color: '#666' }}>Tidak ada mitra online.</p>
      )}
    </div>
  )
}
