"use client" import * as React from "react" import { useState } from "react" import { Button } from "@/components/ui/button" import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, } from "@/components/ui/dialog" import { Info, Download, Edit, Loader2 } from "lucide-react" import { getPageInformationDirect, getEditPermissionDirect } from "@/lib/information/service" import { getPageNotices } from "@/lib/notice/service" import { UpdateInformationDialog } from "@/lib/information/table/update-information-dialog" import { NoticeViewDialog } from "@/components/notice/notice-view-dialog" import type { PageInformation, InformationAttachment } from "@/db/schema/information" import type { Notice } from "@/db/schema/notice" import { useSession } from "next-auth/react" import { formatDate } from "@/lib/utils" // downloadFile은 동적으로 import interface InformationButtonProps { pagePath: string className?: string variant?: "default" | "outline" | "ghost" | "secondary" size?: "default" | "sm" | "lg" | "icon" } type NoticeWithAuthor = Notice & { authorName: string | null authorEmail: string | null } export function InformationButton({ pagePath, className, variant = "ghost", size = "icon" }: InformationButtonProps) { const { data: session } = useSession() const [isOpen, setIsOpen] = useState(false) const [information, setInformation] = useState<(PageInformation & { attachments: InformationAttachment[] }) | null>(null) const [notices, setNotices] = useState([]) const [hasEditPermission, setHasEditPermission] = useState(false) const [isEditDialogOpen, setIsEditDialogOpen] = useState(false) const [selectedNotice, setSelectedNotice] = useState(null) const [isNoticeViewDialogOpen, setIsNoticeViewDialogOpen] = useState(false) const [dataLoaded, setDataLoaded] = useState(false) const [isLoading, setIsLoading] = useState(false) // 데이터 로드 함수 (단순화) const loadData = React.useCallback(async () => { if (dataLoaded) return // 이미 로드되었으면 중복 방지 setIsLoading(true) try { // pagePath 정규화 (앞의 / 제거) const normalizedPath = pagePath.startsWith('/') ? pagePath.slice(1) : pagePath console.log('🔍 Information Button - 데이터 로딩:', { originalPath: pagePath, normalizedPath: normalizedPath, sessionUserId: session?.user?.id }) // 병렬로 데이터 조회 const [infoResult, noticesResult] = await Promise.all([ getPageInformationDirect(normalizedPath), getPageNotices(normalizedPath) ]) console.log('📊 조회 결과:', { infoResult: infoResult ? { id: infoResult.id, pagePath: infoResult.pagePath, pageName: infoResult.pageName, attachmentsCount: infoResult.attachments?.length || 0 } : null, noticesCount: noticesResult.length }) setInformation(infoResult) setNotices(noticesResult) setDataLoaded(true) // 권한 확인 if (session?.user?.id) { const hasPermission = await getEditPermissionDirect(normalizedPath, session.user.id) setHasEditPermission(hasPermission) } } catch (error) { console.error("데이터 로딩 중 오류:", error) } finally { setIsLoading(false) } }, [pagePath, session?.user?.id, dataLoaded]) // 다이얼로그 열기 const handleDialogOpen = (open: boolean) => { setIsOpen(open) if (open && !dataLoaded) { loadData() } } // 편집 관련 핸들러 const handleEditClick = () => { setIsEditDialogOpen(true) } const handleEditSuccess = () => { setIsEditDialogOpen(false) // 편집 후 데이터 다시 로드 setDataLoaded(false) loadData() } // 공지사항 클릭 핸들러 const handleNoticeClick = (notice: NoticeWithAuthor) => { setSelectedNotice(notice) setIsNoticeViewDialogOpen(true) } // 파일 다운로드 핸들러 const handleDownload = async (attachment: InformationAttachment) => { try { // 동적으로 downloadFile 함수 import const { downloadFile } = await import('@/lib/file-download') await downloadFile( attachment.filePath, attachment.fileName, { action: 'download', showToast: true, showSuccessToast: true } ) } catch (error) { console.error('파일 다운로드 실패:', error) } } return ( <>
{isLoading ? (
정보를 불러오는 중...
) : (
{/* 공지사항 섹션 */}

공지사항

{notices.length > 0 && ( {notices.length}개 )}
{notices.length > 0 ? (
{notices.map((notice) => (
handleNoticeClick(notice)} >
{notice.title}
{formatDate(notice.createdAt, "KR")} {notice.authorName && ( {notice.authorName} )}
))}
) : (
공지사항이 없습니다
)}
{/* 인포메이션 컨텐츠 */}

안내사항

{hasEditPermission && information && ( )}
{information?.informationContent ? (
{information.informationContent}
) : (
안내사항이 없습니다
)}
{/* 첨부파일 */}

첨부파일

{information?.attachments && information.attachments.length > 0 && ( {information.attachments.length}개 )}
{information?.attachments && information.attachments.length > 0 ? (
{information.attachments.map((attachment) => (
{attachment.fileName}
{attachment.fileSize && (
{attachment.fileSize}
)}
))}
) : (
첨부파일이 없습니다
)}
)}
{/* 공지사항 보기 다이얼로그 */} {/* 편집 다이얼로그 */} {information && ( )} ) }