import { useCallback, useEffect, useMemo, 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,
  ProgressBar,
  QuickLinkCard,
  StatCard,
  StatusBadge,
} from '../components/ui'
import { isActiveJobStatus, isTerminalJobStatus, jobStatusBadgeClass, jobStatusLabel } from '../lib/jobStatus'
import { jobTemplateLabel } from '../lib/jobTemplate'
import { filterManagedSchedules } from '../lib/scheduleCatalog'
import type { JobData, JobScheduleData, Pagination } from '../types/api'

type DashboardStats = {
  activeJobs: number
  scheduleTotal: number
  enabledSchedules: number
}

export function DashboardPage() {
  const { member } = useAuth()
  const [jobs, setJobs] = useState<JobData[]>([])
  const [stats, setStats] = useState<DashboardStats | null>(null)
  const [statsLoading, setStatsLoading] = useState(true)

  const loadStats = useCallback(async () => {
    try {
      const [jobsRes, schedulesRes] = await Promise.all([
        api.get<{ list: JobData[]; pagination: Pagination }>('/api/v1/jobs', {
          auth: true,
          query: { page: 1, pageSize: 50 },
        }),
        api.get<{ list: JobScheduleData[]; pagination: Pagination }>('/api/v1/job/schedules', {
          auth: true,
          query: { page: 1, pageSize: 100 },
        }),
      ])
      const list = jobsRes.list ?? []
      const activeJobs = list.filter((j) => isActiveJobStatus(j.status))
      const managedSchedules = filterManagedSchedules(schedulesRes.list ?? [])
      setJobs(activeJobs)
      setStats({
        activeJobs: activeJobs.length,
        scheduleTotal: managedSchedules.length,
        enabledSchedules: managedSchedules.filter((s) => s.enabled).length,
      })
    } catch {
      setJobs([])
      setStats(null)
    } finally {
      setStatsLoading(false)
    }
  }, [])

  useEffect(() => {
    loadStats().catch(() => undefined)
  }, [loadStats])

  useEffect(() => {
    const hasActive = jobs.some((j) => !isTerminalJobStatus(j.status))
    if (!hasActive) return
    const timer = window.setInterval(() => loadStats().catch(() => undefined), 3000)
    return () => window.clearInterval(timer)
  }, [jobs, loadStats])

  const displayName =
    member?.display_name?.trim() || member?.email?.split('@')[0] || '島民'
  const activeJobs = useMemo(() => jobs.slice(0, 5), [jobs])

  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">{displayName}</span>
        </h1>
        {stats && stats.activeJobs > 0 ? (
          <div className="mt-5 flex flex-wrap gap-2">
            <Badge tone="sky">{stats.activeJobs} 個任務進行中</Badge>
          </div>
        ) : null}
      </section>

      {stats ? (
        <>
          <PageTitle title="概況" />
          <div className="mb-10 grid gap-4 sm:grid-cols-2">
            <StatCard
              label="進行中任務"
              value={stats.activeJobs}
              hint={stats.activeJobs > 0 ? '背景任務執行或排隊中' : '目前沒有進行中的任務'}
              tone={stats.activeJobs > 0 ? 'brand' : 'default'}
            />
            <StatCard
              label="定時排程"
              value={stats.enabledSchedules > 0 ? `${stats.enabledSchedules} 啟用` : stats.scheduleTotal}
              hint={
                stats.scheduleTotal > 0
                  ? stats.enabledSchedules > 0
                    ? `共 ${stats.scheduleTotal} 筆海巡排程`
                    : `共 ${stats.scheduleTotal} 筆，尚未啟用`
                  : '尚未建立海巡排程'
              }
              tone={stats.enabledSchedules > 0 ? 'sky' : 'default'}
            />
          </div>
        </>
      ) : statsLoading ? (
        <p className="mb-10 text-sm text-muted">載入概況中…</p>
      ) : null}

      {activeJobs.length > 0 ? (
        <section className="mb-10">
          <PageTitle title="進行中任務" />
          <Card className="divide-y divide-line p-0">
            <ul>
              {activeJobs.map((job) => {
                const summary = job.progress?.summary?.trim()
                return (
                  <li key={job.id}>
                    <Link
                      to={`/jobs/${job.id}`}
                      className="flex flex-wrap items-center justify-between gap-3 px-5 py-4 transition hover:bg-surface-muted"
                    >
                      <div className="min-w-0 flex-1">
                        <p className="truncate font-semibold text-ink">
                          {jobTemplateLabel(job.template_type)}
                        </p>
                        {summary ? (
                          <p className="mt-0.5 truncate text-sm text-muted">{summary}</p>
                        ) : null}
                        <div className="mt-2 max-w-xs">
                          <ProgressBar value={job.progress?.percentage ?? 0} />
                        </div>
                      </div>
                      <StatusBadge className={jobStatusBadgeClass(job.status)}>
                        {jobStatusLabel(job.status)}
                      </StatusBadge>
                    </Link>
                  </li>
                )
              })}
            </ul>
            <div className="px-5 py-3 text-right">
              <Link to="/jobs" className="text-sm font-semibold text-brand hover:underline">
                查看全部任務 →
              </Link>
            </div>
          </Card>
        </section>
      ) : null}

      <PageTitle title="核心工作流" />

      <div className="mb-10 grid items-stretch gap-8 lg:grid-cols-2">
        <CopyFlowPipeline />
        <PlacementFlowPipeline />
      </div>

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

      <div className="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="/settings" icon="settings" title="系統設定" desc="連線、AI 與帳號偏好。" />
      </div>
    </div>
  )
}