"use client";

/**
 * 노드 속성 편집 패널
 */

import { X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useFlowEditorStore } from "@/lib/stores/flowEditorStore";
import { TableSourceProperties } from "./properties/TableSourceProperties";
import { InsertActionProperties } from "./properties/InsertActionProperties";
import { ConditionProperties } from "./properties/ConditionProperties";
import { UpdateActionProperties } from "./properties/UpdateActionProperties";
import { DeleteActionProperties } from "./properties/DeleteActionProperties";
import { ExternalDBSourceProperties } from "./properties/ExternalDBSourceProperties";
import { UpsertActionProperties } from "./properties/UpsertActionProperties";
import { DataTransformProperties } from "./properties/DataTransformProperties";
import { AggregateProperties } from "./properties/AggregateProperties";
import { FormulaTransformProperties } from "./properties/FormulaTransformProperties";
import { RestAPISourceProperties } from "./properties/RestAPISourceProperties";
import { CommentProperties } from "./properties/CommentProperties";
import { LogProperties } from "./properties/LogProperties";
import { EmailActionProperties } from "./properties/EmailActionProperties";
import { ScriptActionProperties } from "./properties/ScriptActionProperties";
import { HttpRequestActionProperties } from "./properties/HttpRequestActionProperties";
import { ProcedureCallActionProperties } from "./properties/ProcedureCallActionProperties";
import type { NodeType } from "@/types/node-editor";

export function PropertiesPanel() {
  const { nodes, selectedNodes, setShowPropertiesPanel } = useFlowEditorStore();

  // 선택된 노드가 하나일 경우 해당 노드 데이터 가져오기
  const selectedNode = selectedNodes.length === 1 ? nodes.find((n) => n.id === selectedNodes[0]) : null;

  return (
    <div
      style={{
        display: "flex",
        flexDirection: "column",
        height: "100%",
        width: "100%",
        overflow: "hidden",
      }}
    >
      {/* 헤더 */}
      <div
        style={{
          flexShrink: 0,
          height: "64px",
        }}
        className="flex items-center justify-between border-b bg-white p-4"
      >
        <div>
          <h3 className="text-sm font-semibold text-gray-900">속성</h3>
          {selectedNode && (
            <p className="mt-0.5 text-xs text-gray-500">{getNodeTypeLabel(selectedNode.type as NodeType)}</p>
          )}
        </div>
        <Button variant="ghost" size="sm" onClick={() => setShowPropertiesPanel(false)} className="h-6 w-6 p-0">
          <X className="h-4 w-4" />
        </Button>
      </div>

      {/* 내용 - 스크롤 가능 영역 */}
      <div
        style={{
          flex: 1,
          minHeight: 0,
          overflowY: "auto",
          overflowX: "hidden",
        }}
      >
        {selectedNodes.length === 0 ? (
          <div className="flex h-full items-center justify-center p-4">
            <div className="text-center text-sm text-gray-500">
              <div className="mb-2 text-2xl">📝</div>
              <p>노드를 선택하여</p>
              <p>속성을 편집하세요</p>
            </div>
          </div>
        ) : selectedNodes.length === 1 && selectedNode ? (
          <NodePropertiesRenderer node={selectedNode} />
        ) : (
          <div className="flex h-full items-center justify-center p-4">
            <div className="text-center text-sm text-gray-500">
              <div className="mb-2 text-2xl">📋</div>
              <p>{selectedNodes.length}개의 노드가</p>
              <p>선택되었습니다</p>
              <p className="mt-2 text-xs">한 번에 하나의 노드만 편집할 수 있습니다</p>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

/**
 * 노드 타입별 속성 렌더러
 */
function NodePropertiesRenderer({ node }: { node: any }) {
  switch (node.type) {
    case "tableSource":
      return <TableSourceProperties nodeId={node.id} data={node.data} />;

    case "insertAction":
      return <InsertActionProperties nodeId={node.id} data={node.data} />;

    case "condition":
      return <ConditionProperties nodeId={node.id} data={node.data} />;

    case "updateAction":
      return <UpdateActionProperties nodeId={node.id} data={node.data} />;

    case "deleteAction":
      return <DeleteActionProperties nodeId={node.id} data={node.data} />;

    case "externalDBSource":
      return <ExternalDBSourceProperties nodeId={node.id} data={node.data} />;

    case "upsertAction":
      return <UpsertActionProperties nodeId={node.id} data={node.data} />;

    case "dataTransform":
      return <DataTransformProperties nodeId={node.id} data={node.data} />;

    case "aggregate":
      return <AggregateProperties nodeId={node.id} data={node.data} />;

    case "formulaTransform":
      return <FormulaTransformProperties nodeId={node.id} data={node.data} />;

    case "restAPISource":
      return <RestAPISourceProperties nodeId={node.id} data={node.data} />;

    case "comment":
      return <CommentProperties nodeId={node.id} data={node.data} />;

    case "log":
      return <LogProperties nodeId={node.id} data={node.data} />;

    case "emailAction":
      return <EmailActionProperties nodeId={node.id} data={node.data} />;

    case "scriptAction":
      return <ScriptActionProperties nodeId={node.id} data={node.data} />;

    case "httpRequestAction":
      return <HttpRequestActionProperties nodeId={node.id} data={node.data} />;

    case "procedureCallAction":
      return <ProcedureCallActionProperties nodeId={node.id} data={node.data} />;

    default:
      return (
        <div className="p-4">
          <div className="rounded border border-yellow-200 bg-yellow-50 p-4 text-sm">
            <p className="font-medium text-yellow-800">🚧 속성 편집 준비 중</p>
            <p className="mt-2 text-xs text-yellow-700">
              {getNodeTypeLabel(node.type as NodeType)} 노드의 속성 편집 UI는 곧 구현될 예정입니다.
            </p>
            <div className="mt-3 rounded bg-white p-2 text-xs">
              <p className="font-medium text-gray-700">노드 ID:</p>
              <p className="font-mono text-gray-600">{node.id}</p>
            </div>
          </div>
        </div>
      );
  }
}

/**
 * 노드 타입 라벨 가져오기
 */
function getNodeTypeLabel(type: NodeType): string {
  const labels: Record<NodeType, string> = {
    tableSource: "테이블 소스",
    externalDBSource: "외부 DB 소스",
    restAPISource: "REST API 소스",
    condition: "조건 분기",
    fieldMapping: "필드 매핑",
    dataTransform: "데이터 변환",
    aggregate: "집계",
    formulaTransform: "수식 변환",
    insertAction: "INSERT 액션",
    updateAction: "UPDATE 액션",
    deleteAction: "DELETE 액션",
    upsertAction: "UPSERT 액션",
    emailAction: "메일 발송",
    scriptAction: "스크립트 실행",
    httpRequestAction: "HTTP 요청",
    procedureCallAction: "프로시저 호출",
    comment: "주석",
    log: "로그",
  };
  return labels[type] || type;
}
