"use client";

import { useParams, useRouter } from "next/navigation";
import { useState, useEffect } from "react";
import { ArrowLeft } from "lucide-react";
import { Button } from "@/components/ui/button";
import { DataFlowDesigner } from "@/components/dataflow/DataFlowDesigner";
import { DataFlowAPI } from "@/lib/api/dataflow";

export default function DataFlowEditPage() {
  const params = useParams();
  const router = useRouter();
  const [diagramId, setDiagramId] = useState<number>(0);
  const [diagramName, setDiagramName] = useState<string>("");

  useEffect(() => {
    if (params.diagramId) {
      // URL에서 diagram_id 설정
      const id = parseInt(params.diagramId as string);
      setDiagramId(id);

      // diagram_id로 관계도명 조회
      const fetchDiagramName = async () => {
        try {
          const jsonDiagram = await DataFlowAPI.getJsonDataFlowDiagramById(id);
          if (jsonDiagram && jsonDiagram.diagram_name) {
            setDiagramName(jsonDiagram.diagram_name);
          } else {
            setDiagramName(`관계도 ID: ${id}`);
          }
        } catch (error) {
          console.error("관계도명 조회 실패:", error);
          setDiagramName(`관계도 ID: ${id}`);
        }
      };

      fetchDiagramName();
    }
  }, [params.diagramId]);

  const handleBackToList = () => {
    router.push("/admin/dataflow");
  };

  // 관계도 이름 업데이트 핸들러
  const handleDiagramNameUpdate = (newDiagramName: string) => {
    setDiagramName(newDiagramName);
  };

  if (!diagramId || !diagramName) {
    return (
      <div className="flex h-64 items-center justify-center">
        <div className="text-center">
          <div className="mx-auto mb-4 h-8 w-8 animate-spin rounded-full border-b-2 border-primary"></div>
          <p className="text-muted-foreground">관계도 정보를 불러오는 중...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-8">
      {/* 헤더 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-4">
          <Button variant="outline" size="sm" onClick={handleBackToList} className="flex items-center space-x-2">
            <ArrowLeft className="h-4 w-4" />
            <span>목록으로</span>
          </Button>
          <div>
            <h1 className="text-2xl font-bold text-foreground">📊 관계도 편집</h1>
            <p className="mt-1 text-muted-foreground">
              <span className="font-medium text-primary">{diagramName}</span> 관계도를 편집하고 있습니다
            </p>
          </div>
        </div>
      </div>

      {/* 데이터플로우 디자이너 */}
      <div className="rounded-lg border border-border bg-white">
        <DataFlowDesigner
          key={diagramId}
          selectedDiagram={diagramName}
          diagramId={diagramId}
          onBackToList={handleBackToList}
          onDiagramNameUpdate={handleDiagramNameUpdate}
        />
      </div>
    </div>
  );
}
