'use client'

import { useEffect, useState, useContext } from 'react'
import { useRecoilState } from 'recoil'

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

import { useAxios } from '@/hooks/useAxios'
import { useMessage } from '@/hooks/useMessage'

import BoardDetailModal from '../community/modal/BoardDetailModal'

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

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

  const { getMessage } = useMessage()

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

  // 팝업 관련
  const [open, setOpen] = useState(false)
  const [modalNoticeNo, setModalNoticeNo] = useState('')

  // 목록 조회
  useEffect(() => {
    async function fetchData() {
      setIsGlobalLoading(true)
      const startRow = (search.currentPage - 1) * search.pageBlock > 0 ? (search.currentPage - 1) * search.pageBlock + 1 : 1
      const endRow = search.currentPage * search.pageBlock

      const url = `/api/board/list`
      const params = new URLSearchParams({
        schNoticeTpCd: 'QC',
        schNoticeClsCd: clsCode,
        schTitle: search.searchValue ? search.searchValue : '',
        startRow: startRow,
        endRow: endRow,
        schMainYn: 'N',
      })
      const apiUrl = `${url}?${params.toString()}`

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

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

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

  return (
    <>
      <div className="community-table">
        <table>
          <colgroup>
            <col width={100} />
            <col />
            <col width={200} />
            <col width={150} />
          </colgroup>
          <tbody>
            {boardList.length > 0 ? (
              boardList?.map((board) => (
                <tr
                  key={board.noticeNo}
                  onClick={() => {
                    setOpen(true)
                    setModalNoticeNo(board.noticeNo)
                  }}
                >
                  <td className="al-c">
                    {/* 번호 */}
                    {board.totCnt - board.rowNumber + 1}
                  </td>
                  <td>
                    {/* 제목 */}
                    <div className="text-frame">
                      <div className="text-overflow">{board.title}</div>
                      {board.attachYn === 'Y' && <span className="clip"></span>}
                    </div>
                  </td>
                  <td>
                    <div className="renewal">
                      {board.uptDt && (
                        <>
                          (<span>{getMessage('board.uptDt')}</span> : {board.uptDt})
                        </>
                      )}
                    </div>
                  </td>
                  <td className="al-c">
                    {/* 등록일 */}
                    {board.regDt.split(' ')[0]}
                  </td>
                </tr>
              ))
            ) : (
              <tr>
                <td colSpan={4} className="al-c">
                  {getMessage('common.message.no.data')}
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
      {open && <BoardDetailModal noticeNo={modalNoticeNo} setOpen={setOpen} />}
    </>
  )
}
