import { component$, $, useSignal, useContext } from "@builder.io/qwik";
import { DocumentHead, useNavigate, routeLoader$, Link, useLocation } from "@builder.io/qwik-city";
import axios from "axios";
import { getCookie } from "~/utils/cookie";
// import { AppStateContext } from "~/utils/context";


type DiaryResponse = {diary: DiaryEntry, myInfo: number } | { detail: string };

export const useDiaryLoader = routeLoader$<DiaryResponse>(async ({params, cookie, status}) => {
    const diary_id = params.diary_id;
    try {
        console.log(diary_id);
        const res = await axios.get(`http://localhost:8000/api/diary/${diary_id }`);
        const myInfo = await axios.get(`http://localhost:8000/api/user/me`, {
            headers: {
                Authorization: `Bearer ${cookie.get("access_token")?.value}`,
            },
        });
        console.log(myInfo.data.id);
        console.log(res.data);
        return {diary: res.data, myInfo: myInfo.data.id};
    } catch (error : any) {
        console.error(error);
        return error.response?.data?.detail || 'Diary not found';
    }
});

export default component$(() => {
    const navigate = useNavigate();
    const location = useLocation();
    const diaryLoader = useDiaryLoader();

    // const AppState = useContext(AppStateContext);
    const handleDelete = $(() => {
        if ('diary' in diaryLoader.value && 'id' in diaryLoader.value.diary) {
          try {
            axios.delete(`http://localhost:8000/api/diary/${diaryLoader.value.diary.id}`,
              {
                headers: {
                  Authorization: `Bearer ${getCookie("access_token")}`,
                },
              }
            );
          } catch (error : any) {
            console.error(error);
          }
        } 
        navigate(`/${location.params.username}/diary`);
    });
    
    if ('detail' in diaryLoader.value) {
        return <div class="p-6">Diary not found or error: {diaryLoader.value.detail}</div>;
    }
    
    const { diary, myInfo } = diaryLoader.value;
    
    return (
        <div class="p-6">
            <div class="flex border-b-2 border-text-default justify-between items-center mb-8">
                <h1 class="text-2xl font-bold">{diary.title}</h1> 
                <div class="flex flex-row justify-between items-center">
                {diary.user_id === myInfo && (
                <div class="flex gap-3">
                  <button onClick$={handleDelete} >
                    <i class="bi bi-trash-fill text-3xl text-black"></i>
                  </button>
                  <Link href={`/${location.params.username}/diary/${location.params.diary_id}/edit/`}>
                    <i class="bi bi-send-fill text-3xl text-black"></i>
                  </Link>
                </div>
                )}
            </div>
              </div>
             
            <div class="mt-8 flex flex-col gap-4">
              <div class="flex gap-4 overflow-auto border-t-[1px] border-b-[1px] border-text-default p-2">
              {diaryLoader.value.diary.images.map((image, index) => (
                <img key={index} src={`http://localhost:8000/${image}`} alt={`일기 ${index + 1}`} class="max-w-full h-auto max-h-64" />
              ))}
              </div>
              
              <p class="whitespace-pre-wrap ">{diaryLoader.value.diary.content}</p>
            </div>
            
            {('detail' in diaryLoader.value) && (
                <div class="flex border-b-2 border-text-default justify-center items-center w-full h-full">
                <p>일기가 없습니다.</p>
                </div>
            )}
        </div>
    );
});

export const head: DocumentHead = {
    title: "일기",
    meta: [
        {
            name: "description",
            content: "유저가 쓴 일기의 상세정보",
        },
    ],
};
