'use client'

import { useEffect, useState, useContext } from 'react'
import { useRecoilState } from 'recoil'
import { useAxios } from '@/hooks/useAxios'

import { searchState } from '@/store/boardAtom'
import { useMessage } from '@/hooks/useMessage'

import { handleFileDown } from '@/util/board-utils'

import { QcastContext } from '@/app/QcastProvider'

export default function ArchiveTable({ clsCode }) {
  // global 로딩바
  const { setIsGlobalLoading } = useContext(QcastContext)

  const { getMessage } = useMessage()

  // api 조회 관련
  const { get } = useAxios()
  const [search, setSearch] = useRecoilState(searchState)
  const [boardList, setBoardList] = useState([])

  // 목록 조회
  useEffect(() => {
    async function fetchData() {
      setIsGlobalLoading(true)
      const url = `/api/board/list`
      const params = new URLSearchParams({
        schNoticeTpCd: 'QC',
        schNoticeClsCd: clsCode,
        schTitle: search.searchValue ? search.searchValue : '',
      })
      const apiUrl = `${url}?${params.toString()}`

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

      if (resultData) {
        if (resultData.result.code === 200) {
          setBoardList(resultData.data)
          if (resultData.data.length > 0) {
            setSearch({ ...search, totalCount: resultData.data[0].totCnt })
          } else {
            setSearch({ ...search, totalCount: 0 })
          }
        } else {
          alert(resultData.result.message)
        }
      }
      setIsGlobalLoading(false)
    }

    fetchData()
  }, [search.searchValue, search.searchFlag])

  return (
    <>
      {boardList.length > 0 ? (
        <div className="file-down-list">
          {boardList?.map((board) => (
            <div key={board.noticeNo} className="file-down-item">
              <div className="file-item-info">
                <div className="item-num">
                  {/* 번호 */}
                  {board.rowNumber}
                </div>
                <div className="item-name">
                  {/* 제목 */}
                  {board.title}
                </div>
                <div className="item-date">
                  {/* 등록일 */}
                  {getMessage('board.sub.updDt')} : {board.uptDt ? board.uptDt : board.regDt}
                </div>
              </div>
              <div className="file-down-box">
                {/* 첨부파일 */}
                <button type="button" className="file-down-btn" onClick={() => handleFileDown(board.noticeNo, 'Y')}></button>
              </div>
            </div>
          ))}
        </div>
      ) : (
        <div className="file-down-nodata">{getMessage('common.message.no.data')}</div>
      )}
    </>
  )
}
