"use client";

import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { api, type Pipeline } from "@/components/api";
import { PipelineForm } from "@/components/pipeline-form";

export default function EditPipelinePage() {
  const params = useParams<{ id: string }>();
  const id = Number(params.id);

  const [pipeline, setPipeline] = useState<Pipeline | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    api<Pipeline>(`/api/pipelines/${id}`)
      .then(setPipeline)
      .catch((e) => setError(e instanceof Error ? e.message : "加载失败"))
      .finally(() => setLoading(false));
  }, [id]);

  if (loading) return <div className="text-sm text-muted-foreground">加载中…</div>;
  if (error || !pipeline)
    return (
      <div className="text-sm text-red-500">
        {error ? `加载失败：${error}` : "流水线不存在"}
      </div>
    );

  return <PipelineForm initial={pipeline} />;
}
