import { $, component$, useSignal, useVisibleTask$} from "@builder.io/qwik";
import { DocumentHead } from "@builder.io/qwik-city";
import RoomGrid from "~/components/room/RoomGrid";
import { typechecker } from "~/utils/func";
import { routeLoader$ } from "@builder.io/qwik-city";
import axios from "axios";
import { getCookie } from "~/utils/cookie";
interface Furniture {
    furniture_name: string;
    image_path: string;
    x : number;
    y : number;
}
interface SendFurniture {
  
  name: string;
  image_path : string;

}
// interface Avatar {
//     id: number;
//     user_id: number;
//     avatar_type: {
//         name: string;
//         path: string
//     },
//     top_clothe_type: {
//         name: string;
//         path: string
//     },
//     bottom_clothe_type: {
//         name: string;
//         path: string
//     }
// }
interface SetAvatarType {
    avatar_type: string;
    top_clothe_type: string;
    bottom_clothe_type: string;
}
interface RoomType {
    type: string;
    image_path: string;
}

// interface Room {
//     id: number;
//     user_id: number;
//     room_type: string;
//     room_name: string;
//     room_image_path: string;
// }
export const useRoomLoader = routeLoader$(async ({cookie}) => {
    const headers = {
        Authorization: `Bearer ${cookie.get("access_token")?.value}`,
    }
    try {
        const [myRoom, myAvatar, roomType, furniture, avatarType] = await Promise.all([
            axios.get("http://localhost:8000/api/room/layout", { headers }),
            axios.get("http://localhost:8000/api/avatar", { headers }),
            axios.get("http://localhost:8000/api/room/types", { headers }),
            axios.get("http://localhost:8000/api/room/my", { headers }),
            axios.get("http://localhost:8000/api/avatar/options", { headers }),
          ]);
        return {myData : {room: myRoom.data, avatar: myAvatar.data}, selectionData: {roomType: roomType.data, furniture: furniture.data, avatarType: avatarType.data}};
    } catch (error : any) {
        console.error(error);
        return error.response?.data?.detail || 'Room not found';
    }
})
export default component$(() => {
    const data = useRoomLoader();
    // const navigate = useNavigate();
    const reloadPage = $(() => {
      window.location.reload();
    });
    // 1. 소유한 가구 데이터 (layout API에서 가져옴)
    const ownedFurnitures = useSignal<SendFurniture[]>([]);
    // 2. 현재 배치된 가구 데이터 (room/my API에서 가져옴)
    const placedFurnitures = useSignal<Furniture[]>([]);
    // 3. 현재 선택된 가구 (새로 배치하려는 가구만) - 제거
    // const selectedFurniture = useSignal<Furniture | null>(null);
     
    const selectedType = useSignal<"furniture" | "avatar" | "background">("furniture");
    // const editingPosition = useSignal<number | null>(null);
    const selectedRoomType = useSignal("room_1");
    const selectedAvatar = useSignal<SetAvatarType>({
        avatar_type: "",
        top_clothe_type: "",
        bottom_clothe_type: ""
    });
    const mergedFurnitures = useSignal<Furniture[]>([] as Furniture[]);
    // 오류 상태 관리
    const errorMessage = useSignal<string>("");
    const successMessage = useSignal<string>("");
    useVisibleTask$(async () => {
        // 기본 데이터 설정
        selectedRoomType.value = data.value.myData.room.room.room_type;
        selectedAvatar.value.avatar_type = data.value.myData.avatar.avatar_type.name;
        selectedAvatar.value.top_clothe_type = data.value.myData.avatar.top_clothe_type.name;
        selectedAvatar.value.bottom_clothe_type = data.value.myData.avatar.bottom_clothe_type.name;
        ownedFurnitures.value = data.value.selectionData.furniture;
        placedFurnitures.value = [...data.value.myData.room.furniture];
        mergedFurnitures.value = ownedFurnitures.value.map(o => {
          const placed = placedFurnitures.value.find(p => p.furniture_name === o.name);
          return placed 
            ? placed
            : {
                furniture_name: o.name,
                image_path: o.image_path,
                x: -1,
                y: -1,
              };
        });
        
    })
    // 가구 배치 함수
    const placeFurniture = $(async (furniture: Furniture, x: number, y: number) => {
        try {
            await axios.post("http://localhost:8000/api/room/furniture", {
                furniture_name: furniture.furniture_name,
                x: x,
                y: y
            }, {
                headers: { Authorization: `Bearer ${getCookie("access_token")}` }
            });
            
            // 성공 시 placedFurnitures에 추가
            if (!mergedFurnitures.value.find(f => f.furniture_name === furniture.furniture_name)) {
            mergedFurnitures.value = Array.from(new Set([
              ...mergedFurnitures.value, 
              {
                furniture_name: furniture.furniture_name,  // SendFurniture has 'name' property
                image_path: furniture.image_path,
                x: x,
                y: y
              }
            ]));
        
            placedFurnitures.value = Array.from(new Set([...placedFurnitures.value, furniture]));
            }
            else {
              mergedFurnitures.value =Array.from(new Set([...mergedFurnitures.value]));
              placedFurnitures.value = Array.from(new Set([...placedFurnitures.value]));
            }
            console.log('Placed fu  rniture:', mergedFurnitures.value);
            
            return true;
        } catch (error: any) {
            console.error('가구 배치 실패:', error);
            errorMessage.value = error.response.data.detail;
            setTimeout(() => { errorMessage.value = ""; }, 10000);
            return false;
        }
    });

    // 가구 제거 함수
    const removeFurniture = $(async (furniture: Furniture) => {
        console.log(furniture + " furniture");
        try {
            await axios.delete(`http://localhost:8000/api/room/furniture?x=${furniture.x}&y=${furniture.y}&furniture_name=${furniture.furniture_name}`, {
                headers: { Authorization: `Bearer ${getCookie("access_token")}` }
            });
            
            placedFurnitures.value = Array.from(new Set([...placedFurnitures.value.filter(f => 
                f.furniture_name !== furniture.furniture_name && (f.x !== furniture.x || f.y !== furniture.y)
            )]));
            mergedFurnitures.value = Array.from(new Set([...mergedFurnitures.value.map(f => 
              f.furniture_name === furniture.furniture_name 
                ? { ...f, x: -1, y: -1 } 
                : f
            )]));
            return true;
        } catch (error: any) {
            console.error('가구 제거 실패:', error);
            errorMessage.value = `${furniture.furniture_name} 제거에 실패했습니다.`;
            setTimeout(() => { errorMessage.value = ""; }, 10000);
            return false;
        }
    });

    // 가구 위치 업데이트 함수
    const updateFurniturePosition = $(async (furniture:Furniture, newX: number, newY: number) => {
      if ((newX < 0 || newX >= 10) || (newY < 0 || newY >= 10)) {
        errorMessage.value = "위치가 이상합니다.";
        console.log(newX, newY);
        setTimeout(() => { errorMessage.value = ""; }, 10000);
        return false;
      }  
      try {
          
            const foundedFurniture = mergedFurnitures.value.find(f => f.x === newX && f.y === newY)
            if (foundedFurniture) {
                await removeFurniture(foundedFurniture);
            }
            //같은 이름으 가구가 이미 있나
            console.log(placedFurnitures.value, furniture + " furniture");
            const foundedFurniture2 = placedFurnitures.value.find(f => f.furniture_name === furniture.furniture_name)
            if (foundedFurniture2) {
                await removeFurniture(foundedFurniture2);
            }
            // 새 위치에 가구 배치
            console.log(furniture + " 가구 움직임");
            await placeFurniture(furniture, newX, newY);
            
            return true;
        } catch (error: any) {
            console.error('가구 위치 업데이트 실패:', error);
            return false;
        }
        
    });

  
    const handleChange = $( async () => {
        try {
            await axios.patch("http://localhost:8000/api/room/", {type: selectedRoomType.value}, {headers: {Authorization: `Bearer ${getCookie("access_token")}`}});
            await axios.put("http://localhost:8000/api/avatar", {avatar_type: selectedAvatar.value.avatar_type,top_clothe_type: selectedAvatar.value.top_clothe_type,bottom_clothe_type: selectedAvatar.value.bottom_clothe_type,}, {headers: {Authorization: `Bearer ${getCookie("access_token")}`}});
            
          } catch (error) {console.log(error);}
    })
    return (
        <div class="flex flex-col h-full p-4">
          <div class="flex flex-row justify-between items-center mb-4">
            <h1 class="text-2xl font-bold text-[#4b3c28]">내 방 꾸미기</h1>
            
            {/* 오류 메시지 표시 */}
            {errorMessage.value && (
                <div class="px-2 bg-red-100 border border-red-400 text-red-700 rounded-lg">
                    {errorMessage.value?errorMessage.value:"  "} 
                </div>
            )}
            
            {/* 성공 메시지 표시 */}
            {successMessage.value && (
                <div class=" bg-green-100 border border-green-400 text-green-700 rounded-lg">
                    {successMessage.value?successMessage.value:"  "} 
                </div>
            )}
            
          </div>
            
            <div class="flex flex-col md:flex-row gap-6 flex-1">
                {/* Room Preview */}
                <div class="flex-1 bg-white rounded-xl border border-gray-200 p-4">
                    <div class="h-full flex items-center justify-center">
                      
                        <RoomGrid 
                            furnitures={placedFurnitures} 
                            avatars={selectedAvatar}  
                            roomSrc={selectedRoomType} 
                        />
                    </div>
                </div>
            
                {/* Controls */}
                <div class="w-full md:w-80 flex flex-col gap-4">
                    {/* Category Tabs */}
                    <div class="flex gap-1 bg-gray-100 p-1 rounded-lg">
                        <button 
                            onClick$={() => { selectedType.value = "furniture" }}
                            class={`flex-1 py-2 px-3 text-sm rounded-md font-medium transition-colors ${
                                selectedType.value === "furniture" 
                                    ? "bg-white text-[#4b3c28] shadow-sm" 
                                    : "text-gray-600 hover:bg-gray-50"
                            }`}
                        >
                            가구
                        </button>
                        <button 
                            onClick$={() => { selectedType.value = "avatar" }}
                            class={`flex-1 py-2 px-3 text-sm rounded-md font-medium transition-colors ${
                                selectedType.value === "avatar" 
                                    ? "bg-white text-[#4b3c28] shadow-sm" 
                                    : "text-gray-600 hover:bg-gray-50"
                            }`}
                        >
                            아바타
                        </button>
                        <button 
                            onClick$={() => { selectedType.value = "background" }}
                            class={`flex-1 py-2 px-3 text-sm rounded-md font-medium transition-colors ${
                                selectedType.value === "background" 
                                    ? "bg-white text-[#4b3c28] shadow-sm" 
                                    : "text-gray-600 hover:bg-gray-50"
                            }`}
                        >
                             배경
                        </button>
                    </div>

                {/* Items Grid */}
                <div class="flex flex-col h-[600px] bg-white border-2 border-[#FAD659] rounded-lg overflow-hidden">
                    <h3 class="text-lg font-semibold p-4 text-[#4b3c28] border-b border-gray-200">
                        {selectedType.value === "furniture" ? "가구" : 
                         selectedType.value === "avatar" ? "아바타" : "배경"} 선택
                    </h3>
                    
                    <div class="flex-1 overflow-y-auto p-4">
                        <div class="flex flex-col gap-3">
                        {selectedType.value === "furniture" ? (
                            <div class="space-y-4">
                              {/* 배치된 가구 목록 - 각각 입력창 표시 */}
                              <div class="space-y-3">
                                {mergedFurnitures.value.map((furniture: Furniture) => (
                                  <div key={`${furniture.furniture_name}-${furniture.x}-${furniture.y}`} class="bg-white border border-text-default rounded-lg p-4">
                                    <div class="flex items-center gap-3 mb-3">
                                      <img 
                                        src={`http://localhost:8000/${furniture.image_path}`} 
                                        alt={furniture.furniture_name} 
                                        style={{imageRendering: "pixelated"}} 
                                        class="object-contain w-12 h-12"
                                      />
                                      <div>
                                        <h5 class="font-medium text-text-default">
                                          {furniture.furniture_name}
                                        </h5>
                                        {furniture.x !== -1 && furniture.y !== -1 && (
                                        <p class="text-sm text-diary-icon-hover">
                                          현재 위치: ({furniture.x}, {furniture.y})
                                        </p>
                                        )}
                                      </div>
                                      {furniture.x !== -1 && furniture.y !== -1 && (
                                        <button 
                                          onClick$={() => {removeFurniture(furniture); reloadPage();}}
                                          class="ml-auto px-3 py-1 bg-button-color-2 text-white text-sm rounded hover:bg-button-color-2-hover"
                                        >
                                          제거
                                        </button>
                                      ) 
                                      }
                                    </div>
                                    
                                    {/* 위치 수정 입력창 */}
                                    <div class="flex gap-3 items-center">
                                      <label class="text-sm font-medium text-green-900">X:</label>
                                      <input 
                                        type="number" 
                                        min="0" 
                                        max="9" 
                                        value={furniture.x === -1 ? 1 : furniture.x}
                                        onInput$={
                                          (e) => {
                                            furniture.x = parseInt((e.target as HTMLInputElement).value);
                                          }
                                        }
                                        class="w-16 px-2 py-1 text-center border rounded"
                                      />
                                      <label class="text-sm font-medium text-green-900">Y:</label>
                                      <input 
                                        type="number" 
                                        min="0" 
                                        max="9"
                                        value={furniture.y === -1 ? 1 : furniture.y} 
                                        onInput$={
                                          (e) => {
                                            furniture.y = parseInt((e.target as HTMLInputElement).value);
                                          }
                                        }
                                        class="w-16 px-2 py-1 text-center border rounded"
                                      />
                                      
                                      <button 
                                        onClick$={() => {updateFurniturePosition(furniture, furniture.x === -1 ? 1 : furniture.x, furniture.y === -1 ? 1 : furniture.y); reloadPage();}}
                                        class="ml-auto px-3 py-1 bg-button-color-2 text-white text-sm rounded hover:bg-button-color-2-hover"
                                      >
                                        추가
                                      </button>
                                    </div>
                                  </div>
                                ))}

                                {/* 배치된 가구가 없을 때 */}
                                {ownedFurnitures.value.length === 0 && (
                                  <div class="text-center py-8 text-gray-500">
                                    <p>가구가 없습니다.</p>
                                    <p class="text-sm">가구를 배치하려면 상점에서 가구를 구매하세요.</p>
                                  </div>
                                )}
                              </div>
                            </div>
                            ) :
                            selectedType.value === "avatar" ? (
                              <div class="flex flex-col gap-3 ">
                                <div>
                                  <h4 class="font-medium text-gray-700 mb-2">아바타 타입</h4>
                                  <div class="grid grid-cols-3 gap-3">
                                    {data.value.selectionData.avatarType.avatar_types.map((type: string, index: number) => (
                                      <div 
                                        key={`type-${index}`}
                                        class={`flex flex-col items-center p-2 rounded-lg hover:bg-gray-100 cursor-pointer ${selectedAvatar.value.avatar_type === type ? "border-[2px] border-[#FAD659]" : "border-2 border-gray-200"}`}
                                        onClick$={() => {
                                            selectedAvatar.value = {
                                                ...selectedAvatar.value,
                                                avatar_type: type
                                            };
                                            console.log(selectedAvatar.value.avatar_type)}}
                                      >
                                        <div class="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mb-1 overflow-hidden border-2 border-gray-200 hover:border-[#FAD659] transition-colors">
                                          <img src={`http://localhost:8000/${typechecker(type)}`} alt="avatar" style={{imageRendering: "pixelated"}} class="object-contain w-16 h-16" />
                                        </div>
                                        <span class="text-xs text-gray-700">{type}</span>
                                      </div>
                                    ))}
                                  </div>
                                </div>

                                <div>
                                  <h4 class="font-medium text-gray-700 mb-2">상의</h4>
                                  <div class="grid grid-cols-3 gap-3">
                                    {data.value.selectionData.avatarType.top_clothe_types.map((clothe: string, index: number) => (
                                      <div 
                                        key={`top-${index}`}
                                        class={`flex flex-col items-center p-2 rounded-lg hover:bg-gray-100 cursor-pointer ${selectedAvatar.value.top_clothe_type === clothe ? "border-[2px] border-[#FAD659]" : "border-2 border-gray-200"}`}
                                        onClick$={() => {
                                            selectedAvatar.value = {
                                                ...selectedAvatar.value,
                                                top_clothe_type: clothe
                                            };
                                            console.log(selectedAvatar.value.top_clothe_type)}}

                                      >
                                        <div class="w-20 h-20 bg-gray-50 rounded-lg flex items-center justify-center mb-2 overflow-hidden border-2 border-gray-200 hover:border-[#FAD659] transition-colors">
                                          <img src={`http://localhost:8000/${typechecker(clothe)}`} alt="avatar" style={{imageRendering: "pixelated"}} class="object-contain w-16 h-16" />
                                        </div>
                                        <span class="text-xs text-gray-700 text-center">{clothe}</span>
                                      </div>
                                    ))}
                                  </div>
                                </div>

                                <div>
                                  <h4 class="font-medium text-gray-700 mb-2">하의</h4>
                                  <div class="grid grid-cols-3 gap-3">
                                    {data.value.selectionData.avatarType.bottom_clothe_types.map((bottom: string, index: number) => (
                                      <div 
                                        key={`bottom-${index}`}
                                        class={`flex flex-col items-center p-2 rounded-lg hover:bg-gray-100 cursor-pointer ${selectedAvatar.value.bottom_clothe_type === bottom ? "border-[2px] border-[#FAD659]" : "border-2 border-gray-200"}`}
                                        onClick$={() => {
                                            selectedAvatar.value = {
                                                ...selectedAvatar.value,
                                                bottom_clothe_type: bottom
                                            };
                                            console.log(selectedAvatar.value.bottom_clothe_type)}}
                                      >
                                        <div class="w-20 h-20 bg-gray-50 rounded-lg flex items-center justify-center mb-2 overflow-hidden border-2 border-gray-200 hover:border-[#FAD659] transition-colors">
                                          <img src={`http://localhost:8000/${typechecker(bottom)}`} alt="avatar" style={{imageRendering: "pixelated"}} class="object-contain w-full h-full" />
                                        </div>
                                        <span class="text-xs text-gray-700 text-center">{bottom}</span>
                                      </div>
                                    ))}
                                  </div>
                                </div>
                              </div>
                            ) : (
                                <div class="space-y-4 w-full">
                                  <h4 class="font-medium text-gray-700 mb-2">방 배경 선택</h4>
                                  <div class="grid grid-cols-3 gap-4">
                                    {data.value.selectionData.roomType.map((roomType: RoomType, index: number) => (
                                      <div 
                                        key={`room-${index}`}
                                        class="flex flex-col w-full items-center p-3 rounded-lg hover:bg-gray-50 cursor-pointer border-2 border-gray-200 hover:border-[#FAD659] transition-colors bg-white shadow-sm hover:shadow-md"
                                        onClick$={() => {
                                          console.log('Selected room type:', roomType);
                                          selectedRoomType.value = roomType.type;
                                        }}
                                      >
                                        <img 
                                          src={`http://localhost:8000/${roomType.image_path}`}
                                          alt={roomType.type}
                                          class="w-full h-20 object-cover rounded mb-2"
                                        />
                                        <span class="text-sm font-medium text-gray-700">
                                          {roomType.type}
                                        </span>
                                      </div>
                                    ))}
                                  </div>
                                </div>
                            )
                        }
                    </div>
                </div>

                {/* Action Buttons */}
                <div class="flex gap-2">
                    <button 
                        class="flex-1 bg-[#FAD659] hover:bg-[#f8ce3a] text-[#4b3c28] font-bold py-2 px-4 rounded-lg transition-colors"
                        onClick$={(e) => { if (selectedType.value === "furniture") {
                          e.preventDefault();
                      } else {
                          handleChange();
                          reloadPage();
                      }}}
                    >
                        {selectedType.value === "furniture" ? "가구를 배치해보세요" : "아바타 & 배경 저장하기"}
                    </button>
                    {/* <button 
                        class="flex-1 bg-gray-200 hover:bg-gray-300 text-gray-700 font-bold py-2 px-4 rounded-lg transition-colors"
                        onClick$={() => {handleCancel()}}
                    >
                        취소
                    </button> */}
                </div>
            </div>
        </div>
    </div>
    </div>
    );
});

export const head: DocumentHead = {
    title: "Room",
    meta: [
        {
            name: "description",
            content: "Room page description",
        },
    ],
};
