import { $, component$, useSignal, useStylesScoped$, Signal, useVisibleTask$} from "@builder.io/qwik";
import { typechecker } from "~/utils/func";

interface FurnitureItem {
  name: string;
  image_path: string;
  x: number;
  y: number;
}

export default component$(({ furniture, avatar, roomType }: { furniture: Signal<any>, avatar: Signal<any>, roomType: Signal<string> }) => {
  useStylesScoped$(STYLES); 
  // 가구 아이템 상태 관리
  const checkedAvatar = useSignal({
    avatar_type: "",
    top_clothe_type: "",
    bottom_clothe_type: ""
  });
  const furnitureItems = useSignal<FurnitureItem[]>([]);
  useVisibleTask$(({ track }) => {
    track(() => avatar.value);
    console.log(avatar.value);
    checkedAvatar.value = {
    ...avatar.value,
    avatar_type: typechecker(avatar.value.avatar_type),
    top_clothe_type: typechecker(avatar.value.top_clothe_type),
    bottom_clothe_type: typechecker(avatar.value.bottom_clothe_type),
    };
    furnitureItems.value = [furniture.value];
  console.log(checkedAvatar.value);
  })
  // const furnitureItems = useSignal<FurnitureItem[]>([
  //   { 
  //     name: '큰 식물1', 
  //     image_path: 'public/funiture/큰 식물.png',
  //     x: 1,
  //     y: 1
  //   },
  //   { 
  //     name: '녹색 침대1', 
  //     image_path: 'public/funiture/녹색 침대-90.png',
  //     x: 3,
  //     y: 3
  //   },
  //   { 
  //     name: '쓰레기통열림1', 
  //     image_path: 'public/funiture/쓰레기통열림.png',
  //     x: 5,
  //     y: 5
  //   },
  //   { 
  //     name: '어항2', 
  //     image_path: 'public/funiture/어항-0.png',
  //     x: 7,
  //     y: 7
  //   }
  // ]);

  // 현재 드래그 중인 가구
  // const draggedItem = useSignal<FurnitureItem | null>(null);
  // // 드래그 시작 시 호출
  // const handleDragStart = $((item: FurnitureItem, e: Event) => {
  //   e.preventDefault();
  //   draggedItem.value = item;
  // });
  
  // 드래그 오버 시 기본 동작 방지
  const handleDragOver = $((e: Event) => {
    e.preventDefault();
  });
  
  // 셀 클릭 시 호출
  const handleCellClick = $((x: number, y: number, e: Event) => {
    e.preventDefault();
    console.log(`Cell clicked: (${x}, ${y})`);
    furnitureItems.value = furnitureItems.value.map(item => 
      item.name === furniture.value?.name
        ? { ...item, x: x, y: y }
        : item
    );
    // draggedItem.value = null;
  });

  // 드롭 시 호출
  // const handleDrop = $((cellX: number, cellY: number, e: Event) => {
  //   e.preventDefault();
  //   if (!draggedItem.value) return;

  //   // 이미 해당 위치에 다른 가구가 있는지 확인
  //   const isOccupied = furnitureItems.value.some(
  //     item => item.x === cellX && item.y === cellY
  //   );

  //   if (!isOccupied) {
  //     // 가구 위치 업데이트
  //     furnitureItems.value = furnitureItems.value.map(item => 
  //       item.name === draggedItem.value?.name
  //         ? { ...item, x: cellX, y: cellY }
  //         : item
  //     );
  //   }
    
  //   draggedItem.value = null;
  // });


  // 10x10 그리드 셀 생성
  const gridCells = Array.from({ length: 100 }, (_, i) => {
    const row = Math.floor(i / 10) + 1; // 1-10
    const col = (i % 10) + 1; // 1-10
    
    // 해당 위치의 가구 찾기
    const furniture = furnitureItems.value.find(item => item.x === col && item.y === row);
    
    return {
      x: col,
      y: row,
      furniture: furniture ? {
        name: furniture.name,
        src: furniture.image_path,
      } : null
    };
  });


  return (
    <div class="room-wrapper">
      <img 
        src={`http://localhost:8000/public/room/${roomType.value}.png`} 
        class="room" 
        alt="Room background"
      />
      
      {/* Grid overlay */}
      <div class="grid-overlay ">
        {gridCells.map((cell) => (
          <div 
            key={`${cell.x}-${cell.y}`} 
            class="grid-cell"
            // onDragOver$={handleDragOver}
            // onDrop$={ e => handleDrop(cell.x, cell.y, e)}
            onClick$={ e => handleCellClick(cell.x, cell.y, e)}
          >
            {cell.furniture && (
              <img 
                src={`http://localhost:8000/${cell.furniture.src}`} 
                alt={cell.furniture.name}
                // draggable
                // onDragStart$={ e => handleDragStart(furnitureItems.value.find(f => f.name === cell.furniture?.name)!, e)}
              />
            )}
          </div>
        ))}
      </div>

      {/* Avatar */}
      <div class="avatar-wrapper">
          <img 
            src={`http://localhost:8000/${checkedAvatar.value.avatar_type}`} 
            alt={checkedAvatar.value.avatar_type}
          /> 
          <img 
            src={`http://localhost:8000/${checkedAvatar.value.top_clothe_type}`} 
            alt={checkedAvatar.value.top_clothe_type}
          />
          <img 
            src={`http://localhost:8000/${checkedAvatar.value.bottom_clothe_type}`} 
            alt={checkedAvatar.value.bottom_clothe_type}
          />
      </div>
    </div>
  );
});

const STYLES = `
.room-wrapper {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.room {
  width: 100%;
  height: 100%;
  object-fit: cover;
}


.avatar-wrapper {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  pointer-events: none;
}

.avatar-wrapper img {
  position: absolute;
  top: 0;
  left: 0;
  width: 75px;
  height: 100px;
  object-fit: contain;
  image-rendering: pixelated;
}

.room-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 700px;
  height: 700px;
  position: relative;
}

.room {
  position: absolute;
  z-index: 1 !important;
  width: 100%;
  height: 100%;
  image-rendering: pixelated;
  border-radius: 0.5rem;
}

/* Grid */
.grid-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 700px;
  height: 700px;
  display: grid;
  grid-template-columns: repeat(10, 1fr);
  grid-template-rows: repeat(10, 1fr);
  z-index: 2;
  
}

.grid-overlay div {
  box-sizing: border-box;
  position: relative;
}

.grid-overlay > div {
  position: relative;
  height: 70px;
  width: 100%;
  overflow: visible;
}

.grid-overlay > div img {
  pointer-events: none;
  user-select: none;
  -webkit-user-drag: none;
}

.avatar-wrapper {
  width: 200px;
  height: 200px;
  position: absolute;
  top: 70%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 99;
}
.grid-overlay div#oneone>img {
      width: 70px;
      image-rendering: pixelated;
      position: absolute;
      bottom: 0;
    }
.grid-overlay div#twoone>img {
  width: 140px;
  image-rendering: pixelated;
  position: absolute;
  transform: translate(-50%, -50%);
}
.avatar-wrapper img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  image-rendering: pixelated;
  z-index: 99;
}
`;
