'use client'

import LoadMoreButton from '@/components/LoadMoreButton'
import { useServey } from '@/hooks/useSurvey'
import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import SearchForm from './SearchForm'
import { useSurveyFilterStore } from '@/store/surveyFilterStore'
import { useSessionStore } from '@/store/session'

export default function ListTable() {
  const router = useRouter()
  const { surveyList, isLoadingSurveyList, surveyListCount } = useServey()
  const { offset, setOffset } = useSurveyFilterStore()

  const [heldSurveyList, setHeldSurveyList] = useState<typeof surveyList>([])
  const [hasMore, setHasMore] = useState(false)

  const { session } = useSessionStore()

  useEffect(() => {
    if (surveyList && surveyList.length > 0) {
      if (offset === 0) {
        setHeldSurveyList(surveyList)
      } else {
        const remainingList = heldSurveyList.slice(offset, offset + 10)
        if (JSON.stringify(remainingList) !== JSON.stringify(surveyList)) {
          setHeldSurveyList((prev) => [...prev, ...surveyList])
        }
      }
      setHasMore(surveyListCount > offset + 10)
    }
  }, [surveyList, surveyListCount, offset, session?.role])

  const handleDetailClick = (id: number) => {
    router.push(`/survey-sale/${id}`)
  }
  const handleItemsInit = () => {
    setHeldSurveyList([])
    setOffset(0)
  }

  // TODO: 로딩 처리 필요

  return (
    <>
      <SearchForm onItemsInit={handleItemsInit} memberRole={session?.role ?? ''} userId={session?.userId ?? ''} />
      {heldSurveyList.length > 0 ? (
        <div className="sale-frame">
          <ul className="sale-list-wrap">
            {heldSurveyList.map((survey) => (
              <li className="sale-list-item cursor-pointer" key={survey.ID} onClick={() => handleDetailClick(survey.ID)}>
                <div className="sale-item-bx">
                  <div className="sale-item-date-bx">
                    <div className="sale-item-num">{survey.ID}</div>
                    <div className="sale-item-date">{survey.INVESTIGATION_DATE}</div>
                  </div>
                  <div className="sale-item-tit">{survey.BUILDING_NAME}</div>
                  <div className="sale-item-customer">{survey.CUSTOMER_NAME}</div>
                  <div className="sale-item-update-bx">
                    <div className="sale-item-name">{survey.REPRESENTATIVE}</div>
                    <div className="sale-item-update">{new Date(survey.UPT_DT).toLocaleString()}</div>
                  </div>
                </div>
              </li>
            ))}
          </ul>
          <div className="sale-edit-btn">
            <LoadMoreButton hasMore={hasMore} onLoadMore={() => setOffset(offset + 10)} />
          </div>
        </div>
      ) : (
        <div>
          <p>作成された物件はありません。</p>
        </div>
      )}
    </>
  )
}
