import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { api } from '../api/client'
import { useAuth } from '../auth/AuthContext'
import { CopyFlowPipeline } from '../components/CopyFlowPipeline'
import { PlacementFlowPipeline } from '../components/PlacementFlowPipeline'
import { Badge, Card, PageTitle, QuickLinkCard, StatCard } from '../components/ui'

export function DashboardPage() {
  const { member, tenantId, uid } = useAuth()
  const [health, setHealth] = useState('')
  useEffect(() => {
    api
      .get<{ pong: string }>('/api/v1/health')
      .then((d) => setHealth(d.pong))
      .catch(() => setHealth('unreachable'))
  }, [])

  const healthy = health === 'pong'

  return (
    <div>
      <section className="ac-bulletin mb-10">
        <div className="mb-3 flex items-center gap-2">
          <span className="ac-mark" aria-hidden />
          <p className="display-en text-xs font-semibold tracking-[0.16em] text-accent uppercase">Overview</p>
        </div>
        <h1 className="max-w-xl text-balance text-3xl font-bold tracking-tight text-ink md:text-4xl">
          歡迎回來，
          <span className="text-brand">{member?.email?.split('@')[0] || '使用者'}</span>
        </h1>
        <p className="mt-3 max-w-lg text-base leading-relaxed text-ink-secondary">
          兩條平行工作流：拷貝忍者學風格仿寫爆款；找 TA 找痛點、推產品獲客。
        </p>
        <div className="mt-5 flex flex-wrap gap-2">
          <Badge tone="brand">巡檢</Badge>
          <Badge tone="sky">任務</Badge>
          <Badge tone={healthy ? 'success' : 'warning'}>{healthy ? 'API 正常' : 'API 異常'}</Badge>
        </div>
      </section>

      <PageTitle title="系統狀態" subtitle="連線與登入資訊" />

      <div className="mb-10 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
        <StatCard
          label="API 連線"
          value={healthy ? '正常' : health || '…'}
          hint="GET /api/v1/health"
          tone={healthy ? 'brand' : 'sky'}
        />
        <StatCard label="租戶" value={tenantId} hint="Tenant ID" />
        <StatCard label="角色" value={member?.roles?.join(', ') || 'user'} hint={member?.email} />
      </div>

      <PageTitle title="核心工作流" subtitle="拷貝忍者（A）與找 TA（B）並行" />

      <div className="mb-10 grid gap-8 lg:grid-cols-2">
        <CopyFlowPipeline />
        <PlacementFlowPipeline />
      </div>
      <p className="-mt-4 mb-10 text-sm text-ink-secondary">
        <Link to="/brands" className="font-semibold text-brand hover:underline">
          品牌庫
        </Link>
        {'（流程 B）· '}
        <Link to="/personas" className="font-semibold text-brand hover:underline">
          人設庫
        </Link>
        {'（8D 對標與留言語氣）'}
      </p>

      <PageTitle title="快速入口" subtitle="常用功能" />

      <div className="mb-10 grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
        <QuickLinkCard to="/jobs" icon="jobs" title="背景任務" desc="建立、追蹤、取消或重試巡檢任務。" />
        <QuickLinkCard to="/job-schedules" icon="schedule" title="定時排程" desc="以 cron 自動觸發背景任務。" />
        <QuickLinkCard to="/ai" icon="ai" title="AI 助手" desc="串流對話，輔助紀錄與分析。" />
        <QuickLinkCard to="/settings" icon="settings" title="系統設定" desc="管理 key-value 設定項目。" />
        <QuickLinkCard to="/profile" icon="profile" title="個人資料" desc="更新顯示名稱與偏好。" />
        <QuickLinkCard to="/job-templates" icon="template" title="任務模板" desc="查看可用的背景任務模板。" />
      </div>

      <Card>
        <div className="ac-title-bar -mx-1 -mt-1 mb-4">Session</div>
        <dl className="grid gap-3 text-sm sm:grid-cols-2">
          <div className="ac-slot px-4 py-3">
            <dt className="text-xs font-semibold text-ink-secondary">UID</dt>
            <dd className="mt-1 break-all font-mono text-sm text-ink">{member?.uid || uid}</dd>
          </div>
          <div className="ac-slot px-4 py-3">
            <dt className="text-xs font-semibold text-ink-secondary">Email</dt>
            <dd className="mt-1 text-ink">{member?.email}</dd>
          </div>
        </dl>
      </Card>
    </div>
  )
}