"use client";

import { useState } from "react";
import { useScopeEffect } from "@/lib/company-scope";
import { CompanyNameTag } from "@/components/shared/CompanyNameTag";
import {Sparkles } from "lucide-react";
import { listPreMortems, runPreMortem, listRedTeams, runRedTeam } from "@/lib/api-v2";
import { PageContainer, Card, Badge } from "@/components/shared/PageContainer";
import { LoadingSpinner } from "@/components/shared/LoadingSpinner";
import { EmptyState } from "@/components/shared/EmptyState";
import { toast } from "sonner";

/** Pre-mortem 记录项。 */
interface PreMortemItem {
  company_id?: string;
  decision_context: string;
  failure_paths?: FailurePath[];
}

/** 失败路径项。 */
interface FailurePath {
  path?: string;
}

/** Red Team 记录项。 */
interface RedTeamItem {
  company_id?: string;
  perspective: string;
  analysis: string;
}

export default function PreMortemsPage() {
  const [tab, setTab] = useState<"pre-mortem" | "red-team">("pre-mortem");
  const [preMortems, setPreMortems] = useState<PreMortemItem[]>([]);
  const [redTeams, setRedTeams] = useState<RedTeamItem[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [input, setInput] = useState("");
  const [perspective, setPerspective] = useState("competitor");

  useScopeEffect(() => {
    Promise.all([listPreMortems(), listRedTeams()])
      .then(([pm, rt]) => {
        setPreMortems((pm.data as PreMortemItem[]) ?? []);
        setRedTeams((rt.data as RedTeamItem[]) ?? []);
      })
      .catch(() => {
        setPreMortems([]);
        setRedTeams([]);
      })
      .finally(() => setIsLoading(false));
  });

  const handleRun = async () => {
    if (!input.trim()) {
      toast.error("请输入内容");
      return;
    }
    try {
      if (tab === "pre-mortem") {
        const resp = await runPreMortem(input);
        setPreMortems([resp.data as PreMortemItem, ...preMortems]);
        toast.success("Pre-mortem 分析完成");
      } else {
        const resp = await runRedTeam(input, perspective);
        setRedTeams([resp.data as RedTeamItem, ...redTeams]);
        toast.success("Red Team 分析完成");
      }
    } catch {
      toast.error("分析失败");
    }
  };

  return (
    <PageContainer title="Pre-mortem & Red Team" description="AI 失败路径推演 + 对抗分析">
      <div className="flex gap-2 border-b border-gray-200">
        <button
          onClick={() => setTab("pre-mortem")}
          className={`px-4 py-2 text-sm font-medium ${tab === "pre-mortem" ? "border-b-2 border-gray-900 text-gray-900" : "text-gray-500"}`}
        >
          Pre-mortem
        </button>
        <button
          onClick={() => setTab("red-team")}
          className={`px-4 py-2 text-sm font-medium ${tab === "red-team" ? "border-b-2 border-gray-900 text-gray-900" : "text-gray-500"}`}
        >
          Red Team
        </button>
      </div>

      <Card>
        <textarea
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder={tab === "pre-mortem" ? "输入决策上下文..." : "输入企业上下文..."}
          className="w-full rounded-md border border-gray-300 p-3 text-sm"
          rows={3}
        />
        {tab === "red-team" && (
          <select
            value={perspective}
            onChange={(e) => setPerspective(e.target.value)}
            className="mt-2 rounded-md border border-gray-300 px-3 py-1.5 text-sm"
          >
            <option value="competitor">竞争对手视角</option>
            <option value="pessimistic_investor">悲观投资人视角</option>
            <option value="devils_advocate">魔鬼代言人视角</option>
          </select>
        )}
        <button
          onClick={handleRun}
          className="mt-2 flex items-center gap-1 rounded-md bg-gray-900 px-3 py-1.5 text-sm text-white hover:bg-gray-700"
        >
          <Sparkles size={16} /> {tab === "pre-mortem" ? "失败推演" : "对抗分析"}
        </button>
      </Card>

      {isLoading ? (
        <LoadingSpinner />
      ) : tab === "pre-mortem" ? (
        preMortems.length === 0 ? <EmptyState description="暂无 Pre-mortem 记录" /> : (
          <div className="space-y-3">
            {preMortems.map((item, i) => (
              <Card key={i}>
                <CompanyNameTag companyId={item.company_id} />
                <h3 className="font-medium text-gray-900">{item.decision_context as string}</h3>
                {Array.isArray(item.failure_paths) && (
                  <div className="mt-2 space-y-1">
                    {(item.failure_paths as FailurePath[]).map((fp, fi) => (
                      <p key={fi} className="text-xs text-gray-500">• {String(fp.path ?? fp)}</p>
                    ))}
                  </div>
                )}
              </Card>
            ))}
          </div>
        )
      ) : (
        redTeams.length === 0 ? <EmptyState description="暂无 Red Team 记录" /> : (
          <div className="space-y-3">
            {redTeams.map((item, i) => (
              <Card key={i}>
                <div className="flex items-center gap-2">
                  <CompanyNameTag companyId={item.company_id} />
                  <Badge color="red">{item.perspective as string}</Badge>
                </div>
                <p className="mt-2 text-sm text-gray-600">{item.analysis as string}</p>
              </Card>
            ))}
          </div>
        )
      )}
    </PageContainer>
  );
}
