"use client";

import { useEffect, useState } from "react";
import {Sparkles } from "lucide-react";
import { listAARs, generateAAR } from "@/lib/api-v2";
import { PageContainer, Card} from "@/components/shared/PageContainer";
import { LoadingSpinner } from "@/components/shared/LoadingSpinner";
import { EmptyState } from "@/components/shared/EmptyState";
import { toast } from "sonner";

/** AAR 复盘记录项。 */
interface AARItem {
  trigger_event: string;
  gap_analysis?: string;
  lessons?: string[];
}

export default function AARsPage() {
  const [items, setItems] = useState<AARItem[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [triggerEvent, setTriggerEvent] = useState("");
  const [originalPlan, setOriginalPlan] = useState("");
  const [actualResult, setActualResult] = useState("");

  useEffect(() => {
    listAARs()
      .then((resp) => setItems((resp.data as AARItem[]) ?? []))
      .catch(() => setItems([]))
      .finally(() => setIsLoading(false));
  }, []);

  const handleGenerate = async () => {
    if (!triggerEvent.trim()) {
      toast.error("请输入触发事件");
      return;
    }
    try {
      const resp = await generateAAR(triggerEvent, originalPlan, actualResult);
      setItems([resp.data as AARItem, ...items]);
      toast.success("AAR 复盘已生成");
    } catch {
      toast.error("生成失败");
    }
  };

  return (
    <PageContainer title="AAR 系统化复盘" description="AI 五问复盘 — 发生了什么/为什么/什么做得好/什么没做好/下次怎么改">
      <Card>
        <h3 className="font-medium text-gray-900">生成 AAR 复盘</h3>
        <input
          type="text"
          value={triggerEvent}
          onChange={(e) => setTriggerEvent(e.target.value)}
          placeholder="触发事件"
          className="mt-2 w-full rounded-md border border-gray-300 px-3 py-1.5 text-sm"
        />
        <input
          type="text"
          value={originalPlan}
          onChange={(e) => setOriginalPlan(e.target.value)}
          placeholder="原计划"
          className="mt-2 w-full rounded-md border border-gray-300 px-3 py-1.5 text-sm"
        />
        <input
          type="text"
          value={actualResult}
          onChange={(e) => setActualResult(e.target.value)}
          placeholder="实际结果"
          className="mt-2 w-full rounded-md border border-gray-300 px-3 py-1.5 text-sm"
        />
        <button
          onClick={handleGenerate}
          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} /> AI 五问复盘
        </button>
      </Card>

      {isLoading ? (
        <LoadingSpinner />
      ) : items.length === 0 ? (
        <EmptyState description="暂无 AAR 复盘记录" />
      ) : (
        <div className="space-y-3">
          {items.map((item, i) => (
            <Card key={i}>
              <h3 className="font-medium text-gray-900">{item.trigger_event}</h3>
              {item.gap_analysis && <p className="mt-1 text-sm text-gray-600">{item.gap_analysis}</p>}
              {Array.isArray(item.lessons) && (
                <div className="mt-2 space-y-1">
                  {item.lessons.map((lesson, li) => (
                    <p key={li} className="text-xs text-gray-500">• {lesson}</p>
                  ))}
                </div>
              )}
            </Card>
          ))}
        </div>
      )}
    </PageContainer>
  );
}
