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

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 getDotory = await axios.put(`http://localhost:8000/api/store?dotory_num=100`, {
        //     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}`,
        //     },
        // });
        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);
        console.log(dotory.data);
        return {storeData: res.data, avatarData: avatar.data, dotory: dotory.data};
    } catch (error : any) {
        console.error(error);
        return { storeData: [], avatarData: null, dotory: 0};
    }
});
export default component$(() => {
    const data = useShopLoader();
    const dotory = useSignal<number>(0);
    const selectedItem = useSignal<ShopItem | null>(null);
    const showBuyModal = useSignal(false);
    useVisibleTask$(() => {
      dotory.value = data.value.dotory.dotory as number;
    });
    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)] p-4 gap-8">
            {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 transition-all duration-200 ${
                  selectedItem.value === item 
                    ? 'scale-105 transform -translate-y-1' 
                    : 'opacity-90 hover:opacity-100'
                }`}
                onClick$={() => {
                  selectedItem.value = selectedItem.value === item ? null : item;
                }}
              >
                <div class="relative">
                  <img 
                    src={`http://localhost:8000/${item.image_path}`} 
                    alt={item.name} 
                    style={{imageRendering: "pixelated"}} 
                    class={`object-contain w-24 h-24 transition-all duration-200 ${
                      selectedItem.value === item 
                        ? 'ring-4 ring-yellow-400 ring-offset-2' 
                        : 'border border-gray-200'
                    } rounded-lg`} 
                  />
                  {selectedItem.value === item && (
                    <div class="absolute -top-2 -right-2 w-6 h-6 bg-yellow-400 rounded-full flex items-center justify-center">
                      <i class="bi bi-check-lg text-white text-sm"></i>
                    </div>
                  )}
                </div>
                <span class={`text-center font-bold rounded-lg w-24 py-2 transition-colors ${
                  selectedItem.value === item 
                    ? 'bg-yellow-400 text-gray-900' 
                    : 'bg-[#E5E2B6] text-gray-800'
                }`}>
                  {item.name}
                </span>
              </div>
            ))}
        </div>

        {/* 중앙 미리보기 */}
        <div class="w-72 bg-white border-[3px] border-[#4b3c28] rounded-xl h-80 flex items-center justify-center shadow-lg">
          {selectedItem.value &&
          <div class="flex flex-col items-center p-4 w-full">
            <div class="text-center mb-2">
              <h3 class="text-lg font-bold text-[#4b3c28]">{selectedItem.value.name}</h3>
              <p class="text-sm text-gray-600">비율: {selectedItem.value.width}</p>
            </div>
            <div class="flex-1 flex items-center justify-center my-2 w-full">
              <img 
                src={`http://localhost:8000/${selectedItem.value?.image_path}`} 
                alt={selectedItem.value.name}
                style={{imageRendering: "pixelated"}} 
                class="object-contain w-40 h-40" 
              />
            </div>
            <button  
              class="mt-2 bg-[#FAD659] hover:bg-yellow-400 w-full text-[#4b3c28] px-4 py-3 rounded-xl font-bold transition-all duration-200 flex items-center justify-center gap-2 shadow-md hover:shadow-lg" 
              onClick$={() => {showBuyModal.value = true}}>
              <i class="bi bi-cart-fill"></i>
              <span>구매하기</span>
            </button>
          </div>
          }
          {!selectedItem.value && <p>아이템을 선택해주세요.</p>}
        </div>
        
        {/* 우측 */}
        <div class="grid grid-cols-2 overflow-auto h-full max-h-[calc(100vh-100px)] p-4 gap-8">
            {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 transition-all duration-200 ${
                  selectedItem.value === item 
                    ? 'scale-105 transform -translate-y-1' 
                    : 'opacity-90 hover:opacity-100'
                }`}
                onClick$={() => {
                  selectedItem.value = selectedItem.value === item ? null : item;
                }}
              >
                <div class="relative">
                  <img 
                    src={`http://localhost:8000/${item.image_path}`} 
                    alt={item.name} 
                    style={{imageRendering: "pixelated"}} 
                    class={`object-contain w-24 h-24 transition-all duration-200 ${
                      selectedItem.value === item 
                        ? 'ring-1 ring-yellow-400 ring-offset-1' 
                        : 'border border-gray-200'
                    } rounded-lg`} 
                  />
                  {selectedItem.value === item && (
                    <div class="absolute -top-2 -right-2 w-6 h-6 bg-yellow-400 rounded-full flex items-center justify-center">
                      <i class="bi bi-check-lg text-white text-sm"></i>
                    </div>
                  )}
                </div>
                <span class={`text-center font-bold rounded-lg w-24 py-2 transition-colors ${
                  selectedItem.value === item 
                    ? 'bg-yellow-400 text-gray-900' 
                    : 'bg-[#E5E2B6] text-gray-800'
                }`}>
                  {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={dotory} itemdotory={100}/>
      </div>
      }
      </div>
    );
});
export const head: DocumentHead = {
    title: "Shop",
    meta: [
        {
            name: "description",
            content: "Shop page description",
        },
    ],
};
