"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import {
  MetricCard,
  StageProgress,
  AgentStatusCard,
} from "@/components/business";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import {
  Sparkles,
  Search,
  FileText,
  Send,
  BarChart3,
  Target,
  Plus,
  ArrowRight,
  Zap,
  TrendingUp,
  Quote,
  AlertCircle,
} from "lucide-react";
import { lifecycleApi, type GeoProject, type LifecycleStats } from "@/lib/api";

/* ─── Helpers ─────────────────────────────────────────────────────────────────*/

const STAGE_CONFIG = [
  { id: "diagnosis", label: "诊断分析" },
  { id: "strategy", label: "策略制定" },
  { id: "content", label: "内容生产" },
  { id: "publishing", label: "分发执行" },
  { id: "monitoring", label: "监测优化" },
];

const MOCK_AGENTS = [
  {
    name: "内容生成Agent",
    description: "自动化内容生产",
    status: "busy" as const,
    lastActiveAt: "2分钟前",
    completedCount: 156,
  },
  {
    name: "引用监测Agent",
    description: "AI平台引用追踪",
    status: "online" as const,
    lastActiveAt: "刚刚",
    completedCount: 3420,
  },
  {
    name: "SEO诊断Agent",
    description: "搜索引擎优化分析",
    status: "offline" as const,
    lastActiveAt: "3小时前",
    completedCount: 89,
  },
];

function buildStages(currentStage: GeoProject["current_stage"]) {
  const currentIndex = STAGE_CONFIG.findIndex((s) => s.id === currentStage);
  return STAGE_CONFIG.map((stage, idx) => {
    let status: "completed" | "active" | "pending" | "error" = "pending";
    if (idx < currentIndex) status = "completed";
    else if (idx === currentIndex) status = "active";
    return { id: stage.id, label: stage.label, status };
  });
}

function getRecommendation(stage: GeoProject["current_stage"]) {
  const map: Record<
    GeoProject["current_stage"],
    { title: string; description: string; icon: React.ReactNode; href: string }
  > = {
    diagnosis: {
      title: "开始诊断分析",
      description: "诊断您品牌在AI搜索中的可见性现状",
      icon: <Search className="h-5 w-5" />,
      href: "/dashboard/diagnosis",
    },
    strategy: {
      title: "生成优化策略",
      description: "基于诊断结果制定GEO+SEO优化方案",
      icon: <Target className="h-5 w-5" />,
      href: "/dashboard/strategy",
    },
    content: {
      title: "创建新内容",
      description: "使用AI Agent批量生成优化内容",
      icon: <FileText className="h-5 w-5" />,
      href: "/dashboard/content",
    },
    publishing: {
      title: "配置分发渠道",
      description: "将内容分发到各大AI平台和搜索引擎",
      icon: <Send className="h-5 w-5" />,
      href: "/dashboard/publishing",
    },
    monitoring: {
      title: "查看监测报告",
      description: "分析内容分发后的引用和排名数据",
      icon: <BarChart3 className="h-5 w-5" />,
      href: "/dashboard/monitoring",
    },
  };
  return map[stage];
}

/* ─── Component ───────────────────────────────────────────────────────────────*/

