import { redirect } from 'next/navigation'
import Link from 'next/link'
import { Bell, History, TrendingUp } from 'lucide-react'
import { getSession, isAdmin } from '@/lib/auth'
import { Recorder } from '@/components/recorder'
import { CaptureList } from '@/components/capture-list'
import { Focus } from '@/components/focus'
import { ChecklistsCard } from '@/components/checklists-card'
import { Overview } from '@/components/overview'
import { SyncButton } from '@/components/sync-button'
import { GlobalSearch } from '@/components/global-search'
import { HealthBadge } from '@/components/health-badge'
import { PushToggle } from '@/components/push-toggle'
import { AccountMenu } from '@/components/account-menu'

export const dynamic = 'force-dynamic'

export default async function DashboardPage() {
  const session = await getSession()
  if (!session) redirect('/login')
  // Host health, the trading dashboard and the manual Apple sync are one
  // account's infrastructure, not household features — don't show the controls
  // to members who would only get bounced back here.
  const admin = await isAdmin(session.userId)

  return (
    <div className="min-h-screen max-w-md mx-auto flex flex-col">
      <header className="safe-top px-5 pb-3 flex items-center gap-2">
        <div className="w-9 h-9 rounded-xl bg-gradient-to-tr from-primary to-violet-400 flex items-center justify-center">
          <Bell className="h-5 w-5 text-primary-foreground" />
        </div>
        <AccountMenu name={session.name} email={session.email} />
        <div className="ml-auto flex items-center gap-1">
          <GlobalSearch />
          <PushToggle vapidPublicKey={process.env.VAPID_PUBLIC_KEY || ''} />
          {admin && <HealthBadge />}
          {admin && (
            <Link href="/trades" className="p-2 rounded-lg hover:bg-muted text-muted-foreground" aria-label="Trade profiles" title="Trade profiles">
              <TrendingUp className="h-4 w-4" />
            </Link>
          )}
          <Link href="/activity" className="p-2 rounded-lg hover:bg-muted text-muted-foreground" aria-label="Activity history" title="Activity history">
            <History className="h-4 w-4" />
          </Link>
          {admin && <SyncButton />}
        </div>
      </header>

      <main className="flex-1 px-4 pb-10 space-y-6">
        {/* Capture */}
        <section className="space-y-2">
          <Recorder />
        </section>

        {/* Focus — app-only daily side list */}
        <Focus />

        {/* Special lists (camping trip, party prep…) — create, work, dismiss */}
        <ChecklistsCard />

        {/* Live overview */}
        <Overview />

        {/* Recent captures */}
        <section className="space-y-2">
          <h2 className="text-sm font-semibold text-muted-foreground px-1">Recent captures</h2>
          <CaptureList />
        </section>
      </main>

      <footer className="safe-bottom" />
    </div>
  )
}
