import React, { useEffect, useState } 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 { sessionStore } from '@/store/commonAtom'
import MainSkeleton from '../ui/MainSkeleton'

export default function MainContents() {
  const { getMessage } = useMessage()
  const router = useRouter()
  const globalLocaleState = useRecoilValue(globalLocaleStore)
  const { promiseGet, get } = useAxios(globalLocaleState)

  const sessionState = useRecoilValue(sessionStore)

  //최근 물건
  const [objectList, setObjectList] = useState([])

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

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

  //Sales Contact info
  const [businessCharger, setBusinessCharger] = useState(null)
  const [businessChargerMail, setBusinessChargerMail] = useState(null)

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

  //최근 갱신 물건목록 / Sales Contact info 정보
  const fetchObjectList = async () => {
    try {
      const apiUrl = `/api/main-page/object/${sessionState?.storeId}/list`
      await promiseGet({
        url: apiUrl,
      }).then((res) => {
        if (res.status === 200) {
          setObjectList(res.data.objectList)
          setBusinessCharger(res.data.businessCharger)
          setBusinessChargerMail(res.data.businessChargerMail)
        } else {
          setObjectList([])
          setBusinessCharger(null)
          setBusinessChargerMail(null)
        }
      })
    } catch (error) {
      console.error('MAIN API fetching error:', error)
    }
  }

  //공지사항 호출
  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)
    }
  }

  return (
    <div className="main-product-list-wrap">
      <div className="main-product-list">
        <ProductItem num={1} name={getMessage('main.content.objectList')}>
          {objectList.length > 0 ? (
            <ul className="recently-list">
              {objectList.map((row) => {
                return (
                  <li
                    key={row.objectNo}
                    className="recently-item"
                    onClick={() => {
                      if (row.objectNo.substring(0, 1) === 'R') {
                        router.push(`/management/stuff/detail?objectNo=${row.objectNo.toString()}`)
                      } else {
                        router.push(`/management/stuff/tempdetail?objectNo=${row.objectNo.toString()}`)
                      }
                    }}
                  >
                    <div className="item-inner">
                      <span className="time">{dayjs(row.lastEditDatetime).format('YYYY.MM.DD HH:mm:ss')}</span>
                      <span>{row.objectNo}</span>
                      <span>{row.objectName}</span>
                      <span>{row.saleStoreName}</span>
                    </div>
                  </li>
                )
              })}
            </ul>
          ) : (
            <MainSkeleton />
          )}
        </ProductItem>
        <ProductItem num={2} name={getMessage('main.content.notice')}>
          <div className="notice-box">
            {recentNoticeList.length > 0 ? (
              <>
                <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">{recentNoticeList[0]?.contents}</div>
              </>
            ) : null}
          </div>
        </ProductItem>
      </div>
      <div className="main-product-list">
        <ProductItem num={3} name={getMessage('main.faq')}>
          <ul className="faq-list">
            {recentFaqList.length > 0 ? (
              <>
                {recentFaqList.map((row) => {
                  return (
                    <li key={row.rowNumber} className="faq-item">
                      <div className="faq-item-inner">
                        <div className="faq-num pre">FAQ {row.noticeNo}</div>
                        <div className="faq-title pre">{row.title}</div>
                        <div className="faq-day pre">{dayjs(row.regDt).format('YYYY.MM.DD')}</div>
                      </div>
                    </li>
                  )
                })}
              </>
            ) : null}
          </ul>
        </ProductItem>
        <ProductItem num={4} name={'Data Download'}>
          <div className="data-download-wrap">
            <button className="data-down">
              <span>{getMessage('main.content.download1')}</span>
            </button>
            <button className="data-down">
              <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>
              {(businessCharger && <div className="infor-data">{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>
              {(businessChargerMail && <div className="infor-data pre">{businessChargerMail}</div>) || (
                <div className="infor-data pre">{getMessage('main.content.noBusiness')}</div>
              )}
            </li>
          </ul>
        </ProductItem>
      </div>
    </div>
  )
}
