import { useQuery } from '@tanstack/react-query'
import { getEntities } from '../api/entitiesApi'
import { getLogs } from '../api/logsApi'

export default function DashboardPage() {
  const appVersion = __APP_VERSION__
  const { data: entities = [] } = useQuery({ queryKey: ['entities'], queryFn: getEntities })
  const { data: logs = [] } = useQuery({ queryKey: ['logs'], queryFn: getLogs })

  const activeCount = entities.filter((e) => e.active).length

  return (
    <div className="p-8">
      <h1 className="text-2xl font-bold text-gray-900">Dashboard</h1>
      <p className="mt-2 text-xs text-gray-400">Version {appVersion}</p>
      <div className="mt-6 grid grid-cols-2 gap-4">
        <div className="rounded-lg border bg-white p-4 shadow-sm">
          <p className="text-sm text-gray-500">Active Entities</p>
          <p className="mt-1 text-2xl font-bold">{activeCount} active {activeCount === 1 ? 'entity' : 'entities'}</p>
        </div>
      </div>
      <div className="mt-8">
        <h2 className="text-lg font-semibold text-gray-800">Recent Dispatches</h2>
        <ul className="mt-2 divide-y divide-gray-100 rounded-lg border bg-white shadow-sm">
          {logs.slice(0, 10).map((log) => (
            <li key={log.id} className="px-4 py-3 text-sm">
              <span className="font-medium">{log.emailSubject}</span>
              <span className="ml-2 text-gray-400">{log.entityName}</span>
            </li>
          ))}
          {logs.length === 0 && (
            <li className="px-4 py-3 text-sm text-gray-400">No dispatches yet.</li>
          )}
        </ul>
      </div>
    </div>
  )
}
