'use client'

import { useEffect, useState, useContext } from 'react'
import ProductItem from './ProductItem'
import { useMessage } from '@/hooks/useMessage'
import Image from 'next/image'
import dayjs from 'dayjs'
import { useAxios } from '@/hooks/useAxios'
import { useRecoilValue } from 'recoil'
import { useRouter } from 'next/navigation'
import { globalLocaleStore } from '@/store/localeAtom'
import { queryStringFormatter } from '@/util/common-utils'
import { useMainContentsController } from '@/hooks/main/useMainContentsController'
import { QcastContext } from '@/app/QcastProvider'
import { useSwal } from '@/hooks/useSwal'

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

export default function MainContents() {
  const { swalFire } = useSwal()

  const { getMessage } = useMessage()
  const router = useRouter()
  const globalLocaleState = useRecoilValue(globalLocaleStore)
  const { promiseGet } = useAxios(globalLocaleState)

  //공지사항
  const [recentNoticeList, setRecentNoticeList] = useState([])

  //FAQ
  const [recentFaqList, setRecentFaqList] = useState([])

  const { qcastState, setIsGlobalLoading } = useContext(QcastContext)
  const { fetchObjectList, initObjectList } = useMainContentsController()

  useEffect(() => {
    fetchObjectList()
    fetchNoticeList()
    fetchFaqList()
    return () => {
      initObjectList()
    }
  }, [])

  //공지사항 호출
  const fetchNoticeList = async () => {
    try {
      const param = {
        schNoticeTpCd: 'QC',
        schNoticeClsCd: 'NOTICE',
        startRow: 1,
        endRow: 1,
      }
      const noticeApiUrl = `api/board/list?${queryStringFormatter(param)}`
      await promiseGet({ url: noticeApiUrl }).then((res) => {
        if (res.status === 200) {
          setRecentNoticeList(res.data.data)
        } else {
          setRecentNoticeList([])
        }
      })
    } catch (error) {
      console.error('NOTICE fetching error:', error)
    }
  }

  //FAQ 호출
  const fetchFaqList = async () => {
    try {
      const param = {
        schNoticeTpCd: 'QC',
        schNoticeClsCd: 'FAQ',
        startRow: 1,
        endRow: 3,
      }
      const faqApiUrl = `api/board/list?${queryStringFormatter(param)}`
      await promiseGet({
        url: faqApiUrl,
      }).then((res) => {
        if (res.status === 200) {
          setRecentFaqList(res.data.data)
        } else {
          setRecentFaqList([])
        }
      })
    } catch (error) {
      console.error('FAQ fetching error:', error)
    }
  }

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

  return (
    <div className="main-product-list-wrap">
      <div className="main-product-list">
        <ProductItem num={1} name={getMessage('main.content.objectList')}>
          {qcastState?.objectList.length > 0 ? (
            <ul className="recently-list">
              {qcastState?.objectList.map((row) => {
                return (
                  <li
                    key={row.objectNo}
                    className="recently-item"
                    onClick={() => {
                      setIsGlobalLoading(true)
                      if (row.tempFlg === '0') {
                        router.push(`/management/stuff/detail?objectNo=${row.objectNo.toString()}`, { scroll: false })
                      } else {
                        router.push(`/management/stuff/tempdetail?objectNo=${row.objectNo.toString()}`, { scroll: false })
                      }
                    }}
                  >
                    <div className="item-inner">
                      <span className="time">{dayjs(row.lastEditDatetime).format('YYYY.MM.DD HH:mm:ss')}</span>
                      <span>{row.tempFlg === '0' ? row.objectNo : getMessage('stuff.gridData.tempObjectNo')}</span>
                      <span>{row.objectName ? row.objectName : '-'}</span>
                      <span>{row.saleStoreName}</span>
                    </div>
                  </li>
                )
              })}
            </ul>
          ) : (
            <div className="recently-no-data">
              <h3>{getMessage('main.content.objectList.noData1')}</h3>
              <p>{getMessage('main.content.objectList.noData2')}</p>
              <button type="button" className="btn-origin navy" onClick={() => router.push('/management/stuff/tempReg')}>
                + {getMessage('stuff.search.btn.register')}
              </button>
            </div>
          )}
        </ProductItem>
        <ProductItem num={2} name={getMessage('main.content.notice')}>
          {recentNoticeList.length > 0 ? (
            <div className="notice-box">
              <div className="notice-day pre">{dayjs(recentNoticeList[0]?.regDt).format('YYYY.MM.DD')}</div>
              <div className="notice-title">{recentNoticeList[0]?.title}</div>
              <div
                className="notice-contents"
                dangerouslySetInnerHTML={{ __html: recentNoticeList[0]?.contents ? recentNoticeList[0].contents.replaceAll('\n', '<br/>') : '' }}
              ></div>
            </div>
          ) : (
            <div className="recently-no-data">
              <h3>{getMessage('main.content.noBusiness')}</h3>
            </div>
          )}
        </ProductItem>
      </div>

      {open && <BoardDetailModal noticeNo={modalNoticeNo} setOpen={setOpen} />}
      <div className="main-product-list">
        <ProductItem num={3} name={getMessage('main.faq')}>
          {recentFaqList.length > 0 ? (
            <ul className="faq-list">
              {recentFaqList.map((row) => {
                return (
                  <li key={row.rowNumber} className="faq-item">
                    <div className="faq-item-inner">
                      <div className="faq-num pre">FAQ {row.totCnt - row.rowNumber + 1}</div>
                      <div
                        className="faq-title pre"
                        style={{ cursor: 'pointer' }}
                        onClick={() => {
                          setOpen(true)
                          setModalNoticeNo(row.noticeNo)
                        }}
                      >
                        {row.title}
                      </div>
                      <div className="faq-day pre">{dayjs(row.regDt).format('YYYY.MM.DD')}</div>
                    </div>
                  </li>
                )
              })}
            </ul>
          ) : (
            <div className="recently-no-data">
              <h3>{getMessage('main.content.noBusiness')}</h3>
            </div>
          )}
        </ProductItem>
        <ProductItem num={4} name={'Data Download'}>
          <div className="data-download-wrap">
            <button className="data-down" type="button" onClick={() => swalFire({ text: getMessage('main.content.alert.noFile'), type: 'alert' })}>
              <span>{getMessage('main.content.download1')}</span>
            </button>
            <button className="data-down" type="button" onClick={() => swalFire({ text: getMessage('main.content.alert.noFile'), type: 'alert' })}>
              <span>{getMessage('main.content.download2')}</span>
            </button>
          </div>
        </ProductItem>
        <ProductItem num={5} name={'Sales Contact info'}>
          <ul className="contact-info-list">
            <li className="info-item">
              <div className="icon-box">
                <Image src="/static/images/main/user.svg" alt="react" width={20} height={20} />
              </div>
              {(qcastState?.businessCharger && <div className="infor-data">{qcastState?.businessCharger}</div>) || (
                <div className="infor-data pre">{getMessage('main.content.noBusiness')}</div>
              )}
            </li>
            <li className="info-item">
              <div className="icon-box">
                <Image src="/static/images/main/mail.svg" alt="react" width={20} height={20} />
              </div>
              {(qcastState?.businessChargerMail && <div className="infor-data pre">{qcastState?.businessChargerMail}</div>) || (
                <div className="infor-data pre">{getMessage('main.content.noBusiness')}</div>
              )}
            </li>
          </ul>
        </ProductItem>
      </div>
    </div>
  )
}
