import { useMemo } from 'react'
import { useNavigate } from '@tanstack/react-router'
import {
  Activity,
  Clock,
  ListTodo,
  Play,
  ScrollText,
  Variable,
} from 'lucide-react'
import {
  CartesianGrid,
  Legend,
  Line,
  LineChart,
  Pie,
  PieChart,
  Cell,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from 'recharts'
import { useSendStats, useStats, useTaskStats } from '@/api/hooks'
import { Card, Loading, PageHeader, SectionLabel } from '@/components/ui'
import { useTheme } from '@/context/ThemeContext'

const PIE_COLORS = ['#3b82f6', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6', '#06b6d4', '#ec4899', '#84cc16']

export default function Dashboard() {
  const navigate = useNavigate()
  const { theme } = useTheme()
  const isDark = theme !== 'light'
  const { data: stats, isLoading: statsLoading } = useStats()
  const { data: sendStatsData } = useSendStats(30)
  const { data: taskStatsData } = useTaskStats(30)

  const sendStats = Array.isArray(sendStatsData) ? sendStatsData : []
  const taskStats = Array.isArray(taskStatsData) ? taskStatsData : []

  const lineData = useMemo(
    () =>
      sendStats.map((item) => ({
        day: item.day?.slice(5) || item.day,
        total: item.total || 0,
        success: item.success || 0,
        failed: item.failed || 0,
      })),
    [sendStats],
  )

  const pieData = useMemo(
    () =>
      taskStats.slice(0, 8).map((item) => ({
        name: item.task_name || item.task_id,
        value: item.count || 0,
      })),
    [taskStats],
  )

  const axisColor = isDark ? '#94a3b8' : '#64748b'
  const gridColor = isDark ? '#334155' : '#e2e8f0'

  if (statsLoading) {
    return <Loading text="加载仪表盘..." />
  }

  const statItems = [
    { key: 'today_execs', label: '今日执行', icon: Play, value: stats?.today_execs || 0, route: '/history' as const },
    { key: 'tasks', label: '任务总数', icon: ListTodo, value: stats?.tasks || 0, route: '/tasks' as const },
    { key: 'envs', label: '环境变量', icon: Variable, value: stats?.envs || 0, route: '/environments' as const },
    { key: 'logs', label: '日志总数', icon: ScrollText, value: stats?.logs || 0, route: '/history' as const },
    { key: 'scheduled', label: '调度注册', icon: Clock, value: stats?.scheduled || 0, route: '/tasks' as const },
    { key: 'running', label: '正在运行', icon: Activity, value: stats?.running || 0, route: '/history' as const, search: { status: 'running' } as const },
  ]

  return (
    <div>
      <PageHeader title="数据仪表" subtitle="Overview" description="系统概览与任务统计" />

      <section className="mb-7">
        <SectionLabel>任务概览</SectionLabel>
        <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
          {statItems.map((item) => (
            <button
              key={item.key}
              type="button"
              className="text-left"
              onClick={() =>
                navigate({
                  to: item.route,
                  search: 'search' in item ? item.search : undefined,
                } as any)
              }
            >
              <Card hoverable className="p-4">
                <div className="mb-3 flex items-center justify-between">
                  <span className="text-[12px] font-medium text-[var(--text-muted)]">{item.label}</span>
                  <div className="flex h-8 w-8 items-center justify-center rounded-md border border-[var(--border)] bg-[var(--bg-tertiary)]">
                    <item.icon size={15} strokeWidth={1.5} className="text-[var(--text-secondary)]" />
                  </div>
                </div>
                <div className="text-[22px] font-bold tracking-tight text-[var(--text-primary)]">{item.value}</div>
              </Card>
            </button>
          ))}
        </div>
      </section>

      <section className="mb-7 grid gap-3 xl:grid-cols-[1.4fr_1fr]">
        <Card className="p-4">
          <SectionLabel>近 30 天执行趋势</SectionLabel>
          <div className="h-[300px] w-full">
            {lineData.length === 0 ? (
              <div className="flex h-full items-center justify-center text-sm text-[var(--text-muted)]">暂无统计</div>
            ) : (
              <ResponsiveContainer width="100%" height="100%">
                <LineChart data={lineData} margin={{ top: 8, right: 12, left: 0, bottom: 0 }}>
                  <CartesianGrid stroke={gridColor} strokeDasharray="3 3" vertical={false} />
                  <XAxis dataKey="day" tick={{ fill: axisColor, fontSize: 11 }} axisLine={false} tickLine={false} />
                  <YAxis tick={{ fill: axisColor, fontSize: 11 }} axisLine={false} tickLine={false} width={36} />
                  <Tooltip
                    contentStyle={{
                      background: isDark ? '#0f172a' : '#fff',
                      border: `1px solid ${gridColor}`,
                      borderRadius: 8,
                      fontSize: 12,
                    }}
                  />
                  <Legend wrapperStyle={{ fontSize: 12 }} />
                  <Line type="monotone" dataKey="total" name="执行总数" stroke="#3b82f6" strokeWidth={2} dot={false} />
                  <Line type="monotone" dataKey="success" name="执行成功" stroke="#10b981" strokeWidth={2} dot={false} />
                  <Line type="monotone" dataKey="failed" name="执行失败" stroke="#ef4444" strokeWidth={2} dot={false} />
                </LineChart>
              </ResponsiveContainer>
            )}
          </div>
        </Card>

        <Card className="p-4">
          <SectionLabel>任务执行占比</SectionLabel>
          <div className="h-[300px] w-full">
            {pieData.length === 0 ? (
              <div className="flex h-full items-center justify-center text-sm text-[var(--text-muted)]">暂无统计</div>
            ) : (
              <ResponsiveContainer width="100%" height="100%">
                <PieChart>
                  <Pie data={pieData} dataKey="value" nameKey="name" innerRadius={55} outerRadius={95} paddingAngle={2}>
                    {pieData.map((_, idx) => (
                      <Cell key={idx} fill={PIE_COLORS[idx % PIE_COLORS.length]} />
                    ))}
                  </Pie>
                  <Tooltip
                    contentStyle={{
                      background: isDark ? '#0f172a' : '#fff',
                      border: `1px solid ${gridColor}`,
                      borderRadius: 8,
                      fontSize: 12,
                    }}
                  />
                  <Legend wrapperStyle={{ fontSize: 11 }} />
                </PieChart>
              </ResponsiveContainer>
            )}
          </div>
        </Card>
      </section>

      <section>
        <Card className="overflow-hidden">
          <div className="border-b border-[var(--border)] px-4 py-3 text-[12px] font-medium uppercase tracking-wide text-[var(--text-muted)]">
            近 30 天任务执行 Top
          </div>
          {taskStats.length === 0 ? (
            <div className="p-8 text-center text-sm text-[var(--text-muted)]">暂无统计</div>
          ) : (
            <div className="divide-y divide-[var(--border)]">
              {taskStats.slice(0, 10).map((item, idx) => (
                <div key={item.task_id || idx} className="flex items-center justify-between px-4 py-3 text-sm">
                  <div className="flex min-w-0 items-center gap-3">
                    <span className="w-5 shrink-0 font-mono text-[11px] text-[var(--text-muted)]">
                      {String(idx + 1).padStart(2, '0')}
                    </span>
                    <span className="truncate pr-3">{item.task_name || item.task_id}</span>
                  </div>
                  <span className="rounded-md border border-[var(--border)] bg-[var(--bg-tertiary)] px-2 py-0.5 font-mono text-[12px] text-[var(--text-secondary)]">
                    {item.count}
                  </span>
                </div>
              ))}
            </div>
          )}
        </Card>
      </section>
    </div>
  )
}
