import { useState, useRef, useEffect } from "react";
import { useParams } from "react-router";
import {
  Sparkles,
  Play,
  Pause,
  RotateCcw,
  CheckCircle2,
  Circle,
  Loader2,
  ChevronDown,
  Bot,
  Shield,
  Zap,
  AlertCircle,
  Download,
  SkipForward,
  Clock,
  Star,
  MessageSquare,
} from "lucide-react";
import {
  useLatestAgentRun,
  useStartAgentRun,
  usePauseAgentRun,
  useResumeAgentRun,
  useAgentSse,
} from "../../hooks/useAgent";
import type { AgentStepDTO } from "../../lib/api/agent";

// ─── Sub Components ───────────────────────────────────────────────────────────

function ScoreTag({ score }: { score?: string }) {
  if (!score) return null;
  const cfg: Record<string, { color: string; label: string }> = {
    A: { color: "text-emerald-400 bg-emerald-400/10 border-emerald-400/20", label: "A · 优质，直接通过" },
    B: { color: "text-blue-400 bg-blue-400/10 border-blue-400/20", label: "B · 良好，可继续" },
    C: { color: "text-amber-400 bg-amber-400/10 border-amber-400/20", label: "C · 建议修改" },
    D: { color: "text-red-400 bg-red-400/10 border-red-400/20", label: "D · 建议重做" },
  };
  const c = cfg[score];
  if (!c) return null;
  return (
    <span className={`inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs border font-medium ${c.color}`}>
      <Star className="w-3 h-3" />
      {c.label}
    </span>
  );
}

function StepIcon({ status }: { status: AgentStepDTO["status"] }) {
  if (status === "RUNNING") return <Loader2 className="w-4 h-4 animate-spin text-primary" />;
  if (status === "DONE") return <CheckCircle2 className="w-4 h-4 text-emerald-400" />;
  if (status === "FAILED") return <AlertCircle className="w-4 h-4 text-red-400" />;
  if (status === "SKIPPED") return <SkipForward className="w-4 h-4 text-muted-foreground" />;
  return <Circle className="w-4 h-4 text-muted-foreground/40" />;
}

