"use client";

import { useState } from "react";
import DataFlowList from "@/components/dataflow/DataFlowList";
import { FlowEditor } from "@/components/dataflow/node-editor/FlowEditor";
import { useAuth } from "@/hooks/useAuth";
import { toast } from "sonner";
import { showErrorToast } from "@/lib/utils/toastUtils";
import { Button } from "@/components/ui/button";
import { ArrowLeft } from "lucide-react";

type Step = "list" | "editor";

export default function DataFlowPage() {
  const { user } = useAuth();
  const [currentStep, setCurrentStep] = useState<Step>("list");
  const [loadingFlowId, setLoadingFlowId] = useState<number | null>(null);

  const handleLoadFlow = async (flowId: number | null) => {
    if (flowId === null) {
      setLoadingFlowId(null);
      setCurrentStep("editor");
      return;
    }

    try {
      setLoadingFlowId(flowId);
      setCurrentStep("editor");
      toast.success("플로우를 불러왔어요");
    } catch (error: any) {
      console.error("플로우 불러오기 실패:", error);
      showErrorToast("플로우를 불러오는 데 실패했어요", error, {
        guidance: "네트워크 연결을 확인해 주세요.",
      });
    }
  };

  const handleBackToList = () => {
    setCurrentStep("list");
    setLoadingFlowId(null);
  };

  if (currentStep === "editor") {
    return (
      <div className="bg-background fixed inset-0 z-50">
        <div className="flex h-full flex-col">
          <div className="bg-background flex items-center gap-4 border-b px-5 py-3">
            <Button
              variant="ghost"
              size="sm"
              onClick={handleBackToList}
              className="text-muted-foreground hover:text-foreground flex items-center gap-2 text-sm"
            >
              <ArrowLeft className="h-4 w-4" />
              목록으로
            </Button>
          </div>

          <div className="flex-1 overflow-hidden">
            <FlowEditor
              key={loadingFlowId || "new"}
              initialFlowId={loadingFlowId}
            />
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="h-full overflow-y-auto">
      <div className="mx-auto w-full max-w-[1400px] space-y-6 p-4 sm:p-6 pb-20">
        <DataFlowList onLoadFlow={handleLoadFlow} />
      </div>
    </div>
  );
}
