'use client'

import Link from 'next/link'
import Image from 'next/image'

import Search from '@/components/community/Search'
import Pagination from '@/components/community/Pagination'

import { useContext } from 'react'

import { useEffect, useState } from 'react'
import { useResetRecoilState, useRecoilValue, useRecoilState } from 'recoil'
import { useMessage } from '@/hooks/useMessage'

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

import { QcastContext } from '@/app/QcastProvider'
import QnaBoardDetailModal from '@/components/community/modal/QnaDetailModal'
import { sessionStore } from '@/store/commonAtom'
import { useAxios } from '@/hooks/useAxios'
import { useCommonCode } from '@/hooks/common/useCommonCode'

export default function Qna() {
  const { getMessage } = useMessage()
  const resetSearch = useResetRecoilState(searchState)
  const [isInitialized, setIsInitialized] = useState(false)

  //const search = useRecoilValue(searchState)
  const [searchForm, setSearchForm] = useRecoilState(searchState)
  const { findCommonCode } = useCommonCode()
  const { setIsGlobalLoading } = useContext(QcastContext)
  const { get } = useAxios()
  const [boardList, setBoardList] = useState([])
  const [sessionState, setSessionState] = useRecoilState(sessionStore)
  const [search, setSearch] = useRecoilState(searchState)
  // 팝업 관련
  const [open, setOpen] = useState(false)
  const [modalQnaNo, setModalQnaNo] = useState('')
  const [modalQnaType, setModalQnaType] = 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: 'QNA',
        compCd        : 5200,
        storeId       : sessionState.storeId,
        loginId       : sessionState.userId,
        schTitle      : search.searchValue ? search.searchValue : '',
        startRow      : startRow,
        endRow        : endRow,
        schMainYn     : 'N',
        siteTpCd      : 'QC',
        langCd        : 'JA',
      })
      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])


  useEffect(() => {
    if (search.mainFlag === 'N') {
      resetSearch()
    } else {
      //메인에서 FAQ 조회 왔을때 로딩바 해제
      setIsGlobalLoading(false)
      setSearchForm({ ...searchForm, mainFlag: 'N' })
    }
    setIsInitialized(true)

    //문의구분코드
    // const codeL = findCommonCode(204200)
    // const codeM = findCommonCode(204300)
    // const codeS = findCommonCode(204400)



  }, [])

  if (!isInitialized) {
    return null
  }

  const boardType = {
    boardTitle: getMessage('qna.title'),
    subTitle: getMessage('qna.sub.title'),
    clsCode: 'QNA',
  }


  return (
    <>
      <div className="sub-header">
        <div className="sub-header-inner">
          <ul className="sub-header-title-wrap">
            <li className="title-item">
              <Link className="sub-header-title" href={'#'}>
                {getMessage('qna.title')}
              </Link>
            </li>
          </ul>
          <ul className="sub-header-location">
            <li className="location-item">
              <span className="home">
                <Image src="/static/images/main/home_icon.svg" alt="react" width={16} height={16} />
              </span>
            </li>
            <li className="location-item">
              <span>{getMessage('header.menus.community')}</span>
            </li>
            <li className="location-item">
              <span>{getMessage('qna.title')}</span>
            </li>
          </ul>
        </div>
      </div>
      <div className="sub-content">
        <div className="sub-content-inner">
          <div className="sub-table-box">
            <Search title={boardType.boardTitle} subTitle={boardType.subTitle} isSelectUse={true} clsCode={boardType.clsCode} />
            {/*<QnaTable clsCode={boardType.clsCode} />*/}
            <div className="community-table">
              <table>
                <colgroup>
                  <col width={100}/>
                  <col width={150}/>
                  <col />
                  <col width={150}/>
                  <col width={150}/>
                </colgroup>
                <tbody>
                {boardList.length > 0 ? (
                  boardList?.map((board) => (
                    <tr
                      key={board.qnaNo}
                      onClick={() => {
                        setOpen(true)
                        setModalQnaNo(board.qnaNo)
                        setModalQnaType("["+board?.qnaClsLrgCd+"/"+board?.qnaClsMidCd+"/"+board?.qnaClsSmlCd+"]")
                      }}
                    >
                      <td className="al-c">
                        {/* 번호 */}
                        {board.totCnt - board.rowNumber + 1}
                      </td>
                      {/* 답변 */}
                      {board?.answerYn === 'Y'? (<td className="al-c "> {getMessage('qna.list.header.answer.yes')}</td>) : (<td className="al-c org"> {getMessage('qna.list.header.answer.no')}</td>)}
                      <td>
                        <div className="mb5">[{board?.qnaClsLrgCd} / {board?.qnaClsMidCd} / {board?.qnaClsSmlCd}]</div>
                        {/* 제목 */}
                        <div className="text-frame">
                          <div className="text-overflow">{board.title}{board.qstTitle}</div>
                          {board.attachYn === 'Y' && <span className="clip"></span>}
                        </div>
                      </td>
                      <td>
                        <div className="renewal">
                          {/*{board.uptDt && (*/}
                          {/*  <>*/}
                          {/*    (<span>{getMessage('board.uptDt')}</span> : {board.uptDt})*/}
                          {/*  </>*/}
                          {/*)}*/}
                          {board.regUserNm}
                        </div>
                      </td>
                      <td className="al-c">
                        {/* 등록일 */}
                        {board.regDt.split(' ')[0]}
                      </td>
                    </tr>
                  ))
                ) : (
                  <tr>
                    <td className="al-c no-data" colSpan={5}>{getMessage('common.message.no.data')}</td>
                  </tr>
                )}
                </tbody>
              </table>
            </div>

            <Pagination />
          </div>
        </div>
      </div>
      {open && <QnaBoardDetailModal qnaNo={modalQnaNo} setOpen={setOpen} qnaType = {modalQnaType} />}
    </>
  )
}
