import { $, component$, useSignal, useTask$, 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 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 selectedFurnitures = useSignal<Array<Furniture & {x?: number, y?: number}>>([]);
     
    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: ""
    });
    useVisibleTask$(() => {
        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;

    })
    const deleteFurniture = $(async (selectedFurniture : Furniture) => {
        try {
        await axios.delete(`http://localhost:8000/api/room/furniture?x=${selectedFurniture.x}&y=${selectedFurniture.y}&furniture_name=${selectedFurniture.furniture_name}`, {headers: {Authorization: `Bearer ${getCookie("access_token")}`}});
          selectedFurnitures.value = selectedFurnitures.value.filter((f : Furniture) => f.furniture_name !== selectedFurniture.furniture_name);
        } catch (error : any) {console.error(error);}
    })
    const addFurniture = $(async (selectedFurniture : Furniture) => {
        try { await axios.post("http://localhost:8000/api/room/furniture", {furniture_name: selectedFurniture.furniture_name,x: selectedFurniture.x,y: selectedFurniture.y,},        { headers: {       Authorization: `Bearer ${getCookie("access_token")}`,},},)
        } catch (error : any) {console.error(error);}
    })
    useTask$(({track}) => {
        track(() => selectedFurnitures.value);
        try {
            for (let i = 0; i < selectedFurnitures.value.length; i++) {
                if(data.value.myData.room.room.furniture.some((f : Furniture) => f.furniture_name === selectedFurnitures.value[i].furniture_name)) {deleteFurniture(selectedFurnitures.value[i]);}
                else {   addFurniture(selectedFurnitures.value[i]);}
            }
        } catch (error : any) {console.error(error);}
    })
  
    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">
            <h1 class="text-2xl font-bold text-[#4b3c28] mb-6">내 방 꾸미기</h1>
            <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 furniture={selectedFurnitures} avatar={selectedAvatar}  roomType={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" ? (
                            data.value.selectionData.furniture.map((furniture: Furniture) => {
                              const isSelected = selectedFurnitures.value.some(f => f.furniture_name === furniture.furniture_name);
                              const selectedItem = selectedFurnitures.value.find(f => f.furniture_name === furniture.furniture_name);
                              
                              return (
                                <div key={furniture.furniture_name} class="flex flex-col items-center gap-2">
                                  <div 
                                    class={`flex flex-col items-center gap-2 rounded-t-lg ${isSelected ? 'ring-2 ring-yellow-400' : ''}`}
                                    onClick$={() => {
                                      if (isSelected) {
                                        selectedFurnitures.value = selectedFurnitures.value.filter(
                                          item => item.furniture_name !== furniture.furniture_name
                                        );
                                      } else {
                                        selectedFurnitures.value = [...selectedFurnitures.value, {
                                          ...furniture,
                                          x: 0,
                                          y: 0
                                        }];
                                      }
                                    }}
                                  >
                                    <img 
                                      src={`http://localhost:8000/${furniture.image_path}`} 
                                      alt={furniture.furniture_name} 
                                      style={{imageRendering: "pixelated"}} 
                                      class="object-contain w-24 h-24"
                                    />
                                    <span class="text-center font-bold rounded-b-lg w-24 h-12 bg-[#E5E2B6] flex items-center justify-center">
                                      {furniture.furniture_name}
                                    </span>
                                  </div>
                                  
                                  {isSelected && (
                                    <div class="flex gap-2 mt-1">
                                      <input 
                                        type="number" 
                                        min="1" 
                                        max="10" 
                                        value={selectedItem?.x || ''}
                                        onInput$={(e) => {
                                          const value = (e.target as HTMLInputElement).value;
                                          const index = selectedFurnitures.value.findIndex(f => f.furniture_name === furniture.furniture_name);
                                          if (index !== -1) {
                                            const updated = [...selectedFurnitures.value];
                                            updated[index] = { ...updated[index], x: parseInt(value) || 0 };
                                            selectedFurnitures.value = updated;
                                          }
                                        }}
                                        class="w-12 px-1 text-center border rounded"
                                        placeholder="X"
                                      />
                                      <input 
                                        type="number" 
                                        min="1" 
                                        max="10"
                                        value={selectedItem?.y || ''}
                                        onInput$={(e) => {
                                          const value = (e.target as HTMLInputElement).value;
                                          const index = selectedFurnitures.value.findIndex(f => f.furniture_name === furniture.furniture_name);
                                          if (index !== -1) {
                                            const updated = [...selectedFurnitures.value];
                                            updated[index] = { ...updated[index], y: parseInt(value) || 0 };
                                            selectedFurnitures.value = updated;
                                          }
                                        }}
                                        class="w-12 px-1 text-center border rounded"
                                        placeholder="Y"
                                      />
                                    </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$={() => {handleChange() }}
                    >
                        저장하기
                    </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",
        },
    ],
};
