import { component$, useSignal, $, useVisibleTask$, useTask$} from "@builder.io/qwik";
import type { DocumentHead } from "@builder.io/qwik-city";
import { routeLoader$ } from "@builder.io/qwik-city";
import { getCookie } from "~/utils/cookie";
import axios from "axios";
import DeleteModal from "~/components/features/guestbook/DeleteModal";
interface GuestbookContent{
  id: number,
  content: string,
  target_user_id: number,
  user_id: number,
  user_profile_path: string,
  username: string,
  created_at: string
}
interface GuestbookResponse {
  messages: GuestbookContent[];
  myInfo: {
    id: number,
  username: string,
  email: string,
  created_at: string,
  profile_image_path: string,
  is_active: boolean
  };
  targetUser: {
    id: number,
    username: string,
    email: string,
    created_at: string,
    profile_image_path: string,
    is_active: boolean
  };
}

export const useGuestbookLoader = routeLoader$(async ({params, cookie}) => {
  try {
    console.log(params.username + "의 방명록 가져오기");
    const userid = await axios.get(`http://localhost:8000/api/user/profile/${params.username}`);
    const myid = await axios.get(`http://localhost:8000/api/user/me`, {
      headers: {
        Authorization: `Bearer ${cookie.get("access_token")?.value}`,
      },
    });
    const res = await axios.get<GuestbookContent[]>(`http://localhost:8000/api/guestbook/${userid.data.id}`);
    console.log(res.data);
    
    return {
      messages: res.data,
      myInfo: myid.data,
      targetUser: userid.data,
    } as GuestbookResponse;
  } catch (error) {
    console.error(error);
    return {
      messages: [],
      myInfo: { id: 0, username: 'Guest'  ,email: 'Guest', created_at: 'Guest', profile_image_path: 'Guest', is_active: false},
      targetUser: { id: 0, username: 'Guest' ,email: 'Guest', created_at: 'Guest', profile_image_path: 'Guest', is_active: false}
    } as GuestbookResponse;
  }
});
export default component$(() => {
  const loaderData = useGuestbookLoader();
  const messages = useSignal<GuestbookContent[]>([]);
  const newMessage = useSignal('');
  const showUpdateModal = useSignal(false);
  const showDeleteModal = useSignal(false);
  const selectedMessage = useSignal<GuestbookContent>({} as GuestbookContent);
  const updatedMessage = useSignal('');
  const diaryContainer = useSignal<HTMLElement>();
  const refreshMessages = $(async () => {
    try {
    const res = await axios.get<GuestbookContent[]>(`http://localhost:8000/api/guestbook/${loaderData.value.targetUser.id}`);
    messages.value = res.data;
    console.log(messages.value + " loader");
    } catch (error) {
        console.error(error);
      console.log("방명록 가져오기 실패" +loaderData.value.targetUser.id);
    }
  });
  useVisibleTask$(() => {
    console.log("useTask");
    refreshMessages();

  });
  useTask$(({track}) => {
    track(() => messages.value);
    // setTimeout(() => {
      if (diaryContainer.value) {
        setTimeout(() => {
          diaryContainer.value!.scrollTop = diaryContainer.value!.scrollHeight;
        }, 0);
      }
    // }, 100);
  });
  const handleSubmit = $(async () => {
    if (!newMessage.value.trim()) return;
    try {
      console.log(newMessage.value);
      await axios.post(`http://localhost:8000/api/guestbook`, {
        content: newMessage.value,
        target_user_id: loaderData.value.targetUser.id,
      }, {
        headers: {
          Authorization: `Bearer ${getCookie("access_token")}`,
        },
      }); 
      console.log("방명록 추가");
      refreshMessages();
    } catch (error) {
      console.error(error);
    }
    newMessage.value = '';
  });
  const handleEdit = $(async () => {
    console.log("수정 요청 보내기");
    if (!updatedMessage.value.trim()) {
      console.log("수정 내용이 없습니다.");
      return;
    }
    try {
      await axios.put(`http://localhost:8000/api/guestbook/${selectedMessage.value.id}`, {
        content: updatedMessage.value,
      }, {
        headers: {
          Authorization: `Bearer ${getCookie("access_token")}`,
        },
      }); 
      refreshMessages();
    } catch (error) {
      console.error(error);
    }
    showUpdateModal.value = false;
    updatedMessage.value = '';
  });
  return (
    <div class="flex flex-col h-screen bg-gray-50">
    {showDeleteModal.value && <DeleteModal messages={messages} showDeleteModal={showDeleteModal} selectedMessage={selectedMessage}/>}
    <div ref={diaryContainer} class="flex-1 overflow-y-auto p-4 space-y-4  divide-y-[1px] divide-gray-200">
      {messages.value.map((msg) => (
        <div key={msg.id} class="flex relative items-start pt-2 space-x-3">
          <div class={`w-14 h-14 rounded-full text-black`}>
            <img class="w-full h-full object-cover rounded-full" src={`http://localhost:8000/${msg.user_profile_path}`} alt="" />
          </div>
          <div class="flex-1">
            <div class="text-sm text-gray-500">
              <span class=" flex items-center gap-2"><span class="text-xl font-bold text-black">{msg.username}</span>  <span class="text-xs font-medium text-gray-400">{new Date(msg.created_at).toLocaleString("ko-KR", { timeZone: "Asia/Seoul", year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false, })}</span></span>
            </div>
            <div class="whitespace-pre-wrap text-gray-800">
              {msg.content}
            </div>  
          </div>
          {msg.user_id === loaderData.value.myInfo.id &&
            <div class="flex space-x-2">
              <button 
                onClick$={() => {
                  selectedMessage.value = msg;
                  updatedMessage.value = msg.content;
                  showUpdateModal.value = true;
                }} 
                class="text-gray-400 hover:text-blue-500 px-2 py-1 text-sm"
              >
                <i class="bi bi-pencil-fill"></i>
              </button>
               <button 
                onClick$={() => {
                  selectedMessage.value = msg;
                  showDeleteModal.value = true;
                }} 
                class="text-gray-400 hover:text-red-500 px-2 py-1 text-sm"
              >
                <i class="bi bi-trash-fill"></i>
              </button>
            </div>
          }
          {showUpdateModal.value && msg.id === selectedMessage.value.id && (
        <form
          class="absolute z-50 bg-white right-0 top-0 p-2 rounded-xl focus:outline-none w-full min-w-[220px]"
          // onClick$={(e) => e.stopPropagation()} /* 외부 클릭으로 닫히는 건 부모가 처리하게 둘 수 있음 */
          preventdefault:submit
          onSubmit$={handleEdit}
        >
        <div class="flex mt-2 justify-between">
          <p>수정할 내용을 입력해주세요.</p>
          <div class="flex gap-2 mt-2 justify-end">
          <button class="btn-cancel text-button-color-1 border-black" onClick$={() => showUpdateModal.value = false}>
            <i class="bi bi-x"></i>
          </button>
          <button class="btn-save text-diary-color border-black">
            <i class="bi bi-check"></i>
          </button>
          </div>
        </div>
          <input
            value={updatedMessage.value}
            onInput$={(ev: any) => (updatedMessage.value = ev.target.value)}
            class="w-full p-2 border border-input-border-color rounded-xl"
          />
        </form>
      )}
        </div>
      ))}
    </div>
    <div class="p-4 bg-white">
      <form  preventdefault:submit  onSubmit$={handleSubmit} class=" relative flex">
      <input 
        bind:value={newMessage}
        type="text"
        placeholder="방명록을 입력해 주세요."
        class="flex-1 p-2 rounded-lg border bg-input-color text-white placeholder:text-white border-gray-300 focus:outline-none focus:ring-1 focus:ring-[#4b3c28]"
      />
      
      {/* <button class="absolute right-12 w-6 h-6 top-1/2 rounded-full bg-gray-500 p-0.5 transform -translate-x-1/2 -translate-y-1/2 text-center">
        <i class="bi bi-images text-white text-center"></i>
      </button> */}
      <button class="absolute right-4 w-6 h-6 top-1/2 rounded-full bg-gray-500 p-0.5 transform -translate-x-1/2 -translate-y-1/2 text-center">
        <i class="bi bi-send text-white text-center"></i>
      </button>
      </form>
    </div>
  </div>
  );
});

export const head: DocumentHead = {
  title: "방명록",
  meta: [
    {
      name: "description",
      content: "방명록 페이지입니다. 자유롭게 메시지를 남겨보세요!",
    },
  ],
};
