import { BarChart3, BrainCircuit, Clock3, Eye, RefreshCcw, Search, Sparkles } from 'lucide-react'
import { startTransition, useCallback, useEffect, useMemo, useState } from 'react'
import { toast } from 'sonner'

import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Skeleton } from '@/components/ui/skeleton'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { adminApi, ApiError } from '@/lib/api'
import { buildFrontendUrl } from '@/lib/frontend-url'
import type { AdminAnalyticsResponse } from '@/lib/types'

function StatCard({
  label,
  value,
  note,
  icon: Icon,
}: {
  label: string
  value: string
  note: string
  icon: typeof Search
}) {
  return (
    <Card className="bg-gradient-to-br from-card via-card to-background/70">
      <CardContent className="flex items-start justify-between pt-6">
        <div>
          <p className="text-xs uppercase tracking-[0.22em] text-muted-foreground">{label}</p>
          <div className="mt-3 text-3xl font-semibold tracking-tight">{value}</div>
          <p className="mt-2 text-sm leading-6 text-muted-foreground">{note}</p>
        </div>
        <div className="flex h-12 w-12 items-center justify-center rounded-2xl border border-primary/20 bg-primary/10 text-primary">
          <Icon className="h-5 w-5" />
        </div>
      </CardContent>
    </Card>
  )
}

function formatEventType(value: string) {
  return value === 'ai_question' ? 'AI 问答' : '站内搜索'
}

function formatSuccess(value: boolean | null) {
  if (value === null) {
    return '未记录'
  }

  return value ? '成功' : '失败'
}

function formatPercent(value: number) {
  return `${Math.round(value)}%`
}

function formatDuration(value: number | null) {
  if (value === null || !Number.isFinite(value) || value <= 0) {
    return '暂无'
  }

  if (value < 1000) {
    return `${Math.round(value)} ms`
  }

  const seconds = value / 1000
  if (seconds < 60) {
    return `${seconds.toFixed(seconds >= 10 ? 0 : 1)} 秒`
  }

  const minutes = Math.floor(seconds / 60)
  const restSeconds = Math.round(seconds % 60)
  return `${minutes} 分 ${restSeconds} 秒`
}

function formatReferrerLabel(value: string) {
  switch (value) {
    case 'chatgpt-search':
      return 'ChatGPT Search'
    case 'perplexity':
      return 'Perplexity'
    case 'copilot-bing':
      return 'Copilot / Bing'
    case 'gemini':
      return 'Gemini'
    case 'claude':
      return 'Claude'
    case 'google':
      return 'Google'
    case 'duckduckgo':
      return 'DuckDuckGo'
    case 'kagi':
      return 'Kagi'
    case 'direct':
      return 'Direct'
    default:
      return value
  }
}

