import { component$, $,  } 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}) => {
    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 max-w-6xl mx-auto">
            <div class="border-b-2 border-text-default pb-4 mb-8">
                <div class="flex justify-between items-center">
                    <h1 class="text-3xl font-bold text-gray-800">{diary.title}</h1> 
                    {diary.user_id === myInfo && (
                    <div class="flex gap-4">
                        <button 
                            onClick$={handleDelete}
                            class="text-gray-600 hover:text-red-500 transition-colors"
                            aria-label="일기 삭제"
                        >
                            <i class="bi bi-trash-fill text-2xl"></i>
                        </button>
                        <Link 
                            href={`/${location.params.username}/diary/${location.params.diary_id}/edit/`}
                            class="text-gray-600 hover:text-blue-500 transition-colors"
                            aria-label="일기 수정"
                        >
                            <i class="bi bi-send-fill text-2xl"></i>
                        </Link>
                    </div>
                    )}
                </div>
                <p class="text-sm text-gray-500 mt-2">
                    {new Date(diary.created_at).toLocaleDateString('ko-KR', {
                        year: 'numeric',
                        month: 'long',
                        day: 'numeric',
                        weekday: 'long'
                    })}
                </p>
            </div>
            
            <div class="mt-8 space-y-8">
                {diary.images.length > 0 && (
                    <div class="flex overflow-x-auto py-4 gap-4">
                        {diary.images.map((image, index) => (
                               <img 
                                    src={`http://localhost:8000/${image}`} 
                                    alt={`일기 이미지 ${index + 1}`} 
                                    class="w-auto h-64 object-contain border border-button-color-2 rounded-lg"
                                    loading="lazy"
                                />
                        ))}
                    </div>
                )}
                
                <div class="prose max-w-none">
                    <p class="whitespace-pre-wrap text-gray-700 leading-relaxed text-lg">
                        {diary.content}
                    </p>
                </div>
            </div>
            
            {('detail' in diaryLoader.value) && (
                <div class="text-center py-12">
                    <p class="text-gray-500">일기를 찾을 수 없습니다.</p>
                </div>
            )}
        </div>
    );
});

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