'use client'

import LoadMoreButton from '@/components/LoadMoreButton'
import { useServey } from '@/hooks/useSurvey'
import { useEffect, useState, useMemo, useRef } from 'react'
import { useRouter, usePathname } from 'next/navigation'
import SearchForm from './SearchForm'
import { useSurveyFilterStore } from '@/store/surveyFilterStore'
import { useSessionStore } from '@/store/session'
import type { SurveyBasicInfo } from '@/types/Survey'

export default function ListTable() {
  const router = useRouter()
  const pathname = usePathname()

  const { surveyList, isLoadingSurveyList } = useServey()
  const { offset, setOffset } = useSurveyFilterStore()

  const { session } = useSessionStore()

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

  useEffect(() => {
    setOffset(0)
    setHeldSurveyList([])
  }, [pathname])

  useEffect(() => {
    if (!session.isLoggedIn || !('data' in surveyList)) return
    if ('count' in surveyList && surveyList.count > 0) {
      if (offset > 0) {
        setHeldSurveyList((prev) => [...prev, ...surveyList.data])
      } else {
        setHeldSurveyList(surveyList.data)
      }
      setHasMore(surveyList.count > offset + 10)
    } else {
      setHeldSurveyList([])
      setHasMore(false)
    }
  }, [surveyList, offset, session.isLoggedIn])

  const handleDetailClick = (id: number) => {
    router.push(`/survey-sale/${id}`)
  }

  // TODO: 로딩 처리 필요

  return (
    <>
      <SearchForm memberRole={session?.role ?? ''} userNm={session?.userNm ?? ''} />
        <div className="sale-frame">
          {heldSurveyList.length > 0 ? (
            <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.srlNo}</div>
                    <div className="sale-item-date">{survey.investigationDate}</div>
                  </div>
                  <div className="sale-item-tit">{survey.buildingName}</div>
                  <div className="sale-item-customer">{survey.customerName}</div>
                  <div className="sale-item-update-bx">
                    <div className="sale-item-name">{survey.representative}</div>
                    <div className="sale-item-update">{new Date(survey.uptDt).toLocaleString()}</div>
                  </div>
                </div>
                </li>
              ))}
            </ul>
          ) : (
            <div className="compliace-nosearch">
              <span className="mb10">作成された物件はありません。</span>
            </div>
          )}
          <div className="sale-edit-btn">
            <LoadMoreButton hasMore={hasMore} onLoadMore={() => setOffset(offset + 10)} />
          </div>
        </div>
    </>
  )
}
