import { component$, useSignal } from "@builder.io/qwik";
import { DocumentHead, routeLoader$ } from "@builder.io/qwik-city";
import axios from "axios";
import { BuyModal } from "~/components/features/shop/BuyModal";
import RoomGrid from "~/components/room/RoomGrid";

interface ShopItem {
  name: string;
  image_path: string;
  width: number;
  // Add other properties that your items might have
}
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 ShopResponse {
  storeData: ShopItem[];
  avatarData: Avatar[]; // You might want to define a more specific type for avatar data
  dotory: number;
}

export const useShopLoader = routeLoader$(async ({cookie}) => {
    try {
        const res = await axios.get(`http://localhost:8000/api/room/catalog`, {
            headers: {
                Authorization: `Bearer ${cookie.get("access_token")?.value}`,
            },
        });
        const avatar = await axios.get(`http://localhost:8000/api/avatar`, {
            headers: {
                Authorization: `Bearer ${cookie.get("access_token")?.value}`,
            },
        });
        // const dotory = await axios.get(`http://localhost:8000/api/store`, {
        //     headers: {
        //         Authorization: `Bearer ${cookie.get("access_token")?.value}`,
        //     },
        // });
        console.log(res.data);
        console.log(avatar.data);
        return {storeData: res.data, avatarData: avatar.data, dotory: 0};
    } catch (error : any) {
        console.error(error);
        return { storeData: [], avatarData: null, dotory: 0};
    }
});
export default component$(() => {
    const data = useShopLoader() as { value: ShopResponse };
    const selectedItem = useSignal<ShopItem | null>(null);
    const showBuyModal = useSignal(false);
    return (
      <div class="relative flex p-4 justify-between items-center w-full h-full">
        {/* 좌측 */}
        <div class="grid grid-cols-2 overflow-auto h-full max-h-[calc(100vh-100px)] gap-2">
            {data.value.storeData.slice(0, data.value.storeData.length / 2).map((item: ShopItem) => (
              <div key={item.name} class={`flex items-center flex-col gap-2 rounded-t-lg` } onClick$={() => {if(selectedItem.value === item) selectedItem.value = null; else selectedItem.value = item;}}>
                <img src={`http://localhost:8000/${item.image_path}`} alt={item.name} style={{imageRendering: "pixelated"}} class={` object-contain w-24 h-24 ${selectedItem.value === item ? "border-[2px] border-[#FAD659]" : ""}`} />
                <span class="text-center font-bold rounded-b-lg w-24 h-12 bg-[#E5E2B6]">{item.name}</span>
              </div>
            ))}
        </div>

        {/* 중앙 빈 박스 */}
        <div class="w-64 bg-white border-text-default border-[2px] rounded-lg h-80 flex items-center justify-center">
          {selectedItem.value &&
          <div class="flex flex-col gap-4 items-center">
            <span class="font-bold">{selectedItem.value.name}</span>
            <span>비율: {selectedItem.value.width}</span>
           <img src={`http://localhost:8000/${selectedItem.value?.image_path}`} alt="avatar" style={{imageRendering: "pixelated"}} class="object-contain w-32 h-32" />
            <button  
              class="bg-diary-color hover:bg-diary-icon-hover md:w-full text-black px-4 py-2 rounded-3xl font-bold transition-all duration-200 flex items-center gap-2 z-10 relative" 
              onClick$={() => {showBuyModal.value = true}}>
              구매하기
              <i class="bi bi-cart-fill text-3xl text-black"></i>
            </button>
          </div>
          }
          {!selectedItem.value && <p>아이템을 선택해주세요.</p>}
        </div>
        
        {/* 우측 */}
        <div class="grid grid-cols-2 overflow-auto h-full max-h-[calc(100vh-100px)] gap-2">
            {data.value.storeData.slice(data.value.storeData.length / 2, data.value.storeData.length).map((item: ShopItem) => (
              <div key={item.name} class={`flex items-center flex-col gap-2 rounded-t-lg` } onClick$={() => {if(selectedItem.value === item) selectedItem.value = null; else selectedItem.value = item;}}>
                <img src={`http://localhost:8000/${item.image_path}`} alt={item.name} style={{imageRendering: "pixelated"}} class={` object-contain w-24 h-24 ${selectedItem.value === item ? "border-[2px] border-[#FAD659]" : ""}`} />
                <span class="text-center font-bold rounded-b-lg w-24 h-12 bg-[#E5E2B6]">{item.name}</span>
              </div>
            ))}
        </div>
        {showBuyModal.value &&
      <div class="bg-opacity-45 z-[1000] fixed inset-0 w-full h-full bg-black"
      onclick$={() => {showBuyModal.value = false}}>
            <BuyModal showBuyModal={showBuyModal} item={selectedItem.value} mydotory={data.value.dotory} itemdotory={80}/>
      </div>
      }
      </div>
    );
});
export const head: DocumentHead = {
    title: "Shop",
    meta: [
        {
            name: "description",
            content: "Shop page description",
        },
    ],
};
