import { component$, Signal, useSignal, $, useTask$, } from "@builder.io/qwik";
import axios from "axios";
import { getCookie } from "~/utils/cookie";
export const AddFriends = component$(({ showAddFriends }: { showAddFriends: Signal<boolean> }) => {
    const friends = useSignal([]) as Signal<any[]>;
    const myfriends = useSignal([]) as Signal<any[]>;
    const searchQuery = useSignal('');
    useTask$(() => {
      try {
        axios.get(`http://localhost:8000/api/friendship`, {
          headers: {
            Authorization: `Bearer ${getCookie("access_token")}`,
          },
        })
        .then((res) => {
          myfriends.value = res.data; 
        })
      } catch (error) {
        console.log(error);
      }
    })
    const errorMessage = useSignal('');
    const handleAddFriend = $((username: string) => {
      try {
        axios.post(`http://localhost:8000/api/friendship/request`, {
          friend_username: username,
        }, {
          headers: {
            Authorization: `Bearer ${getCookie("access_token")}`,
          },
        })
        .then((res) => {
            console.log(res.data);
            myfriends.value =  [...myfriends.value.filter((friend) => friend.username !== username) ];
        })
      } catch (error : any) {
        console.log(error.response?.data?.detail);
        errorMessage.value = error.response?.data?.ms;
      }
    })
    const handleSearch = $((query: string) => {
      try {
       axios.get(`http://localhost:8000/api/user/find/${query}`, {
       })
       .then((res) => {
          friends.value = res.data;
       })
    } catch (error : any) {
      console.log(error);
    }
  })
    const handleDeleteFriend = $((friendship_id : number) => {
      try {
        console.log(friendship_id + getCookie("access_token")!);
        axios.delete(`http://localhost:8000/api/friendship/${friendship_id}`, {
          headers: {
            Authorization: `Bearer ${getCookie("access_token")}`,
          },
        })
        .then((res) => {
          console.log(res.data);
          myfriends.value =  [...myfriends.value.filter((friend) => friend.id !== friendship_id) ];
        })
      } catch (error : any) {
        console.log(error.response?.data?.detail);
        errorMessage.value = error.response?.data?.detail;
      }
    })
    return (
              <div onclick$={() => {showAddFriends.value = false; console.log(showAddFriends.value)}} class="bg-opacity-45 z-[1000] fixed inset-0 w-full h-full py-6 px-6 bg-black">
                 <div class="flex w-full h-full justify-center items-center">
                 <div onclick$={(e) => {e.stopPropagation()}} class="max-w-[1001px] w-full bg-white rounded-lg shadow p-4">
                    {/* 헤더 */}
                    <div class="flex justify-between items-center mb-3 border-b pb-2 border-black">
                      <h1 class="text-3xl font-bold">친구 추가</h1>
                      <button onclick$={() => {showAddFriends.value = false; console.log(showAddFriends.value)}} class="text-black text-xl"><i class="bi bi-x-square"></i></button>
                    </div>
          
                    {/* 검색창 */}
                    <form class="relative" preventdefault:submit onSubmit$={() => {handleSearch(searchQuery.value)}}>
                      <input
                        type="text"
                        placeholder="닉네임/아이디 검색"
                        class="w-full border border-black text-text-default rounded px-10 py-2 focus:outline-none focus:ring-1 focus:ring-[#4b3c28]"
                        bind:value={searchQuery}
                      />
                      <button class="absolute left-2 top-2 text-black hover:text-gray-600 text-xl"><i class="bi bi-search"></i></button>
                    </form>
                    {/* 검색 결과 */}
                    <p class="text-lg font-bold p-2">검색 결과 {friends.value.length}건</p>
                    <div class="divide-y divide-gray-200 max-h-64 overflow-y-auto">
                      {friends.value.map((friend, i) => (
                        <div key={i} class="flex items-center justify-between py-3">
                          <div class="flex items-center gap-3">
                            <img class={`w-8 h-8 rounded-full`} src={`http://localhost:8000/${friend.profile_image_path}`} />
                            <div class="flex flex-col">
                              <span class="font-medium text-sm">{friend.username}</span>
                            </div>
                          </div>
                          <button class="text-black hover:text-red-500" onclick$={() => {handleAddFriend(friend.username)}}><i class="bi bi-plus"></i></button>
                        </div>
                      ))}
                    </div>
                    <div class="w-full border-b-2 border-y-2 p-1 flex justify-between border-gray-400">
                      <p class="text-lg font-bold">친구 목록</p>
                      {/* <i class="bi bi-arrow-clockwise"></i> */}
                    </div>
                    {/* 이미 추가된 친구들 */}
                    <div class="divide-y divide-gray-200 max-h-64 overflow-y-auto">
                      {myfriends.value.map((friend, i) => (
                        <div key={i} class="flex items-center justify-between py-3">
                          <div class="flex items-center gap-3">
                            {/* <img class={`w-8 h-8 rounded-full`} src={`http://localhost:8000/${friend.profile_image_path}`} /> */}
                            <div class="flex flex-col">
                              <span class="font-medium text-sm">{friend.friend_username}</span>
                              <span class="text-xs text-gray-500">{friend.friend_id}</span>
                            </div>
                          </div>
                          <button class="text-black hover:text-red-500" onclick$={() => {handleDeleteFriend(friend.id)}}><i class="bi bi-trash"></i></button>
                        </div>
                      ))}
                    </div>
                    <p class="text-red-500">{errorMessage.value}</p>
                  </div></div>
                </div>
    );
});
