'use client';

/**
 * 게시글 상세 페이지
 * URL: /board/{boardCode}/{postId}
 */

import { useParams, useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';
import { DetailPageSkeleton } from '@/components/ui/skeleton';
import { BoardDetail } from '@/components/board/BoardDetail';
import { getPost } from '@/components/board/actions';
import type { Post, Comment } from '@/components/board/types';
import { toast } from 'sonner';

export default function BoardDetailPage() {
  const params = useParams();
  const router = useRouter();

  const boardCode = params.boardCode as string;
  const postId = params.postId as string;

  const [post, setPost] = useState<Post | null>(null);
  const [comments, setComments] = useState<Comment[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [currentUserId, setCurrentUserId] = useState<string>('');

  // 현재 사용자 ID 가져오기
  useEffect(() => {
    const userId = localStorage.getItem('user_id') || '';
    setCurrentUserId(userId);
  }, []);

  // 게시글 조회
  useEffect(() => {
    async function fetchPost() {
      if (!boardCode || !postId) return;

      setIsLoading(true);
      try {
        const result = await getPost(boardCode, postId);

        if (result.success && result.data) {
          setPost(result.data);
          // TODO: 댓글 API 호출 추가
          setComments([]);
        } else {
          toast.error(result.error || '게시글을 찾을 수 없습니다.');
          router.push('/ko/board');
        }
      } catch (error) {
        console.error('게시글 조회 오류:', error);
        toast.error('게시글 조회에 실패했습니다.');
      } finally {
        setIsLoading(false);
      }
    }

    fetchPost();
  }, [boardCode, postId, router]);

  if (isLoading) {
    return <DetailPageSkeleton sections={1} fieldsPerSection={4} />;
  }

  if (!post) {
    return null;
  }

  return (
    <BoardDetail
      post={post}
      comments={comments}
      currentUserId={currentUserId}
    />
  );
}