<template>
    <div class="container-xxl flex-grow-1 container-p-y">
        <div class="row">
            <div class="col">
                <div class="card">
                    <!-- 프로필 헤더 -->
                    <div class="card-header">
                        <BoardProfile
                            :boardId="currentBoardId"
                            :profileName="profileName"
                            :views="views"
                            :comments="comments"
                            :date="formattedBoardDate"
                            class="pb-6 border-bottom"
                        />
                    </div>
                    <!-- 게시글 내용 -->
                    <div class="card-body">

                        <div class="d-flex justify-content-between align-items-center flex-wrap mb-6 gap-2">
                            <!-- 제목 섹션 -->
                            <div class="me-1">
                                <h5 class="mb-4">{{ boardTitle }}</h5>
                            </div>

                            <!-- 첨부파일 섹션 -->
                            <div v-if="attachments" class="btn-group">
                                <button type="button" class="btn btn-label-secondary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
                                    <i class="fa-solid fa-download me-2"></i>
                                    첨부파일
                                    <!-- (<span class="attachment-num">{{ dropdownItems.length }}</span>) -->
                                </button>
                                <!-- <ul class="dropdown-menu">
                                    <li v-for="(item, index) in dropdownItems" :key="index">
                                        <a class="dropdown-item" href="javascript:void(0);">
                                            {{ item.label }}
                                        </a>
                                    </li>
                                </ul> -->
                            </div>
                        </div>

                        <!-- HTML 콘텐츠 렌더링 -->
                        <div class="board-content text-body" style="line-height: 1.6;" v-html="$common.contentToHtml(boardContent)"></div>

                        <!-- 좋아요 버튼 -->
                        <div class="row justify-content-center my-10">
                            <BoardRecommendBtn
                                :bigBtn="true"
                                :boardId="currentBoardId"
                                :commentId="null"
                                :likeCount="likes"
                                :dislikeCount="dislikes"
                                @updateReaction="handleUpdateReaction"
                            />
                        </div>

                        <!-- 첨부파일 목록 -->
                        <!-- <ul v-if="attachments.length" class="attachments mt-4 list-unstyled">
                            <li v-for="(attachment, index) in attachments" :key="index" class="mb-2">
                                <a :href="attachment.url" target="_blank" class="text-decoration-none">{{ attachment.name }}</a>
                            </li>
                        </ul> -->

                        <!-- 댓글 영역 -->
                        <BoardComentArea />

                        <!-- 수정 버튼 -->
                        <!-- <button class="btn btn-primary" @click="goToEditPage">
                            글 수정
                        </button> -->
                    </div>
                    <div class="card-footer">
                        <BoardCommentList/>

                        <Pagination/>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import BoardComentArea from '@c/board/BoardComentArea.vue';
import BoardProfile from '@c/board/BoardProfile.vue';
import BoardCommentList from '@/components/board/BoardCommentList.vue';
import BoardRecommendBtn from '@/components/button/BoardRecommendBtn.vue';
import Pagination from '@/components/pagination/Pagination.vue';
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from '@api';

// 게시물 데이터 상태
const profileName = ref('익명 사용자');
const boardTitle = ref('제목 없음');
const boardContent = ref('');
const attachments = ref([]);
const date = ref('');
const views = ref(0);
const likes = ref(0);
const dislikes = ref(0);
const likeClicked = ref(false);
const dislikeClicked = ref(false);
const comments = ref(0);
const attachment = ref(false);

// 라우트에서 ID 가져오기
const route = useRoute();
const router = useRouter();
const currentBoardId = ref(Number(route.params.id));

// 글 수정 페이지로 이동
const goToEditPage = () => {
    router.push({ name: 'BoardEdit', params: { id: currentBoardId.value } });
};

// 게시물 상세 데이터 불러오기
const fetchBoardDetails = async () => {
    try {
        const response = await axios.get(`board/${currentBoardId.value}`);
        const data = response.data.data;

        // API 응답 데이터 반영
        // const boardDetail = data.boardDetail || {};

        // console.log('API Response:', response.data);

        profileName.value = data.author || '익명 사용자';
        boardTitle.value = data.title || '제목 없음';
        boardContent.value = data.content || '';
        date.value = data.date || '';
        views.value = data.cnt || 0;
        likes.value = data.likeCount || 0;
        dislikes.value = data.dislikeCount || 0;
        attachment.value = data.hasAttachment || null;
        comments.value = data.commentCount || 0;
        
    } catch (error) {
        alert('게시물 데이터를 불러오는 중 오류가 발생했습니다.');
    }
};

// 좋아요, 싫어요
const handleUpdateReaction = async ({ type, boardId, commentId }) => {
    try {
        //이거 왜 한건지 찾아보자
        const response = await axios.post(`/board/${boardId}/${commentId}/reaction`, { type });

        // console.log('API 응답:', response.data);
        // console.log(commentId)

        if (response.data.code === 200) {
            if (type === 'like') {
                likeClicked.value = !likeClicked.value;
                likes.value += likeClicked.value ? 1 : -1;
            } else if (type === 'dislike') {
                dislikeClicked.value = !dislikeClicked.value;
                dislikes.value += dislikeClicked.value ? 1 : -1;
            }
        } else {
            alert('반응 업데이트 실패');
        }
        // likes.value = response.data.likeCount;
        // dislikes.value = response.data.dislikeCount;

        // if (type === 'like') {
        //     likeClicked.value = !likeClicked.value;
        //     console.log('aaaa' ,response.data)

        // } else if (type === 'dislike') {
        //     console.log('싫어')
        // }
    } catch (error) {
        alert('반응을 업데이트하는 중 오류 발생');
    }
};

// 날짜
const formattedBoardDate = computed(() => {
    const dateObj = new Date(date.value);
    return `${dateObj.getFullYear()}-${String(dateObj.getMonth() + 1).padStart(2, '0')}-${String(dateObj.getDate()).padStart(2, '0')} ${String(dateObj.getHours()).padStart(2, '0')}:${String(dateObj.getMinutes()).padStart(2, '0')}`;
});

// 컴포넌트 마운트 시 데이터 로드
onMounted(() => {
    fetchBoardDetails();
});
</script>