export default function DashboardPage() {
  const router = useRouter();
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [projects, setProjects] = useState<GeoProject[]>([]);
  const [stats, setStats] = useState<LifecycleStats | null>(null);

  useEffect(() => {
    async function fetchData() {
      try {
        setLoading(true);
        setError(null);
        const [projectList, statsData] = await Promise.all([
          lifecycleApi.listProjects(),
          lifecycleApi.getStats(),
        ]);
        setProjects(projectList ?? []);
        setStats(statsData);
      } catch (err) {
        console.error("Dashboard fetch error:", err);
        setError(err instanceof Error ? err.message : "数据加载失败");
      } finally {
        setLoading(false);
      }
    }
    fetchData();
  }, []);

  /* ─── Loading State ────────────────────────────────────────────────────────*/
  if (loading) {
    return (
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <div className="space-y-1">
            <Skeleton className="h-8 w-56" />
            <Skeleton className="h-4 w-40" />
          </div>
          <Skeleton className="h-9 w-28" />
        </div>
        <Skeleton className="h-20 w-full rounded-xl" />
        <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-4">
          {Array.from({ length: 4 }).map((_, i) => (
            <Skeleton key={i} className="h-36 w-full rounded-xl" />
          ))}
        </div>
        <div className="grid gap-6 md:grid-cols-2">
          <Skeleton className="h-48 w-full rounded-xl" />
          <Skeleton className="h-48 w-full rounded-xl" />
        </div>
      </div>
    );
  }

  /* ─── Error State ──────────────────────────────────────────────────────────*/
  if (error) {
    return (
      <div className="space-y-6">
        <div>
          <h1 className="text-2xl font-bold tracking-tight text-geo-text-primary">
            AI Visibility Dashboard
          </h1>
        </div>
        <div className="flex flex-col items-center justify-center rounded-xl border border-red-200 bg-red-50 py-16 text-center">
          <AlertCircle className="h-10 w-10 text-red-400 mb-3" />
          <p className="text-sm font-medium text-red-600">数据加载失败</p>
          <p className="text-xs text-red-500 mt-1">{error}</p>
          <Button
            variant="outline"
            size="sm"
            className="mt-4"
            onClick={() => window.location.reload()}
          >
            重试
          </Button>
        </div>
      </div>
    );
  }

  /* ─── Empty State ──────────────────────────────────────────────────────────*/
  if (projects.length === 0) {
    return (
      <div className="space-y-6">
        <div>
          <h1 className="text-2xl font-bold tracking-tight text-geo-text-primary">
            AI Visibility Dashboard
          </h1>
          <p className="text-sm text-geo-text-secondary">
            GEO和SEO是AI营销时代的共生体
          </p>
        </div>
        <div className="flex flex-col items-center justify-center rounded-xl border border-geo-border bg-white py-20 text-center shadow-geo-card">
          <div className="mb-6 flex h-16 w-16 items-center justify-center rounded-full bg-primary/10">
            <Sparkles className="h-8 w-8 text-primary" />
          </div>
          <h3 className="mb-2 text-xl font-semibold text-geo-text-primary">
            开始优化您的AI可见性
          </h3>
          <p className="mb-8 max-w-sm text-sm text-geo-text-secondary">
            创建第一个项目，系统将自动引导您完成从诊断分析到监测优化的全生命周期管理。
          </p>
          <Link href="/dashboard/lifecycle/new">
            <Button>
              <Plus className="mr-2 h-4 w-4" />
              创建项目
            </Button>
          </Link>
        </div>
      </div>
    );
  }

  /* ─── Active Dashboard ─────────────────────────────────────────────────────*/
  const project = projects[0];
  const stages = buildStages(project.current_stage);
  const recommendation = getRecommendation(project.current_stage);

  const citationRate = stats?.avg_ai_citation_rate != null
    ? `${(stats.avg_ai_citation_rate * 100).toFixed(1)}%`
    : "—";

  return (
    <div className="space-y-6">
      {/* 1. Top Bar */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-bold tracking-tight text-geo-text-primary">
            AI Visibility Dashboard
          </h1>
          <p className="text-sm text-geo-text-secondary">
            {project.brand_name} — {project.name}
          </p>
        </div>
        <Link href="/dashboard/lifecycle/new">
          <Button variant="outline" className="shrink-0">
            <Plus className="mr-2 h-4 w-4" />
            创建项目
          </Button>
        </Link>
      </div>

      {/* 2. Stage Progress */}
      <Card className="rounded-xl shadow-geo-card">
        <CardHeader className="pb-3">
          <div className="flex items-center justify-between">
            <p className="text-xs font-semibold uppercase tracking-widest text-geo-text-muted">
              生命周期进度
            </p>
            <Badge variant="secondary" className="text-xs">
              当前阶段：
              {STAGE_CONFIG.find((s) => s.id === project.current_stage)?.label}
            </Badge>
          </div>
        </CardHeader>
        <CardContent className="pt-0">
          <StageProgress
            stages={stages}
            onStageClick={(stage) => {
              router.push(`/dashboard/${stage.id}`);
            }}
          />
        </CardContent>
      </Card>

      {/* 3. Metrics Grid */}
      <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-4">
        <MetricCard
          label="活跃项目数"
          value={stats?.active_projects ?? 0}
          trend="neutral"
          trendLabel={`共 ${stats?.total_projects ?? 0} 个项目`}
          icon={<TrendingUp className="h-4 w-4" />}
          size="default"
        />
        <MetricCard
          label="内容产出统计"
          value={stats?.contents_produced ?? 0}
          trend="up"
          trendLabel="全部内容"
          icon={<FileText className="h-4 w-4" />}
          size="default"
        />
        <MetricCard
          label="AI引用率"
          value={citationRate}
          trend={stats?.avg_ai_citation_rate ? "up" : "neutral"}
          trendLabel="平均引用率"
          icon={<Quote className="h-4 w-4" />}
          size="default"
        />
        <MetricCard
          label="已完成项目"
          value={stats?.completed_projects ?? 0}
          trend="neutral"
          trendLabel={`活跃 ${stats?.active_projects ?? 0} 个`}
          icon={<AlertCircle className="h-4 w-4" />}
          size="default"
        />
      </div>

      {/* 4. Smart Recommendations + 5. Agent Activity */}
      <div className="grid gap-6 md:grid-cols-2">
        {/* Smart Recommendation */}
        <Card className="rounded-xl shadow-geo-card">
          <CardHeader className="pb-3">
            <p className="text-xs font-semibold uppercase tracking-widest text-geo-text-muted">
              推荐下一步
            </p>
          </CardHeader>
          <CardContent className="pt-0">
            <div className="flex items-start gap-4 rounded-lg border border-geo-border bg-geo-bg p-4 transition-colors hover:bg-white">
              <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary">
                {recommendation.icon}
              </div>
              <div className="flex-1 min-w-0">
                <p className="text-sm font-semibold text-geo-text-primary">
                  {recommendation.title}
                </p>
                <p className="text-xs text-geo-text-secondary mt-0.5">
                  {recommendation.description}
                </p>
              </div>
              <Button
                size="sm"
                className="shrink-0"
                onClick={() => router.push(recommendation.href)}
              >
                执行
                <ArrowRight className="ml-1 h-3.5 w-3.5" />
              </Button>
            </div>

            <div className="mt-3 grid grid-cols-2 gap-3">
              <Button
                variant="outline"
                size="sm"
                className="justify-start"
                onClick={() => router.push("/dashboard/agents")}
              >
                <Zap className="mr-2 h-3.5 w-3.5" />
                管理Agent
              </Button>
              <Button
                variant="outline"
                size="sm"
                className="justify-start"
                onClick={() => router.push("/dashboard/lifecycle")}
              >
                <BarChart3 className="mr-2 h-3.5 w-3.5" />
                项目详情
              </Button>
            </div>
          </CardContent>
        </Card>

        {/* Agent Activity Summary */}
        <Card className="rounded-xl shadow-geo-card">
          <CardHeader className="pb-3">
            <div className="flex items-center justify-between">
              <p className="text-xs font-semibold uppercase tracking-widest text-geo-text-muted">
                Agent活动
              </p>
              <Link
                href="/dashboard/agents"
                className="text-xs text-primary hover:underline"
              >
                查看全部
              </Link>
            </div>
          </CardHeader>
          <CardContent className="space-y-3 pt-0">
            {MOCK_AGENTS.map((agent) => (
              <AgentStatusCard
                key={agent.name}
                name={agent.name}
                description={agent.description}
                status={agent.status}
                lastActiveAt={agent.lastActiveAt}
                completedCount={agent.completedCount}
              />
            ))}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
