"use client";

import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { ArrowLeft, Save, Loader2, Plus, Settings, Trash2, Edit2 } from "lucide-react";
import { yardLayoutApi } from "@/lib/api/yardLayoutApi";
import dynamic from "next/dynamic";
import { YardLayout, YardPlacement } from "./types";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { AlertCircle, CheckCircle, XCircle } from "lucide-react";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useToast } from "@/hooks/use-toast";

const Yard3DCanvas = dynamic(() => import("./Yard3DCanvas"), {
  ssr: false,
  loading: () => (
    <div className="flex h-full items-center justify-center bg-foreground">
      <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
    </div>
  ),
});

// 나중에 구현할 데이터 바인딩 패널
const YardElementConfigPanel = dynamic(() => import("./YardElementConfigPanel"), {
  ssr: false,
  loading: () => <div>로딩 중...</div>,
});

interface YardEditorProps {
  layout: YardLayout;
  onBack: () => void;
}

export default function YardEditor({ layout, onBack }: YardEditorProps) {
  const { toast } = useToast();
  const [placements, setPlacements] = useState<YardPlacement[]>([]);
  const [originalPlacements, setOriginalPlacements] = useState<YardPlacement[]>([]); // 원본 데이터 보관
  const [selectedPlacement, setSelectedPlacement] = useState<YardPlacement | null>(null);
  const [focusPlacementId, setFocusPlacementId] = useState<number | null>(null); // 카메라 포커스할 요소 ID
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [showConfigPanel, setShowConfigPanel] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false); // 미저장 변경사항 추적
  const [nextPlacementId, setNextPlacementId] = useState(-1); // 임시 ID (음수 사용)
  const [saveResultDialog, setSaveResultDialog] = useState<{
    open: boolean;
    success: boolean;
    message: string;
  }>({ open: false, success: false, message: "" });
  const [deleteConfirmDialog, setDeleteConfirmDialog] = useState<{
    open: boolean;
    placementId: number | null;
  }>({ open: false, placementId: null });
  const [editLayoutDialog, setEditLayoutDialog] = useState<{
    open: boolean;
    name: string;
  }>({ open: false, name: "" });

  // 배치 목록 로드
  useEffect(() => {
    const loadPlacements = async () => {
      try {
        setIsLoading(true);
        const response = await yardLayoutApi.getPlacementsByLayoutId(layout.id);
        if (response.success) {
          const loadedData = (response.data as YardPlacement[]).map((p) => ({
            ...p,
            // 문자열로 저장된 숫자 필드를 숫자로 변환
            position_x: Number(p.position_x),
            position_y: Number(p.position_y),
            position_z: Number(p.position_z),
            size_x: Number(p.size_x),
            size_y: Number(p.size_y),
            size_z: Number(p.size_z),
            quantity: p.quantity !== null && p.quantity !== undefined ? Number(p.quantity) : null,
          }));
          setPlacements(loadedData);
          setOriginalPlacements(JSON.parse(JSON.stringify(loadedData))); // 깊은 복사
        }
      } catch (error) {
        console.error("배치 목록 로드 실패:", error);
        setError("배치 목록을 불러올 수 없습니다.");
      } finally {
        setIsLoading(false);
      }
    };

    loadPlacements();
  }, [layout.id]);

  // 빈 공간 찾기 (그리드 기반)
  const findEmptyGridPosition = (gridSize = 5) => {
    // 이미 사용 중인 좌표 Set
    const occupiedPositions = new Set(
      placements.map((p) => {
        const x = Math.round(p.position_x / gridSize) * gridSize;
        const z = Math.round(p.position_z / gridSize) * gridSize;
        return `${x},${z}`;
      }),
    );

    // 나선형으로 빈 공간 찾기
    let x = 0;
    let z = 0;
    let direction = 0; // 0: 우, 1: 하, 2: 좌, 3: 상
    let steps = 1;
    let stepsTaken = 0;
    let stepsInDirection = 0;

    for (let i = 0; i < 1000; i++) {
      const key = `${x},${z}`;
      if (!occupiedPositions.has(key)) {
        return { x, z };
      }

      // 다음 위치로 이동
      stepsInDirection++;
      if (direction === 0)
        x += gridSize; // 우
      else if (direction === 1)
        z += gridSize; // 하
      else if (direction === 2)
        x -= gridSize; // 좌
      else z -= gridSize; // 상

      if (stepsInDirection >= steps) {
        stepsInDirection = 0;
        direction = (direction + 1) % 4;
        stepsTaken++;
        if (stepsTaken === 2) {
          stepsTaken = 0;
          steps++;
        }
      }
    }

    return { x: 0, z: 0 };
  };

  // 특정 XZ 위치에 배치할 때 적절한 Y 위치 계산 (마인크래프트 쌓기)
  const calculateYPosition = (x: number, z: number, existingPlacements: YardPlacement[]) => {
    const gridSize = 5;
    const halfSize = gridSize / 2;
    let maxY = halfSize; // 기본 바닥 높이 (2.5)

    for (const p of existingPlacements) {
      // XZ가 겹치는지 확인
      const isXZOverlapping = Math.abs(x - p.position_x) < gridSize && Math.abs(z - p.position_z) < gridSize;

      if (isXZOverlapping) {
        // 이 요소의 윗면 높이
        const topY = p.position_y + (p.size_y || gridSize) / 2;
        // 새 요소의 Y 위치 (윗면 + 새 요소 높이/2)
        const newY = topY + gridSize / 2;
        if (newY > maxY) {
          maxY = newY;
        }
      }
    }

    return maxY;
  };

  // 빈 요소 추가 (로컬 상태에만 추가, 저장 시 서버에 반영)
  const handleAddElement = () => {
    const gridSize = 5;
    const emptyPos = findEmptyGridPosition(gridSize);
    const centerX = emptyPos.x + gridSize / 2;
    const centerZ = emptyPos.z + gridSize / 2;

    // 해당 위치에 적절한 Y 계산 (쌓기)
    const appropriateY = calculateYPosition(centerX, centerZ, placements);

    const newPlacement: YardPlacement = {
      id: nextPlacementId, // 임시 음수 ID
      yard_layout_id: layout.id,
      material_code: null,
      material_name: null,
      quantity: null,
      unit: null,
      // 그리드 칸의 중심에 배치 (Three.js Box position은 중심점)
      position_x: centerX, // 칸 중심: 0→2.5, 5→7.5, 10→12.5...
      position_y: appropriateY, // 쌓기 고려한 Y 위치
      position_z: centerZ, // 칸 중심: 0→2.5, 5→7.5, 10→12.5...
      size_x: gridSize,
      size_y: gridSize,
      size_z: gridSize,
      color: "#9ca3af",
      data_source_type: null,
      data_source_config: null,
      data_binding: null,
      created_at: new Date().toISOString(),
      updated_at: new Date().toISOString(),
    };

    setPlacements((prev) => [...prev, newPlacement]);
    setSelectedPlacement(newPlacement);
    setShowConfigPanel(true);
    setHasUnsavedChanges(true);
    setNextPlacementId((prev) => prev - 1); // 다음 임시 ID
  };

  // 요소 선택 (3D 캔버스 또는 목록에서)
  const handleSelectPlacement = (placement: YardPlacement | null) => {
    console.log("📍 handleSelectPlacement called with:", placement);

    if (!placement) {
      // 빈 공간 클릭 시 선택 해제
      console.log("  → Deselecting (null placement)");
      setSelectedPlacement(null);
      setShowConfigPanel(false);
      setFocusPlacementId(null);
      return;
    }

    console.log("  → Selecting placement:", placement.id, placement.material_name);
    setSelectedPlacement(placement);
    setShowConfigPanel(false); // 선택 시에는 설정 패널 닫기

    console.log("  → Setting focusPlacementId to:", placement.id);
    setFocusPlacementId(placement.id); // 카메라 포커스

    // 카메라 애니메이션 완료 후 focusPlacementId 초기화 (재클릭 시 다시 포커스 가능)
    setTimeout(() => {
      console.log("  → Clearing focusPlacementId");
      setFocusPlacementId(null);
    }, 1100); // 애니메이션 시간(1000ms)보다 약간 길게
  };

  // 설정 버튼 클릭
  const handleConfigClick = (placement: YardPlacement) => {
    setSelectedPlacement(placement);
    setShowConfigPanel(true);
  };

  // 요소 삭제 확인 Dialog 열기
  const handleDeletePlacement = (placementId: number) => {
    setDeleteConfirmDialog({ open: true, placementId });
  };

  // 중력 적용: 삭제된 요소 위에 있던 요소들을 아래로 내림
  const applyGravity = (deletedPlacement: YardPlacement, remainingPlacements: YardPlacement[]) => {
    const gridSize = 5;
    const halfSize = gridSize / 2;

    return remainingPlacements.map((p) => {
      // 삭제된 요소와 XZ가 겹치는지 확인
      const isXZOverlapping =
        Math.abs(p.position_x - deletedPlacement.position_x) < gridSize &&
        Math.abs(p.position_z - deletedPlacement.position_z) < gridSize;

      // 삭제된 요소보다 위에 있는지 확인
      const isAbove = p.position_y > deletedPlacement.position_y;

      if (isXZOverlapping && isAbove) {
        // 아래로 내림: 삭제된 요소의 크기만큼
        const fallDistance = deletedPlacement.size_y || gridSize;
        const newY = Math.max(halfSize, p.position_y - fallDistance); // 바닥(2.5) 아래로는 안 내려감

        return {
          ...p,
          position_y: newY,
        };
      }

      return p;
    });
  };

  // 요소 삭제 확정 (로컬 상태에서만 삭제, 저장 시 서버에 반영)
  const confirmDeletePlacement = () => {
    const { placementId } = deleteConfirmDialog;
    if (placementId === null) return;

    setPlacements((prev) => {
      const deletedPlacement = prev.find((p) => p.id === placementId);
      if (!deletedPlacement) return prev;

      // 삭제 후 남은 요소들
      const remaining = prev.filter((p) => p.id !== placementId);

      // 중력 적용 (재귀적으로 계속 적용)
      let result = remaining;
      let hasChanges = true;

      // 모든 요소가 안정될 때까지 반복
      while (hasChanges) {
        const before = JSON.stringify(result.map((p) => p.position_y));
        result = applyGravity(deletedPlacement, result);
        const after = JSON.stringify(result.map((p) => p.position_y));
        hasChanges = before !== after;
      }

      return result;
    });

    if (selectedPlacement?.id === placementId) {
      setSelectedPlacement(null);
      setShowConfigPanel(false);
    }
    setHasUnsavedChanges(true);
    setDeleteConfirmDialog({ open: false, placementId: null });
  };

  // 자재 드래그 (3D 캔버스에서, 로컬 상태에만 반영)
  const handlePlacementDrag = (id: number, position: { x: number; y: number; z: number }) => {
    const updatedPosition = {
      position_x: Math.round(position.x * 2) / 2,
      position_y: position.y,
      position_z: Math.round(position.z * 2) / 2,
    };

    setPlacements((prev) => prev.map((p) => (p.id === id ? { ...p, ...updatedPosition } : p)));

    if (selectedPlacement?.id === id) {
      setSelectedPlacement((prev) => (prev ? { ...prev, ...updatedPosition } : null));
    }

    setHasUnsavedChanges(true);
  };

  // 전체 저장 (신규/수정/삭제 모두 처리)
  const handleSave = async () => {
    setIsSaving(true);
    try {
      // 1. 삭제된 요소 처리 (원본에는 있지만 현재 state에 없는 경우)
      const deletedIds = originalPlacements
        .filter((orig) => !placements.find((p) => p.id === orig.id))
        .map((p) => p.id);

      for (const id of deletedIds) {
        await yardLayoutApi.removePlacement(id);
      }

      // 2. 신규 추가 요소 처리 (ID가 음수인 경우)
      const newPlacements = placements.filter((p) => p.id < 0);
      const addedPlacements: YardPlacement[] = [];

      for (const newPlacement of newPlacements) {
        const response = await yardLayoutApi.addMaterialPlacement(layout.id, {
          material_code: newPlacement.material_code,
          material_name: newPlacement.material_name,
          quantity: newPlacement.quantity,
          unit: newPlacement.unit,
          position_x: newPlacement.position_x,
          position_y: newPlacement.position_y,
          position_z: newPlacement.position_z,
          size_x: newPlacement.size_x,
          size_y: newPlacement.size_y,
          size_z: newPlacement.size_z,
          color: newPlacement.color,
          data_source_type: newPlacement.data_source_type,
          data_source_config: newPlacement.data_source_config,
          data_binding: newPlacement.data_binding,
          memo: newPlacement.memo,
        });

        if (response.success) {
          addedPlacements.push(response.data as YardPlacement);
        }
      }

      // 3. 기존 요소 수정 처리 (ID가 양수인 경우)
      const existingPlacements = placements.filter((p) => p.id > 0);

      for (const placement of existingPlacements) {
        await yardLayoutApi.updatePlacement(placement.id, {
          material_code: placement.material_code,
          material_name: placement.material_name,
          quantity: placement.quantity,
          unit: placement.unit,
          position_x: placement.position_x,
          position_y: placement.position_y,
          position_z: placement.position_z,
          size_x: placement.size_x,
          size_y: placement.size_y,
          size_z: placement.size_z,
          color: placement.color,
          data_source_type: placement.data_source_type,
          data_source_config: placement.data_source_config,
          data_binding: placement.data_binding,
          memo: placement.memo,
        });
      }

      // 4. 저장 성공 후 데이터 다시 로드
      const response = await yardLayoutApi.getPlacementsByLayoutId(layout.id);
      if (response.success) {
        const loadedData = response.data as YardPlacement[];
        setPlacements(loadedData);
        setOriginalPlacements(JSON.parse(JSON.stringify(loadedData)));
        setHasUnsavedChanges(false);
        setSelectedPlacement(null);
        setShowConfigPanel(false);
        setSaveResultDialog({
          open: true,
          success: true,
          message: "모든 변경사항이 성공적으로 저장되었습니다.",
        });
      }
    } catch (error) {
      console.error("저장 실패:", error);
      setSaveResultDialog({
        open: true,
        success: false,
        message: `저장에 실패했습니다: ${error instanceof Error ? error.message : "알 수 없는 오류"}`,
      });
    } finally {
      setIsSaving(false);
    }
  };

  // 설정 패널에서 데이터 업데이트 (로컬 상태에만 반영, 서버 저장 안함)
  const handleSaveConfig = (updatedData: Partial<YardPlacement>) => {
    if (!selectedPlacement) return;

    // 로컬 상태만 업데이트
    setPlacements((prev) =>
      prev.map((p) => {
        if (p.id === selectedPlacement.id) {
          return { ...p, ...updatedData };
        }
        return p;
      }),
    );

    // 선택된 요소도 업데이트
    setSelectedPlacement((prev) => (prev ? { ...prev, ...updatedData } : null));
    setShowConfigPanel(false);
    setHasUnsavedChanges(true);
  };

  // 요소가 설정되었는지 확인
  const isConfigured = (placement: YardPlacement): boolean => {
    return !!(placement.material_name && placement.quantity && placement.unit);
  };

  // 레이아웃 편집 Dialog 열기
  const handleEditLayout = () => {
    setEditLayoutDialog({
      open: true,
      name: layout.name,
    });
  };

  // 레이아웃 정보 저장
  const handleSaveLayoutInfo = async () => {
    try {
      const response = await yardLayoutApi.updateLayout(layout.id, {
        name: editLayoutDialog.name,
      });

      if (response.success) {
        // 레이아웃 정보 업데이트
        layout.name = editLayoutDialog.name;
        setEditLayoutDialog({ open: false, name: "" });
      }
    } catch (error) {
      console.error("레이아웃 정보 수정 실패:", error);
      setError("레이아웃 정보 수정에 실패했습니다.");
    }
  };

  return (
    <div className="flex h-full flex-col bg-background">
      {/* 상단 툴바 */}
      <div className="flex items-center justify-between border-b p-4">
        <div className="flex items-center gap-4">
          <Button variant="ghost" size="sm" onClick={onBack}>
            <ArrowLeft className="mr-2 h-4 w-4" />
            목록으로
          </Button>
          <div className="flex items-center gap-2">
            <div>
              <h2 className="text-lg font-semibold">{layout.name}</h2>
              {layout.description && <p className="text-sm text-muted-foreground">{layout.description}</p>}
            </div>
            <Button variant="ghost" size="sm" onClick={handleEditLayout} className="h-8 w-8 p-0">
              <Edit2 className="h-4 w-4 text-muted-foreground" />
            </Button>
          </div>
        </div>

        <div className="flex items-center gap-2">
          {hasUnsavedChanges && <span className="text-sm font-medium text-warning">미저장 변경사항 있음</span>}
          <Button size="sm" onClick={handleSave} disabled={isSaving || !hasUnsavedChanges}>
            {isSaving ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                저장 중...
              </>
            ) : (
              <>
                <Save className="mr-2 h-4 w-4" />
                저장
              </>
            )}
          </Button>
        </div>
      </div>

      {/* 에러 메시지 */}
      {error && (
        <Alert variant="destructive" className="m-4">
          <AlertCircle className="h-4 w-4" />
          <AlertDescription>{error}</AlertDescription>
        </Alert>
      )}

      {/* 메인 컨텐츠 영역 */}
      <div className="flex flex-1 overflow-hidden">
        {/* 좌측: 3D 캔버스 */}
        <div className="flex-1">
          {isLoading ? (
            <div className="flex h-full items-center justify-center bg-muted">
              <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
            </div>
          ) : (
            <Yard3DCanvas
              placements={placements}
              selectedPlacementId={selectedPlacement?.id || null}
              onPlacementClick={(placement) => handleSelectPlacement(placement as YardPlacement | null)}
              onPlacementDrag={handlePlacementDrag}
              focusOnPlacementId={focusPlacementId}
              onCollisionDetected={() => {
                toast({
                  title: "배치 불가",
                  description: "해당 위치에 이미 다른 요소가 있습니다.",
                  variant: "destructive",
                });
              }}
            />
          )}
        </div>

        {/* 우측: 요소 목록 또는 설정 패널 */}
        <div className="w-80 border-l bg-background">
          {showConfigPanel && selectedPlacement ? (
            // 설정 패널
            <YardElementConfigPanel
              placement={selectedPlacement}
              onSave={handleSaveConfig}
              onCancel={() => setShowConfigPanel(false)}
            />
          ) : (
            // 요소 목록
            <div className="flex h-full flex-col">
              <div className="border-b p-4">
                <div className="mb-3 flex items-center justify-between">
                  <h3 className="text-sm font-semibold">요소 목록</h3>
                  <Button size="sm" onClick={handleAddElement}>
                    <Plus className="mr-1 h-4 w-4" />
                    요소 추가
                  </Button>
                </div>
                <p className="text-xs text-muted-foreground">총 {placements.length}개</p>
              </div>

              <div className="flex-1 overflow-auto p-2">
                {placements.length === 0 ? (
                  <div className="flex h-full items-center justify-center p-4 text-center text-sm text-muted-foreground">
                    요소가 없습니다.
                    <br />
                    {'위의 "요소 추가" 버튼을 클릭하세요.'}
                  </div>
                ) : (
                  <div className="space-y-2">
                    {placements.map((placement) => {
                      const configured = isConfigured(placement);
                      const isSelected = selectedPlacement?.id === placement.id;

                      return (
                        <div
                          key={placement.id}
                          className={`rounded-lg border p-3 transition-all ${
                            isSelected
                              ? "border-primary bg-primary/10"
                              : configured
                                ? "border-border bg-background hover:border-border"
                                : "border-warning bg-warning/10"
                          }`}
                          onClick={() => handleSelectPlacement(placement)}
                        >
                          <div className="flex items-start justify-between">
                            <div className="flex-1">
                              {configured ? (
                                <>
                                  <div className="text-sm font-medium text-foreground">{placement.material_name}</div>
                                  <div className="mt-1 text-xs text-muted-foreground">
                                    수량: {placement.quantity} {placement.unit}
                                  </div>
                                </>
                              ) : (
                                <>
                                  <div className="text-sm font-medium text-warning">요소 #{placement.id}</div>
                                  <div className="mt-1 text-xs text-warning">데이터 바인딩 설정 필요</div>
                                </>
                              )}
                            </div>
                          </div>

                          <div className="mt-2 flex gap-1">
                            <Button
                              variant="outline"
                              size="sm"
                              className="flex-1"
                              onClick={(e) => {
                                e.stopPropagation();
                                handleConfigClick(placement);
                              }}
                            >
                              <Settings className="mr-1 h-3 w-3" />
                              {configured ? "편집" : "설정"}
                            </Button>
                            <Button
                              variant="outline"
                              size="sm"
                              className="text-destructive hover:bg-destructive/10"
                              onClick={(e) => {
                                e.stopPropagation();
                                handleDeletePlacement(placement.id);
                              }}
                            >
                              <Trash2 className="h-3 w-3" />
                            </Button>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>
            </div>
          )}
        </div>
      </div>

      {/* 저장 결과 Dialog */}
      <Dialog open={saveResultDialog.open} onOpenChange={(open) => setSaveResultDialog((prev) => ({ ...prev, open }))}>
        <DialogContent onPointerDown={(e) => e.stopPropagation()}>
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              {saveResultDialog.success ? (
                <>
                  <CheckCircle className="h-5 w-5 text-success" />
                  저장 완료
                </>
              ) : (
                <>
                  <AlertCircle className="h-5 w-5 text-destructive" />
                  저장 실패
                </>
              )}
            </DialogTitle>
            <DialogDescription className="pt-2">{saveResultDialog.message}</DialogDescription>
          </DialogHeader>
          <div className="flex justify-end">
            <Button onClick={() => setSaveResultDialog((prev) => ({ ...prev, open: false }))}>확인</Button>
          </div>
        </DialogContent>
      </Dialog>

      {/* 삭제 확인 Dialog */}
      <Dialog
        open={deleteConfirmDialog.open}
        onOpenChange={(open) => !open && setDeleteConfirmDialog({ open: false, placementId: null })}
      >
        <DialogContent onPointerDown={(e) => e.stopPropagation()}>
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <AlertCircle className="h-5 w-5 text-warning" />
              요소 삭제 확인
            </DialogTitle>
            <DialogDescription className="pt-2">
              이 요소를 삭제하시겠습니까?
              <br />
              <span className="font-semibold text-warning">저장 버튼을 눌러야 최종적으로 삭제됩니다.</span>
            </DialogDescription>
          </DialogHeader>
          <div className="flex justify-end gap-2">
            <Button variant="outline" onClick={() => setDeleteConfirmDialog({ open: false, placementId: null })}>
              취소
            </Button>
            <Button onClick={confirmDeletePlacement} className="bg-destructive hover:bg-destructive/90">
              삭제
            </Button>
          </div>
        </DialogContent>
      </Dialog>

      {/* 레이아웃 편집 Dialog */}
      <Dialog
        open={editLayoutDialog.open}
        onOpenChange={(open) => !open && setEditLayoutDialog({ open: false, name: "" })}
      >
        <DialogContent onPointerDown={(e) => e.stopPropagation()}>
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Edit2 className="h-5 w-5 text-primary" />
              야드 레이아웃 정보 수정
            </DialogTitle>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label htmlFor="layout-name">레이아웃 이름</Label>
              <Input
                id="layout-name"
                value={editLayoutDialog.name}
                onChange={(e) => setEditLayoutDialog((prev) => ({ ...prev, name: e.target.value }))}
                placeholder="레이아웃 이름을 입력하세요"
              />
            </div>
          </div>
          <div className="flex justify-end gap-2">
            <Button variant="outline" onClick={() => setEditLayoutDialog({ open: false, name: "" })}>
              취소
            </Button>
            <Button onClick={handleSaveLayoutInfo} disabled={!editLayoutDialog.name.trim()}>
              저장
            </Button>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
