'use client'

import { useEffect, useState } from 'react'
import LoadMoreButton from '../../LoadMoreButton'
import { useInquiry } from '@/hooks/useInquiry'
import { InquiryList } from '@/types/Inquiry'
import { usePathname, useRouter } from 'next/navigation'
import { useInquiryFilterStore } from '@/store/inquiryFilterStore'
import { useSessionStore } from '@/store/session'
import ListForm from './ListForm'

const badgeStyle = [
  {
    id: 'Y',
    label: '回答完了',
    color: 'orange',
  },
  {
    id: 'N',
    label: '回答待ち',
    color: 'blue',
  },
]
export default function ListTable() {
  const router = useRouter()
  const pathname = usePathname()

  const { inquiryList, isLoadingInquiryList } = useInquiry(undefined, true)
  const { inquiryListRequest, setInquiryListRequest, reset, offset, setOffset } = useInquiryFilterStore()

  const [hasMore, setHasMore] = useState(false)

  const [heldInquiryList, setHeldInquiryList] = useState<InquiryList[]>([])

  const { session } = useSessionStore()

  useEffect(() => {
    setOffset(1)
    setHeldInquiryList([])
  }, [pathname])

  useEffect(() => {
    if (!session.isLoggedIn || isLoadingInquiryList) return
    if (session.isLoggedIn) {
      setInquiryListRequest({ ...inquiryListRequest, storeId: session.storeId ?? '', loginId: session.userId ?? '' })
    }
    if (inquiryList.length > 0 && inquiryList[0].totCnt > 0) {
      if (offset > 1) {
        setHeldInquiryList([...heldInquiryList, ...inquiryList])
      } else {
        setHeldInquiryList(inquiryList)
      }
      setHasMore(inquiryList[0].totCnt > offset + 9)
    } else {
      setHeldInquiryList([])
      setHasMore(false)
    }
  }, [session, inquiryList])

  /** 내 문의 필터 처리 - 체크 시 자신의 문의 목록만 조회 */
  const handleMyInquiry = () => {
    setOffset(1)
    setInquiryListRequest({
      ...inquiryListRequest,
      schRegId: inquiryListRequest.schRegId ? null : session.userId,
    })
  }

  /** 답변 여부 필터 처리리 */
  const handleFilter = (e: React.ChangeEvent<HTMLSelectElement>) => {
    switch (e.target.value) {
      case 'N':
        setInquiryListRequest({ ...inquiryListRequest, schAnswerYn: 'N' })
        break
      case 'Y':
        setInquiryListRequest({ ...inquiryListRequest, schAnswerYn: 'Y' })
        break
      default:
        reset()
        break
    }
  }

  return (
    <>
      <ListForm />
      <div className="sale-frame">
        <div className="inquiry-table-filter">
          <div className="filter-check">
            <div className="check-form-box">
              <input type="checkbox" id="ch01" onChange={handleMyInquiry} checked={inquiryListRequest.schRegId === session.userId} />
              <label htmlFor="ch01">私が書いたお問い合わせ</label>
            </div>
          </div>
          <div className="filter-select">
            <select className="select-form" name="" id="" onChange={(e) => handleFilter(e)}>
              <option value="">全体</option>
              <option value="N">回答待ち</option>
              <option value="Y">回答完了</option>
            </select>
          </div>
        </div>
        <div className="inquiry-list-wrap">
          <div className="inquiry-list-tit">
            合計 <span>{heldInquiryList.length > 0 ? heldInquiryList[0].totCnt : 0}</span>個
          </div>
          <ul className="inquiry-list">
            {heldInquiryList.length === 0 || (heldInquiryList.length > 0 && heldInquiryList[0].totCnt === 0) ? (
              <li className="inquiry-item">
                <div className="inquiry-item-bx nodata">
                  <div className="inquiry-item-nodata">照会されたデータがありません。</div>
                </div>
              </li>
            ) : (
              heldInquiryList.map((inquiry: InquiryList) => (
                <li className="inquiry-item" key={inquiry.qnaNo} onClick={() => router.push(`/inquiry/${inquiry.qnaNo}`)}>
                  <div className="inquiry-item-bx">
                    <div className="inquiry-item-category">
                      <span>{inquiry.qnaClsLrgCd}</span>
                      <span>{inquiry.qnaClsMidCd}</span>
                      <span>{inquiry.qnaClsSmlCd}</span>
                    </div>
                    <div className="inquiry-item-tit">{inquiry.qstTitle}</div>
                    <div className="inquiry-item-date">{inquiry.regDt}</div>
                    <div className={`inquiry-badge badge ${badgeStyle.find((badge) => badge.id === inquiry.answerYn)?.color}`}>
                      {badgeStyle.find((badge) => badge.id === inquiry.answerYn)?.label}
                    </div>
                  </div>
                </li>
              ))
            )}
          </ul>
        </div>
        <div className="sale-edit-btn">
          <LoadMoreButton
            hasMore={hasMore}
            onLoadMore={() => {
              setOffset(offset + 10)
            }}
          />
        </div>
      </div>
    </>
  )
}
