import { component$, useContext, useVisibleTask$ } from "@builder.io/qwik";
import { type DocumentHead, routeLoader$, Link, useLocation } from "@builder.io/qwik-city";
import axios from "axios";
import { useSignal, $ } from "@builder.io/qwik";
import { AppStateContext } from "~/utils/context";
import { getCookie } from "~/utils/cookie";
import ShowRoomGrid from "~/components/room/ShowRoomGrid";
interface FriendRequest {
    id: number;
    user_id: number;
    friend_id: number;
    friend_username: string;
    status: string;
    created_at: string;
}
interface User {
    id: number;
    username: string;
    email: string;
    created_at: string;
    profile_image_path: string;
    is_active: boolean;
}
export const useDataLoader = routeLoader$(async ({params, cookie}) => {
  const headers = {
    Authorization: `Bearer ${cookie.get("access_token")?.value}`,
  }
  try { 
    // console.log(cookie.get("access_token")?.value + "이것은 토큰");
  // console.log(userid.data.id + "<- 이것은 아이디");

  const user = await axios.get<User>(`http://localhost:8000/api/user/profile/${params.username}`);
    const [room, avatar, friendRequest, diaries, guestbooks] = await Promise.all([
      axios.get(`http://localhost:8000/api/room/layout/${user.data.id}`, { headers }),
      axios.get(`http://localhost:8000/api/avatar/${user.data.id}`, { headers }),
      axios.get(`http://localhost:8000/api/friendship/pending`, { headers }),
      axios.get(`http://localhost:8000/api/diary/w/${user.data.id}?skip=0&limit=6`, { headers }),
      axios.get(`http://localhost:8000/api/guestbook/${user.data.id}`, { headers }),
    ]);
    
    // const avatar = await axios.get(`http://localhost:8000/api/avatar/${userid.data.id}`, {
    //   headers: {
    //     Authorization: `Bearer ${cookie.get("access_token")?.value}`,
    //   },
    // });
  // console.log(res.data+ "다이어리 데이터 불러오기");
  // console.log("??/" + res.data.diaries);
  // console.log(room.room.room_type);
  return {diaries: diaries.data, guestbooks: guestbooks.data, friendRequest: friendRequest.data as FriendRequest[], userdata: {room: room.data, avatar: avatar.data} };
} catch (error : any) {
  console.error("에러 : " + error.config.url);
  return {diaries: [], guestbooks: [], friendRequest: [] as FriendRequest[], userdata: {room: [], avatar: [] } };
}
});
export default component$(() => {
    const data = useDataLoader();
    console.log(data.value.userdata.avatar);
    const showMyFriendsRequest = useSignal<boolean>(false);
    const userData = useContext(AppStateContext);
    const selectedRoom = useSignal({});
    const location = useLocation();
    useVisibleTask$(() => {
      selectedRoom.value = data.value.userdata.room;
      // userData.avatar = data.value.userdata.avatar;
    })
    const handleAcceptFriend = $( async (friendship_id : number) => {
        try {
          console.log(getCookie("access_token"));
          const res = await axios.put(`http://localhost:8000/api/friendship/${friendship_id}/accept`, {}, {
                headers: {
                  Authorization: `Bearer ${getCookie("access_token")}`,
                },
            })   
            console.log(res.data);
            data.value.friendRequest = data.value.friendRequest.filter((friend) => friend.id !== friendship_id);
            
        } catch (error : any) {
            console.log(error.response?.data?.detail);
        }
    })
  return (
    <div class="min-h-screen bg-white px-8 py-4 text-[#4b3c28]">
      <header class="flex justify-between items-start border-b border-[#4b3c28] pb-1 mb-4">
        <h1 class="text-3xl font-bold">Title</h1>
        <a href={`/${userData.username}`} class="text-sm underline">내 페이지</a>
      </header>

    <div class="flex flex-col lg:flex-row gap-8">
      <div class="flex-1">
        <section class="mb-6">
          <div class="flex justify-between">
            <h2 class="text-xl font-bold mb-2">Mini Room</h2>
            <Link href="room" class="text-base text-[#4b3c28] font-semibold">
              <i class="bi bi-caret-right"></i> 미니룸 이동
            </Link>
          </div>
          <div>
            <div class="flex flex-col lg:flex-row gap-8">
              {/* <RoomGrid furniture={data.value.room} avatar={data.value.avatar} roomType={data.value.roomType} />   */}
              <ShowRoomGrid
  roomSrc={data.value.userdata.room.room.room_type}
  furnitures={data.value.userdata.room.furniture}
  avatars={data.value.userdata.avatar}
/>
              <section class="mb-6 flex flex-col justify-between gap-8">
                <div class="flex-1">
                  <h2 class="text-xl w-full pl-3 pb-1 font-bold border-b-2 border-[#4b3c28] inline-block mb-2">Update</h2>
                    <ul class="space-y-2">
                    {data.value.diaries.map((diary : any) => (
                      <li key={diary.id} class="flex items-center gap-2 md:text-sm">
                        <Link href={`/${location.params.username}/diary/${diary.id}`} class="flex items-center gap-2 md:text-sm">
                          <span class="bg-[#4b3c28] text-white text-xs w-12 px-2 rounded">게시</span>
                          <span class="text-xs lg:text-sm">{diary.title}</span>
                        </Link>
                      </li>
                    ))}
                  </ul>
                </div>
                <div class="flex-1 pt-7 justify-start w-full lg:w-[220px] text-base lg:mt-0">
                  <div class="border-t border-dashed border-[#4b3c28] pt-2 pb-2">
                    <div class="flex justify-between">
                      <Link href={`/${location.params.username}/diary`} class="flex-1">다이어리 {data.value.diaries.length}개</Link>
                      {userData.username === location.params.username && <span onclick$={() => {showMyFriendsRequest.value = true}} class="flex-1 hover:text-[#4b3c28] cursor-pointer hover:underline">친구 요청 {data.value.friendRequest.length}개</span>}
                    </div>
                  </div>
                  <div class="border-t border-b border-dashed border-[#4b3c28] pt-2 pb-2">
                    <Link href={`/${location.params.username}/guestbook`} class="flex-1">방명록 {data.value.guestbooks.length}개</Link>
                  </div>
                </div>
              </section>
              </div>
              </div>
            </section>
            {showMyFriendsRequest.value && (
              <div onclick$={() => {showMyFriendsRequest.value = false}} class="bg-opacity-45 z-[1000] fixed inset-0 w-full h-full py-6 px-6 flex justify-center items-center bg-black">
                 <div onclick$={(e) => {e.stopPropagation()}} class="flex w-full h-full flex-col max-w-[1000px] p-2 max-h-[400px] bg-white">
          
                    <div class="w-full flex justify-between"><p class="text-lg font-bold p-2 w-full text-left">친구 요청</p>
                    <i class="bi bi-x-lg cursor-pointer" onclick$={() => {showMyFriendsRequest.value = false}}></i></div>
                    {data.value.friendRequest.length > 0 ? (
                      <div class="divide-y-2 divide-gray-200 max-h-64 w-full overflow-y-auto">
                      {data.value.friendRequest.map((friend, i) => (
                        <div key={i} class="flex p-2 items-center justify-between border-b-2 border-gray-200 py-3">
                          <div class="flex items-center gap-3"><span class="font-medium text-lg">{friend.friend_username}</span></div>
                          <button class="text-black hover:text-red-500 flex items-center justify-center" onclick$={() => {handleAcceptFriend(friend.id)}}><i class="bi bi-check text-lg"></i></button>
                        </div>
                      ))}
                    </div>
                    ) : (
                      <div class="flex items-center justify-center h-full">
                        <p class="text-gray-500">친구 요청이 없습니다.</p>
                      </div>
                    )}
                 </div>
              </div>
            )}
            
      </div>

    </div>
  </div>
  );
});

export const head: DocumentHead = {
  title: "내 미니홈피",
  meta: [
    {
      name: "description",
      content: "나만의 공간에 오신 것을 환영합니다!",
    },
  ],
};
