'use client'

import { useEffect, useState } from 'react'
import { useAxios } from '@/hooks/useAxios'
import { handleFileDown } from '@/util/board-utils'
import { useMessage } from '@/hooks/useMessage'

export default function BoardDetailModal({ noticeNo, setOpen }) {
  const { getMessage } = useMessage()

  // api 조회 관련
  const { get } = useAxios()
  const [boardDetail, setBoardDetail] = useState({})

  useEffect(() => {
    // 상세 조회
    const fetchDetail = async (noticeNo) => {
      const url = `/api/board/detail`
      const params = new URLSearchParams({
        noticeNo: noticeNo,
      })
      const apiUrl = `${url}?${params.toString()}`

      const resultData = await get({ url: apiUrl })

      if (resultData) {
        if (resultData.result.code === 200) {
          const boardDetail = resultData.data
          setBoardDetail(boardDetail)
        } else {
          alert(resultData.result.message)
        }
      }
    }

    fetchDetail(noticeNo)
  }, [])

  return (
    <>
      <div key={noticeNo} className="modal-popup community">
        <div className="modal-dialog">
          <div className="modal-content">
            <div className="modal-header">
              <button
                type="button"
                className="modal-close"
                onClick={() => {
                  setOpen(false)
                }}
              >
                {getMessage('board.sub.btn.close')}
              </button>
            </div>
            <div className="modal-body">
              <div className="community_detail">
                <div className="community_detail-tit">{boardDetail.title}</div>

                {boardDetail.listFile && (
                  <dl className="community_detail-file-wrap">
                    <dt>{getMessage('board.sub.fileList')}</dt>
                    {boardDetail.listFile.map((boardFile) => (
                      <dd key={boardFile.encodeFileNo}>
                        <button type="button" className="down" onClick={() => handleFileDown(boardFile.fileNo, 'N')}>
                          {boardFile.srcFileNm}
                        </button>
                      </dd>
                    ))}
                  </dl>
                )}

                <div
                  className="community_detail-inner"
                  dangerouslySetInnerHTML={{
                    __html: boardDetail.contents ? boardDetail.contents.replaceAll('\n', '<br/>') : '',
                  }}
                ></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  )
}