export function AnalyticsPage() {
  const [data, setData] = useState<AdminAnalyticsResponse | null>(null)
  const [loading, setLoading] = useState(true)
  const [refreshing, setRefreshing] = useState(false)

  const loadAnalytics = useCallback(async (showToast = false) => {
    try {
      if (showToast) {
        setRefreshing(true)
      }

      const next = await adminApi.analytics()
      startTransition(() => {
        setData(next)
      })

      if (showToast) {
        toast.success('数据分析已刷新。')
      }
    } catch (error) {
      if (error instanceof ApiError && error.status === 401) {
        return
      }
      toast.error(error instanceof ApiError ? error.message : '无法加载数据分析。')
    } finally {
      setLoading(false)
      setRefreshing(false)
    }
  }, [])

  useEffect(() => {
    void loadAnalytics(false)
  }, [loadAnalytics])

  const maxDailyTotal = useMemo(() => {
    if (!data?.daily_activity.length) {
      return 1
    }

    return Math.max(
      ...data.daily_activity.map((item) => item.searches + item.ai_questions),
      1,
    )
  }, [data])

  if (loading || !data) {
    return (
      <div className="space-y-6">
        <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
          {Array.from({ length: 4 }).map((_, index) => (
            <Skeleton key={index} className="h-44 rounded-3xl" />
          ))}
        </div>
        <div className="grid gap-6 xl:grid-cols-[1.2fr_0.8fr]">
          <Skeleton className="h-[520px] rounded-3xl" />
          <Skeleton className="h-[520px] rounded-3xl" />
        </div>
      </div>
    )
  }

  const statCards = [
    {
      label: '累计搜索',
      value: String(data.overview.total_searches),
      note: `近 7 天 ${data.overview.searches_last_7d} 次，平均命中 ${data.overview.avg_search_results_last_7d.toFixed(1)} 条`,
      icon: Search,
    },
    {
      label: '累计 AI 提问',
      value: String(data.overview.total_ai_questions),
      note: `近 7 天 ${data.overview.ai_questions_last_7d} 次`,
      icon: BrainCircuit,
    },
    {
      label: '24 小时活跃',
      value: String(data.overview.searches_last_24h + data.overview.ai_questions_last_24h),
      note: `搜索 ${data.overview.searches_last_24h} / AI ${data.overview.ai_questions_last_24h}`,
      icon: Clock3,
    },
    {
      label: '近 7 天去重词',
      value: String(
        data.overview.unique_search_terms_last_7d +
          data.overview.unique_ai_questions_last_7d,
      ),
      note: `搜索 ${data.overview.unique_search_terms_last_7d} / AI ${data.overview.unique_ai_questions_last_7d}`,
      icon: BarChart3,
    },
  ]

  const contentStatCards = [
    {
      label: '累计页面访问',
      value: String(data.content_overview.total_page_views),
      note: `近 24 小时 ${data.content_overview.page_views_last_24h} 次，近 7 天 ${data.content_overview.page_views_last_7d} 次`,
      icon: Eye,
    },
    {
      label: '累计完读次数',
      value: String(data.content_overview.total_read_completes),
      note: `近 7 天新增 ${data.content_overview.read_completes_last_7d} 次 read_complete`,
      icon: BarChart3,
    },
    {
      label: '近 7 天平均进度',
      value: formatPercent(data.content_overview.avg_read_progress_last_7d),
      note: '基于 read_progress / read_complete 事件估算内容消费深度',
      icon: Search,
    },
    {
      label: '近 7 天平均阅读时长',
      value: formatDuration(data.content_overview.avg_read_duration_ms_last_7d),
      note: '同一会话在文章页停留并产生阅读进度的平均时长',
      icon: Clock3,
    },
  ]
  const aiDiscoveryShare =
    data.content_overview.page_views_last_7d > 0
      ? (data.ai_discovery_page_views_last_7d / data.content_overview.page_views_last_7d) * 100
      : 0
  const aiDiscoveryTopSource = data.ai_referrers_last_7d[0]

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-4 xl:flex-row xl:items-end xl:justify-between">
        <div className="space-y-3">
          <Badge variant="secondary">数据分析</Badge>
          <div>
            <h2 className="text-3xl font-semibold tracking-tight">前台搜索、阅读行为与 AI 问答洞察</h2>
            <p className="mt-2 max-w-3xl text-sm leading-7 text-muted-foreground">
              这里会同时记录站内搜索、AI 提问、页面访问、阅读进度和来源分析，方便你判断内容需求、热门文章和站点增长质量。
            </p>
          </div>
        </div>

        <div className="flex flex-wrap items-center gap-3">
          <Button variant="outline" asChild>
            <a href={buildFrontendUrl('/ask')} target="_blank" rel="noreferrer">
              <BrainCircuit className="h-4 w-4" />
              打开问答页
            </a>
          </Button>
          <Button
            variant="secondary"
            onClick={() => void loadAnalytics(true)}
            disabled={refreshing}
          >
            <RefreshCcw className="h-4 w-4" />
            {refreshing ? '刷新中...' : '刷新'}
          </Button>
        </div>
      </div>

      <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
        {statCards.map((item) => (
          <StatCard key={item.label} {...item} />
        ))}
      </div>

      <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
        {contentStatCards.map((item) => (
          <StatCard key={item.label} {...item} />
        ))}
      </div>

      <div className="grid gap-4 lg:grid-cols-[1.1fr_0.9fr]">
        <Card className="border-primary/15 bg-gradient-to-br from-primary/5 via-card to-card">
          <CardContent className="flex flex-col gap-5 pt-6 md:flex-row md:items-center md:justify-between">
            <div className="space-y-2">
              <div className="flex items-center gap-2">
                <Badge variant="secondary">AI 来源流量</Badge>
                <span className="text-xs uppercase tracking-[0.2em] text-muted-foreground">
                  最近 7 天
                </span>
              </div>
              <div className="text-3xl font-semibold tracking-tight">
                {data.ai_discovery_page_views_last_7d}
              </div>
              <p className="text-sm leading-6 text-muted-foreground">
                来自 ChatGPT Search、Perplexity、Copilot/Bing、Gemini、Claude
                等 AI / 答案引擎的页面访问。
              </p>
            </div>

            <div className="grid gap-3 sm:min-w-72 sm:grid-cols-2">
              <div className="rounded-2xl border border-border/70 bg-background/75 p-4">
                <p className="text-xs uppercase tracking-[0.2em] text-muted-foreground">
                  占全部 page_view
                </p>
                <p className="mt-3 text-2xl font-semibold">{formatPercent(aiDiscoveryShare)}</p>
                <p className="mt-2 text-sm text-muted-foreground">
                  总 page_view：{data.content_overview.page_views_last_7d}
                </p>
              </div>
              <div className="rounded-2xl border border-border/70 bg-background/75 p-4">
                <p className="text-xs uppercase tracking-[0.2em] text-muted-foreground">
                  最高来源
                </p>
                <p className="mt-3 text-2xl font-semibold">
                  {aiDiscoveryTopSource ? formatReferrerLabel(aiDiscoveryTopSource.referrer) : '暂无'}
                </p>
                <p className="mt-2 text-sm text-muted-foreground">
                  {aiDiscoveryTopSource ? `${aiDiscoveryTopSource.count} 次访问` : '等待来源数据'}
                </p>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Sparkles className="h-4 w-4 text-primary" />
              AI 来源明细
            </CardTitle>
            <CardDescription>
              便于判断 GEO 改造后，哪些 AI 搜索或答案引擎真正把流量带回来了。
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-3">
            {data.ai_referrers_last_7d.length ? (
              data.ai_referrers_last_7d.map((item) => {
                const width = `${
                  Math.max(
                    (item.count / Math.max(data.ai_discovery_page_views_last_7d, 1)) * 100,
                    8,
                  )
                }%`

                return (
                  <div key={item.referrer} className="space-y-2">
                    <div className="flex items-center justify-between gap-3">
                      <span className="font-medium">{formatReferrerLabel(item.referrer)}</span>
                      <Badge variant="outline">{item.count}</Badge>
                    </div>
                    <div className="h-2 overflow-hidden rounded-full bg-secondary">
                      <div
                        className="h-full rounded-full bg-primary transition-[width] duration-300"
                        style={{ width }}
                      />
                    </div>
                  </div>
                )
              })
            ) : (
              <p className="text-sm text-muted-foreground">
                最近 7 天还没有识别到 AI 搜索来源流量。
              </p>
            )}
          </CardContent>
        </Card>
      </div>

      <div className="grid gap-6 xl:grid-cols-[1.2fr_0.8fr]">
        <div className="space-y-6">
          <Card>
            <CardHeader className="flex flex-row items-start justify-between gap-4">
              <div>
                <CardTitle>最近记录</CardTitle>
                <CardDescription>
                  最近一批真实发生的搜索和 AI 问答请求。
                </CardDescription>
              </div>
              <Badge variant="outline">{data.recent_events.length} 条</Badge>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>类型</TableHead>
                    <TableHead>内容</TableHead>
                    <TableHead>结果</TableHead>
                    <TableHead>时间</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {data.recent_events.map((event) => (
                    <TableRow key={event.id}>
                      <TableCell>
                        <div className="space-y-1">
                          <Badge variant={event.event_type === 'ai_question' ? 'secondary' : 'outline'}>
                            {formatEventType(event.event_type)}
                          </Badge>
                          {event.response_mode ? (
                            <p className="text-xs uppercase tracking-[0.16em] text-muted-foreground">
                              {event.response_mode}
                            </p>
                          ) : null}
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="space-y-1">
                          <p className="line-clamp-2 font-medium">{event.query}</p>
                          <p className="text-xs text-muted-foreground">
                            {event.provider ? `${event.provider}` : '未记录渠道'}
                            {event.chat_model ? ` / ${event.chat_model}` : ''}
                          </p>
                        </div>
                      </TableCell>
                      <TableCell className="text-sm text-muted-foreground">
                        <div>{formatSuccess(event.success)}</div>
                        <div className="mt-1">
                          {event.result_count !== null ? `${event.result_count} 条/源` : '无'}
                        </div>
                        {event.latency_ms !== null ? (
                          <div className="mt-1 text-xs uppercase tracking-[0.16em]">
                            {event.latency_ms} ms
                          </div>
                        ) : null}
                      </TableCell>
                      <TableCell className="text-muted-foreground">{event.created_at}</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
              </CardContent>
            </Card>

            <Card>
              <CardHeader className="flex flex-row items-start justify-between gap-4">
                <div>
                  <CardTitle>热门文章榜</CardTitle>
                  <CardDescription>
                    基于 page_view / read_complete 事件聚合的内容表现排行。
                  </CardDescription>
                </div>
                <Badge variant="outline">{data.popular_posts.length} 篇</Badge>
              </CardHeader>
              <CardContent>
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>文章</TableHead>
                      <TableHead>浏览</TableHead>
                      <TableHead>完读</TableHead>
                      <TableHead>平均进度</TableHead>
                      <TableHead>平均时长</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {data.popular_posts.length ? (
                      data.popular_posts.map((post) => (
                        <TableRow key={post.slug}>
                          <TableCell>
                            <div className="space-y-1">
                              <a
                                href={buildFrontendUrl(`/articles/${post.slug}`)}
                                target="_blank"
                                rel="noreferrer"
                                className="font-medium text-primary hover:underline"
                              >
                                {post.title}
                              </a>
                              <p className="font-mono text-xs text-muted-foreground">
                                {post.slug}
                              </p>
                            </div>
                          </TableCell>
                          <TableCell>{post.page_views}</TableCell>
                          <TableCell>{post.read_completes}</TableCell>
                          <TableCell>{formatPercent(post.avg_progress_percent)}</TableCell>
                          <TableCell>{formatDuration(post.avg_duration_ms)}</TableCell>
                        </TableRow>
                      ))
                    ) : (
                      <TableRow>
                        <TableCell colSpan={5} className="text-sm text-muted-foreground">
                          还没有足够的内容访问数据。
                        </TableCell>
                      </TableRow>
                    )}
                  </TableBody>
                </Table>
              </CardContent>
            </Card>

            <div className="grid gap-6 lg:grid-cols-2">
              <Card>
              <CardHeader className="flex flex-row items-start justify-between gap-4">
                <div>
                  <CardTitle>热门搜索词</CardTitle>
                  <CardDescription>
                    近 7 天最常被搜索的关键词。
                  </CardDescription>
                </div>
                <Badge variant="outline">{data.top_search_terms.length} 个</Badge>
              </CardHeader>
              <CardContent className="space-y-3">
                {data.top_search_terms.length ? (
                  data.top_search_terms.map((item) => (
                    <div
                      key={`${item.query}-${item.last_seen_at}`}
                      className="rounded-2xl border border-border/70 bg-background/70 p-4"
                    >
                      <div className="flex items-start justify-between gap-3">
                        <p className="font-medium">{item.query}</p>
                        <Badge variant="secondary">{item.count}</Badge>
                      </div>
                      <p className="mt-2 text-sm text-muted-foreground">
                        最近一次：{item.last_seen_at}
                      </p>
                    </div>
                  ))
                ) : (
                  <p className="text-sm text-muted-foreground">最近 7 天还没有站内搜索记录。</p>
                )}
              </CardContent>
            </Card>

            <Card>
              <CardHeader className="flex flex-row items-start justify-between gap-4">
                <div>
                  <CardTitle>热门 AI 问题</CardTitle>
                  <CardDescription>
                    近 7 天重复出现最多的提问。
                  </CardDescription>
                </div>
                <Badge variant="outline">{data.top_ai_questions.length} 个</Badge>
              </CardHeader>
              <CardContent className="space-y-3">
                {data.top_ai_questions.length ? (
                  data.top_ai_questions.map((item) => (
                    <div
                      key={`${item.query}-${item.last_seen_at}`}
                      className="rounded-2xl border border-border/70 bg-background/70 p-4"
                    >
                      <div className="flex items-start justify-between gap-3">
                        <p className="font-medium">{item.query}</p>
                        <Badge variant="secondary">{item.count}</Badge>
                      </div>
                      <p className="mt-2 text-sm text-muted-foreground">
                        最近一次：{item.last_seen_at}
                      </p>
                    </div>
                  ))
                ) : (
                  <p className="text-sm text-muted-foreground">最近 7 天还没有 AI 提问记录。</p>
                )}
              </CardContent>
            </Card>
          </div>
        </div>

        <div className="space-y-6 xl:sticky xl:top-28 xl:self-start">
          <Card>
            <CardHeader>
              <CardTitle>内容消费概览</CardTitle>
              <CardDescription>
                浏览量、完读率和阅读时长的快速摘要。
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="rounded-2xl border border-border/70 bg-background/70 p-4">
                <p className="text-xs uppercase tracking-[0.2em] text-muted-foreground">
                  24 小时页面访问
                </p>
                <p className="mt-3 text-3xl font-semibold">
                  {data.content_overview.page_views_last_24h}
                </p>
              </div>
              <div className="rounded-2xl border border-border/70 bg-background/70 p-4">
                <p className="text-xs uppercase tracking-[0.2em] text-muted-foreground">
                  近 7 天完读
                </p>
                <p className="mt-3 text-3xl font-semibold">
                  {data.content_overview.read_completes_last_7d}
                </p>
              </div>
              <div className="rounded-2xl border border-border/70 bg-background/70 p-4">
                <p className="text-xs uppercase tracking-[0.2em] text-muted-foreground">
                  近 7 天平均阅读进度
                </p>
                <p className="mt-3 text-3xl font-semibold">
                  {formatPercent(data.content_overview.avg_read_progress_last_7d)}
                </p>
                <p className="mt-2 text-sm text-muted-foreground">统计范围：最近 7 天</p>
              </div>
              <div className="rounded-2xl border border-border/70 bg-background/70 p-4">
                <p className="text-xs uppercase tracking-[0.2em] text-muted-foreground">
                  近 7 天平均阅读时长
                </p>
                <p className="mt-3 text-3xl font-semibold">
                  {formatDuration(data.content_overview.avg_read_duration_ms_last_7d)}
                </p>
                <p className="mt-2 text-sm text-muted-foreground">同一会话聚合后的阅读耗时</p>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>来源分析</CardTitle>
              <CardDescription>
                近 7 天触发 page_view 的主要 referrer host。
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-3">
              {data.top_referrers.length ? (
                data.top_referrers.map((item) => (
                  <div
                    key={item.referrer}
                    className="flex items-center justify-between rounded-2xl border border-border/70 bg-background/70 px-4 py-3"
                  >
                    <span className="line-clamp-1 font-medium">{formatReferrerLabel(item.referrer)}</span>
                    <Badge variant="outline">{item.count}</Badge>
                  </div>
                ))
              ) : (
                <p className="text-sm text-muted-foreground">最近 7 天还没有来源分析数据。</p>
              )}
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>模型渠道分布</CardTitle>
              <CardDescription>
                最近 7 天 AI 请求实际使用的 provider 厂商。
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-3">
              {data.providers_last_7d.length ? (
                data.providers_last_7d.map((item) => (
                  <div
                    key={item.provider}
                    className="flex items-center justify-between rounded-2xl border border-border/70 bg-background/70 px-4 py-3"
                  >
                    <span className="font-medium">{item.provider}</span>
                    <Badge variant="outline">{item.count}</Badge>
                  </div>
                ))
              ) : (
                <p className="text-sm text-muted-foreground">最近 7 天还没有 AI 渠道数据。</p>
              )}
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>7 天走势</CardTitle>
              <CardDescription>
                搜索与 AI 问答的日维度活动量。
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              {data.daily_activity.map((item) => {
                const total = item.searches + item.ai_questions
                const width = `${Math.max((total / maxDailyTotal) * 100, total > 0 ? 12 : 0)}%`

                return (
                  <div key={item.date} className="space-y-2">
                    <div className="flex items-center justify-between gap-3 text-sm">
                      <span className="font-medium">{item.date}</span>
                      <span className="text-muted-foreground">
                        搜索 {item.searches} / AI {item.ai_questions}
                      </span>
                    </div>
                    <div className="h-2 overflow-hidden rounded-full bg-secondary">
                      <div
                        className="h-full rounded-full bg-primary transition-[width] duration-300"
                        style={{ width }}
                      />
                    </div>
                  </div>
                )
              })}
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  )
}
