'use client'
import React, { useEffect, useState } from 'react'

import { useRouter } from 'next/navigation'
import { useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil'
import { modalContent, modalState, modalProps } from '@/store/modalAtom'
import { sessionStore } from '@/store/commonAtom'
import { useAxios } from '@/hooks/useAxios'
import { globalLocaleStore } from '@/store/localeAtom'
import MainContents from './main/MainContents'
import { useMessage } from '@/hooks/useMessage'
import { stuffSearchState } from '@/store/stuffAtom'
import { useForm } from 'react-hook-form'
import '@/styles/contents.scss'
import ChangePasswordPop from './main/ChangePasswordPop'
import { searchState } from '@/store/boardAtom'
export default function MainPage() {
  const [sessionState, setSessionState] = useRecoilState(sessionStore)

  const globalLocaleState = useRecoilValue(globalLocaleStore)

  const { get } = useAxios(globalLocaleState)
  const router = useRouter()
  const { getMessage } = useMessage()

  const [searchTxt, setSearchTxt] = useState('')

  const [searchRadioType, setSearchRadioType] = useState('object')
  //컨텐츠 관련
  const [saleStoreId, setSaleStoreId] = useState('')
  const [saleStoreName, setSaleStoreName] = useState('')

  const [objectList, setObjectList] = useState([])
  const [businessCharger, setBusinessCharger] = useState('')
  const [businessChargerMail, setBusinessChargerMail] = useState('')
  const [businessChargerTel, setBusinessChargerTel] = useState('')

  const [stuffSearch, setStuffSearch] = useRecoilState(stuffSearchState)

  const [searchForm, setSearchForm] = useRecoilState(searchState)

  useEffect(() => {
    if (sessionState.pwdInitYn === 'Y') {
      fetchObjectList()
    }
  }, [sessionState])

  const fetchObjectList = async () => {
    try {
      // const apiUrl = `/api/main-page/object/X167/list`
      const apiUrl = `/api/main-page/object/${sessionState?.storeId}/list`
      const res = await get({ url: apiUrl })
      if (res) {
        setSaleStoreId(res.saleStoreId)
        setSaleStoreName(res.saleStoreName)
        setObjectList(res.objectList)
        setBusinessCharger(res.businessCharger)
        setBusinessChargerMail(res.businessChargerMail)
        setBusinessChargerTel(res.businessChargerTel)
      }
    } catch (error) {
      console.error('MAIN API fetching error:', error)
    }
  }

  // 엔터 이벤트
  const handleByOnKeyUp = (e) => {
    if (e.key === 'Enter') {
      //물건번호 일떄
      if (searchRadioType === 'object') {
        setStuffSearch({
          ...stuffSearch,
          schObjectNo: searchTxt,
          code: 'M',
        })
        router.push('/management/stuff')
      } else {
        setSearchForm({ ...searchForm, searchValue: searchTxt, mainFlag: 'Y' })
        router.push('/community/faq')
      }
    }
  }

  // 라디오 변경 이벤트
  const handleOnChangeRadio = (e) => {
    setSearchRadioType(e.target.value)
  }

  // 돋보기 클릭
  const handleOnSubmit = () => {
    if (searchRadioType === 'object') {
      setStuffSearch({
        ...stuffSearch,
        schObjectNo: searchTxt,
        code: 'M',
      })

      router.push('/management/stuff')
    } else {
      setSearchForm({ ...searchForm, searchValue: searchTxt, mainFlag: 'Y' })
      router.push('/community/faq')
    }
  }

  return (
    <>
      {(sessionState?.pwdInitYn !== 'N' && (
        <>
          <div className="background-bord"></div>
          <div className="main-contents">
            <div className="store-id-wrap">
              <div className="store-id-box">
                <div className="store-id-title">
                  {getMessage('main.storeId')}/ {getMessage('main.storeName')}
                </div>
              </div>
              <span className="store-arr"></span>
              <div className="store-id-name">
                {saleStoreId} / {saleStoreName}
              </div>
            </div>
            <div className="main-search-wrap">
              <div className="search-raido-wrap">
                <div className="d-check-radio">
                  <input type="radio" name="radio01" id="object" value="object" defaultChecked onChange={handleOnChangeRadio} />
                  <label htmlFor="object">{getMessage('main.objectNo')}</label>
                </div>
                <div className="d-check-radio">
                  <input type="radio" name="radio01" id="faq" value="faq" onChange={handleOnChangeRadio} />
                  <label htmlFor="faq">{getMessage('main.faq')}</label>
                </div>
              </div>
              <div className="search-input-box">
                <input
                  type="text"
                  className="main-search"
                  placeholder=""
                  onKeyUp={handleByOnKeyUp}
                  onChange={(e) => {
                    setSearchTxt(e.target.value)
                  }}
                />
                <button className="search-icon" onClick={handleOnSubmit}></button>
              </div>
            </div>
            <MainContents
              objectList={objectList}
              businessCharger={businessCharger}
              businessChargerMail={businessChargerMail}
              businessChargerTel={businessChargerTel}
            />
          </div>
        </>
      )) || (
        <>
          <ChangePasswordPop />
        </>
      )}
    </>
  )
}
