"use client";

import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { ArrowLeft, Save, Loader2, Plus, Settings, Trash2 } 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 } from "lucide-react";

const Yard3DCanvas = dynamic(() => import("./Yard3DCanvas"), {
  ssr: false,
  loading: () => (
    <div className="flex h-full items-center justify-center bg-gray-900">
      <Loader2 className="h-8 w-8 animate-spin text-gray-400" />
    </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 [placements, setPlacements] = useState<YardPlacement[]>([]);
  const [selectedPlacement, setSelectedPlacement] = useState<YardPlacement | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [showConfigPanel, setShowConfigPanel] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // 배치 목록 로드
  useEffect(() => {
    const loadPlacements = async () => {
      try {
        setIsLoading(true);
        const response = await yardLayoutApi.getPlacementsByLayoutId(layout.id);
        if (response.success) {
          setPlacements(response.data as YardPlacement[]);
        }
      } catch (error) {
        console.error("배치 목록 로드 실패:", error);
        setError("배치 목록을 불러올 수 없습니다.");
      } finally {
        setIsLoading(false);
      }
    };

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

  // 빈 요소 추가
  const handleAddElement = async () => {
    try {
      const newPlacementData = {
        position_x: 0,
        position_y: 0,
        position_z: 0,
        size_x: 5,
        size_y: 5,
        size_z: 5,
        color: "#9ca3af", // 회색 (미설정 상태)
      };

      console.log("요소 추가 요청:", { layoutId: layout.id, data: newPlacementData });
      const response = await yardLayoutApi.addMaterialPlacement(layout.id, newPlacementData);
      console.log("요소 추가 응답:", response);

      if (response.success) {
        const newPlacement = response.data as YardPlacement;
        setPlacements((prev) => [...prev, newPlacement]);
        setSelectedPlacement(newPlacement);
        setShowConfigPanel(true); // 자동으로 설정 패널 표시
      } else {
        console.error("요소 추가 실패 (응답):", response);
        setError(response.message || "요소 추가에 실패했습니다.");
      }
    } catch (error) {
      console.error("요소 추가 실패 (예외):", error);
      setError(`요소 추가에 실패했습니다: ${error instanceof Error ? error.message : String(error)}`);
    }
  };

  // 요소 선택 (3D 캔버스 또는 목록에서)
  const handleSelectPlacement = (placement: YardPlacement) => {
    setSelectedPlacement(placement);
    setShowConfigPanel(false); // 선택 시에는 설정 패널 닫기
  };

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

  // 요소 삭제
  const handleDeletePlacement = async (placementId: number) => {
    if (!confirm("이 요소를 삭제하시겠습니까?")) {
      return;
    }

    try {
      const response = await yardLayoutApi.removePlacement(placementId);
      if (response.success) {
        setPlacements((prev) => prev.filter((p) => p.id !== placementId));
        if (selectedPlacement?.id === placementId) {
          setSelectedPlacement(null);
          setShowConfigPanel(false);
        }
      }
    } catch (error) {
      console.error("요소 삭제 실패:", error);
      setError("요소 삭제에 실패했습니다.");
    }
  };

  // 자재 드래그 (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));
    }
  };

  // 저장
  const handleSave = async () => {
    setIsSaving(true);
    try {
      const response = await yardLayoutApi.batchUpdatePlacements(
        layout.id,
        placements.map((p) => ({
          id: p.id,
          position_x: p.position_x,
          position_y: p.position_y,
          position_z: p.position_z,
          size_x: p.size_x,
          size_y: p.size_y,
          size_z: p.size_z,
          color: p.color,
        })),
      );

      if (response.success) {
        alert("저장되었습니다");
      }
    } catch (error) {
      console.error("저장 실패:", error);
      alert("저장에 실패했습니다");
    } finally {
      setIsSaving(false);
    }
  };

  // 설정 패널에서 저장
  const handleSaveConfig = async (updatedData: Partial<YardPlacement>) => {
    if (!selectedPlacement) return;

    try {
      const response = await yardLayoutApi.updatePlacement(selectedPlacement.id, updatedData);
      if (response.success) {
        const updated = response.data as YardPlacement;

        // 현재 위치 정보를 유지하면서 업데이트
        setPlacements((prev) =>
          prev.map((p) => {
            if (p.id === updated.id) {
              // 현재 프론트엔드 상태의 위치를 유지
              return {
                ...updated,
                position_x: p.position_x,
                position_y: p.position_y,
                position_z: p.position_z,
              };
            }
            return p;
          }),
        );

        // 선택된 요소도 동일하게 업데이트
        setSelectedPlacement({
          ...updated,
          position_x: selectedPlacement.position_x,
          position_y: selectedPlacement.position_y,
          position_z: selectedPlacement.position_z,
        });

        setShowConfigPanel(false);
      }
    } catch (error) {
      console.error("설정 저장 실패:", error);
      setError("설정 저장에 실패했습니다.");
    }
  };

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

  return (
    <div className="flex h-full flex-col bg-white">
      {/* 상단 툴바 */}
      <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>
            <h2 className="text-lg font-semibold">{layout.name}</h2>
            {layout.description && <p className="text-sm text-gray-500">{layout.description}</p>}
          </div>
        </div>

        <Button size="sm" onClick={handleSave} disabled={isSaving}>
          {isSaving ? (
            <>
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              저장 중...
            </>
          ) : (
            <>
              <Save className="mr-2 h-4 w-4" />
              저장
            </>
          )}
        </Button>
      </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-gray-50">
              <Loader2 className="h-8 w-8 animate-spin text-gray-400" />
            </div>
          ) : (
            <Yard3DCanvas
              placements={placements}
              selectedPlacementId={selectedPlacement?.id || null}
              onPlacementClick={(placement) => handleSelectPlacement(placement as YardPlacement)}
              onPlacementDrag={handlePlacementDrag}
            />
          )}
        </div>

        {/* 우측: 요소 목록 또는 설정 패널 */}
        <div className="w-80 border-l bg-white">
          {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-gray-500">총 {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-gray-500">
                    요소가 없습니다.
                    <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-blue-500 bg-blue-50"
                              : configured
                                ? "border-gray-200 bg-white hover:border-gray-300"
                                : "border-orange-200 bg-orange-50"
                          }`}
                          onClick={() => handleSelectPlacement(placement)}
                        >
                          <div className="flex items-start justify-between">
                            <div className="flex-1">
                              {configured ? (
                                <>
                                  <div className="text-sm font-medium text-gray-900">{placement.material_name}</div>
                                  <div className="mt-1 text-xs text-gray-500">
                                    수량: {placement.quantity} {placement.unit}
                                  </div>
                                </>
                              ) : (
                                <>
                                  <div className="text-sm font-medium text-orange-700">요소 #{placement.id}</div>
                                  <div className="mt-1 text-xs text-orange-600">데이터 바인딩 설정 필요</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-red-600 hover:bg-red-50"
                              onClick={(e) => {
                                e.stopPropagation();
                                handleDeletePlacement(placement.id);
                              }}
                            >
                              <Trash2 className="h-3 w-3" />
                            </Button>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