function AgentBadge({ type }: { type: AgentStepDTO["agentType"] }) {
  const cfg = {
    DECISION: { icon: Bot, label: "决策层", color: "text-violet-400 bg-violet-400/10" },
    EXECUTOR: { icon: Zap, label: "执行层", color: "text-blue-400 bg-blue-400/10" },
    SUPERVISION: { icon: Shield, label: "监督层", color: "text-amber-400 bg-amber-400/10" },
  }[type];
  const Icon = cfg.icon;
  return (
    <span className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[11px] font-medium ${cfg.color}`}>
      <Icon className="w-3 h-3" />
      {cfg.label}
    </span>
  );
}

function StepCard({ step }: { step: AgentStepDTO }) {
  const [expanded, setExpanded] = useState(
    step.status === "RUNNING" || step.status === "DONE"
  );
  const hasDetail = !!(step.output || step.scoreDetail);

  return (
    <div
      className={`rounded-xl border transition-all ${
        step.status === "RUNNING"
          ? "border-primary/40 bg-primary/5"
          : step.status === "DONE"
          ? "border-border bg-card"
          : "border-border/50 bg-card/50"
      }`}
    >
      <button
        className="w-full flex items-center gap-3 px-4 py-3 text-left"
        onClick={() => hasDetail && setExpanded(!expanded)}
      >
        <StepIcon status={step.status} />
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 flex-wrap">
            <span
              className={`text-sm font-medium ${
                step.status === "PENDING" ? "text-muted-foreground" : "text-foreground"
              }`}
            >
              {step.stepName}
            </span>
            <AgentBadge type={step.agentType} />
            {step.score && <ScoreTag score={step.score} />}
          </div>
          {step.durationMs != null && (
            <span className="text-xs text-muted-foreground flex items-center gap-1 mt-0.5">
              <Clock className="w-3 h-3" />
              {(step.durationMs / 1000).toFixed(1)}s
            </span>
          )}
        </div>
        {hasDetail && (
          <ChevronDown
            className={`w-4 h-4 text-muted-foreground flex-shrink-0 transition-transform ${expanded ? "rotate-180" : ""}`}
          />
        )}
      </button>

      {expanded && hasDetail && (
        <div className="px-4 pb-3 border-t border-border/50">
          <p className="text-sm text-muted-foreground leading-relaxed mt-3 whitespace-pre-wrap">
            {step.scoreDetail || step.output}
          </p>
        </div>
      )}
    </div>
  );
}

// ─── Main Page ────────────────────────────────────────────────────────────────

export function AgentStudio() {
  const { projectId = "" } = useParams();
  const [goal, setGoal] = useState("将剧本生成完整动画短剧，5集，现代都市言情风格");
  const [activeTab, setActiveTab] = useState<"chat" | "logs">("logs");
  const logsEndRef = useRef<HTMLDivElement>(null);

  const { data: run, isLoading, isError } = useLatestAgentRun(projectId);
  const startMut = useStartAgentRun(projectId);
  const pauseMut = usePauseAgentRun(projectId);
  const resumeMut = useResumeAgentRun(projectId);

  const { logs } = useAgentSse(run?.id ?? null, projectId);

  const steps = run?.steps ?? [];
  const runStatus = run?.status ?? "idle";

  const doneCount = steps.filter((s) => s.status === "DONE").length;
  const totalCount = steps.length;
  const progress = totalCount > 0 ? Math.round((doneCount / totalCount) * 100) : 0;
  const runningStep = steps.find((s) => s.status === "RUNNING");

  useEffect(() => {
    if (activeTab === "logs") logsEndRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [logs, activeTab]);

  const handleStart = () => {
    startMut.mutate(goal);
  };

  const handlePause = () => {
    if (run) pauseMut.mutate(run.id);
  };

  const handleResume = () => {
    if (run) resumeMut.mutate(run.id);
  };

  if (isLoading) {
    return (
      <div className="h-full flex items-center justify-center">
        <Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
      </div>
    );
  }

  if (isError) {
    return (
      <div className="h-full flex items-center justify-center flex-col gap-3 text-muted-foreground">
        <AlertCircle className="w-10 h-10" />
        <p className="text-sm">无法连接后端服务，请确认后端已启动</p>
      </div>
    );
  }

  const isIdle = !run || runStatus === "DONE" || runStatus === "FAILED";

  return (
    <div className="h-full flex flex-col bg-background">
      {/* ── Header ── */}
      <div className="border-b border-border bg-card px-6 py-4">
        <div className="flex items-center justify-between">
          <div>
            <div className="flex items-center gap-2 mb-1">
              <Bot className="w-5 h-5 text-primary" />
              <h1 className="text-base font-semibold text-foreground">Agent 制作中心</h1>
              {run && (
                <span
                  className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium ${
                    runStatus === "RUNNING"
                      ? "bg-primary/10 text-primary"
                      : runStatus === "DONE"
                      ? "bg-emerald-400/10 text-emerald-400"
                      : runStatus === "PAUSED"
                      ? "bg-amber-400/10 text-amber-400"
                      : runStatus === "FAILED"
                      ? "bg-red-400/10 text-red-400"
                      : "bg-muted text-muted-foreground"
                  }`}
                >
                  {runStatus === "RUNNING" && <Loader2 className="w-3 h-3 animate-spin" />}
                  {runStatus === "DONE" && <CheckCircle2 className="w-3 h-3" />}
                  {runStatus === "RUNNING" ? "运行中"
                    : runStatus === "DONE" ? "已完成"
                    : runStatus === "PAUSED" ? "已暂停"
                    : runStatus === "FAILED" ? "失败"
                    : "待开始"}
                </span>
              )}
            </div>
            <p className="text-sm text-muted-foreground">
              {run?.goal ?? "AI 自动串联全部制作步骤，一键完成剧本→分镜→视频"}
            </p>
          </div>

          <div className="flex items-center gap-2">
            {isIdle && (
              <button
                onClick={handleStart}
                disabled={startMut.isPending}
                className="flex items-center gap-2 px-4 py-2 rounded-lg bg-primary text-primary-foreground text-sm font-medium hover:bg-primary/90 disabled:opacity-50"
              >
                {startMut.isPending ? (
                  <Loader2 className="w-4 h-4 animate-spin" />
                ) : (
                  <Play className="w-4 h-4" />
                )}
                开始制作
              </button>
            )}
            {runStatus === "RUNNING" && (
              <button
                onClick={handlePause}
                disabled={pauseMut.isPending}
                className="flex items-center gap-2 px-3 py-2 rounded-lg border border-border text-sm hover:bg-muted disabled:opacity-50"
              >
                <Pause className="w-4 h-4" />
                暂停
              </button>
            )}
            {runStatus === "PAUSED" && (
              <button
                onClick={handleResume}
                disabled={resumeMut.isPending}
                className="flex items-center gap-2 px-3 py-2 rounded-lg bg-primary text-primary-foreground text-sm hover:bg-primary/90 disabled:opacity-50"
              >
                <Play className="w-4 h-4" />
                继续
              </button>
            )}
            {runStatus === "DONE" && (
              <button className="flex items-center gap-2 px-4 py-2 rounded-lg bg-primary text-primary-foreground text-sm font-medium hover:bg-primary/90">
                <Download className="w-4 h-4" />
                查看成果
              </button>
            )}
            {run && (
              <button
                onClick={handleStart}
                className="p-2 rounded-lg border border-border hover:bg-muted"
                title="重新制作"
              >
                <RotateCcw className="w-4 h-4 text-muted-foreground" />
              </button>
            )}
          </div>
        </div>

        {/* Progress Bar */}
        {run && totalCount > 0 && (
          <div className="mt-4">
            <div className="flex items-center justify-between mb-1.5">
              <span className="text-xs text-muted-foreground">
                {runningStep ? `正在执行：${runningStep.stepName}` : `${doneCount} / ${totalCount} 步骤完成`}
              </span>
              <span className="text-xs font-medium text-foreground">{progress}%</span>
            </div>
            <div className="h-1.5 rounded-full bg-muted overflow-hidden">
              <div
                className="h-full rounded-full bg-primary transition-all duration-500"
                style={{ width: `${progress}%` }}
              />
            </div>
          </div>
        )}
      </div>

      {/* ── Body ── */}
      <div className="flex-1 overflow-hidden flex">
        {/* Steps Panel */}
        <div className="flex-1 overflow-auto p-6">
          {/* Goal input — idle state */}
          {isIdle && (
            <div className="mb-6 p-4 rounded-xl border border-primary/20 bg-primary/5">
              <label className="block text-sm font-medium text-foreground mb-2">制作目标</label>
              <textarea
                value={goal}
                onChange={(e) => setGoal(e.target.value)}
                rows={2}
                className="w-full px-3 py-2 rounded-lg border border-border bg-background text-sm resize-none focus:outline-none focus:ring-2 focus:ring-primary/20"
                placeholder="描述你想要的短剧，例如：现代都市爱情，5集，每集3分钟..."
              />
              <p className="mt-2 text-xs text-muted-foreground">
                AI 将自动完成：大纲 → 分集脚本 → 角色/场景提取 → 分镜生成，全程监督审核
              </p>
            </div>
          )}

          {/* Step Cards */}
          {steps.length > 0 && (
            <div className="space-y-2">
              {steps.map((step) => (
                <StepCard key={step.id} step={step} />
              ))}
            </div>
          )}

          {/* Placeholder when no run */}
          {!run && (
            <div className="flex flex-col items-center justify-center py-20 text-center text-muted-foreground">
              <Sparkles className="w-12 h-12 mb-4 opacity-20" />
              <p className="text-sm">填写制作目标，点击"开始制作"</p>
              <p className="text-xs mt-1">AI 将自动规划并执行所有步骤</p>
            </div>
          )}

          {/* Done summary */}
          {runStatus === "DONE" && (
            <div className="mt-6 p-4 rounded-xl border border-emerald-400/20 bg-emerald-400/5">
              <div className="flex items-center gap-2 text-emerald-400 mb-2">
                <CheckCircle2 className="w-5 h-5" />
                <span className="font-medium">制作完成</span>
              </div>
              <p className="text-sm text-muted-foreground">
                全部 {totalCount} 个步骤已完成。前往分镜工作台查看生成结果。
              </p>
            </div>
          )}

          {runStatus === "FAILED" && (
            <div className="mt-6 p-4 rounded-xl border border-red-400/20 bg-red-400/5">
              <div className="flex items-center gap-2 text-red-400 mb-2">
                <AlertCircle className="w-5 h-5" />
                <span className="font-medium">制作失败</span>
              </div>
              <p className="text-sm text-muted-foreground">
                请查看日志了解失败原因，可点击"重新制作"重试。
              </p>
            </div>
          )}
        </div>

        {/* Right Panel */}
        <div className="w-80 border-l border-border flex flex-col bg-card">
          <div className="flex border-b border-border">
            <button
              onClick={() => setActiveTab("chat")}
              className={`flex-1 flex items-center justify-center gap-1.5 py-3 text-sm transition-colors ${
                activeTab === "chat"
                  ? "text-foreground border-b-2 border-primary"
                  : "text-muted-foreground hover:text-foreground"
              }`}
            >
              <MessageSquare className="w-4 h-4" />
              说明
            </button>
            <button
              onClick={() => setActiveTab("logs")}
              className={`flex-1 flex items-center justify-center gap-1.5 py-3 text-sm transition-colors ${
                activeTab === "logs"
                  ? "text-foreground border-b-2 border-primary"
                  : "text-muted-foreground hover:text-foreground"
              }`}
            >
              <Zap className="w-4 h-4" />
              执行日志
            </button>
          </div>

          {/* Info panel */}
          {activeTab === "chat" && (
            <div className="flex-1 overflow-auto p-4 text-sm text-muted-foreground space-y-4">
              <div>
                <p className="font-medium text-foreground mb-1">三层 Agent 架构</p>
                <div className="space-y-1.5 text-xs">
                  <div className="flex items-start gap-2">
                    <Bot className="w-3.5 h-3.5 mt-0.5 text-violet-400 flex-shrink-0" />
                    <span><span className="text-violet-400">决策层</span>：分析目标，制定执行计划</span>
                  </div>
                  <div className="flex items-start gap-2">
                    <Zap className="w-3.5 h-3.5 mt-0.5 text-blue-400 flex-shrink-0" />
                    <span><span className="text-blue-400">执行层</span>：各 SubAgent 负责单一任务</span>
                  </div>
                  <div className="flex items-start gap-2">
                    <Shield className="w-3.5 h-3.5 mt-0.5 text-amber-400 flex-shrink-0" />
                    <span><span className="text-amber-400">监督层</span>：质量评审，A/B/C/D 评分</span>
                  </div>
                </div>
              </div>
              <div>
                <p className="font-medium text-foreground mb-1">执行顺序</p>
                <ol className="text-xs space-y-1 list-decimal list-inside">
                  <li>目标分析与规划</li>
                  <li>大纲生成</li>
                  <li>分集脚本生成</li>
                  <li>监督层审核剧本</li>
                  <li>角色/场景提取</li>
                  <li>分镜生成</li>
                  <li>监督层终审</li>
                </ol>
              </div>
            </div>
          )}

          {/* Logs panel */}
          {activeTab === "logs" && (
            <div className="flex-1 overflow-auto p-3 font-mono text-xs space-y-1">
              {logs.length === 0 && (
                <p className="text-muted-foreground/50 text-center mt-8">暂无日志</p>
              )}
              {logs.map((log) => (
                <div key={log.id} className="flex gap-2 leading-relaxed">
                  <span className="text-muted-foreground/60 flex-shrink-0">{log.time}</span>
                  <span
                    className={
                      log.level === "agent"
                        ? "text-primary"
                        : log.level === "warn"
                        ? "text-amber-400"
                        : log.level === "error"
                        ? "text-red-400"
                        : "text-muted-foreground"
                    }
                  >
                    {log.message}
                  </span>
                </div>
              ))}
              <div ref={logsEndRef} />
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
