"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";
import { toast } from "sonner";

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

  useEffect(() => {
    if (params.relationshipId) {
      // URL에서 relationship_id 설정
      const id = params.relationshipId as string;
      setRelationshipId(id);

      // relationship_id로 관계도명 조회
      const fetchDiagramName = async () => {
        try {
          const relationships = await DataFlowAPI.getDiagramRelationshipsByRelationshipId(id);
          if (relationships.length > 0) {
            setDiagramName(relationships[0].relationship_name);
          } else {
            setDiagramName(`관계도 ID: ${id}`);
          }
        } catch (error) {
          console.error("관계도명 조회 실패:", error);
          setDiagramName(`관계도 ID: ${id}`);
        }
      };

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

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

  if (!relationshipId || !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-blue-600"></div>
          <p className="text-gray-500">관계도 정보를 불러오는 중...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* 헤더 */}
      <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-gray-900">📊 관계도 편집</h1>
            <p className="mt-1 text-gray-600">
              <span className="font-medium text-blue-600">{diagramName}</span> 관계도를 편집하고 있습니다
            </p>
          </div>
        </div>
      </div>

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