'use client'

import LoadMoreButton from '@/components/LoadMoreButton'
import { useSurvey } from '@/hooks/useSurvey'
import { useEffect, useState } from 'react'
import { useRouter, usePathname, useSearchParams } from 'next/navigation'
import SearchForm from './SearchForm'
import { useSurveyFilterStore } from '@/store/surveyFilterStore'
import { useSessionStore } from '@/store/session'
import type { SurveyBasicInfo } from '@/types/Survey'
import { formatDateTime, formatDate } from '@/utils/common-utils'

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

  const { surveyList, isLoadingSurveyList } = useSurvey()
  const { offset, setOffset, setIsMySurvey, reset } = useSurveyFilterStore()

  const { session } = useSessionStore()

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

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

  useEffect(() => {
    if (searchParams.get('isMySurvey') === 'true') {
      setIsMySurvey(session.userId)
      router.replace('/survey-sale')
    } else if (searchParams.get('isMySurvey') === 'false') {
      reset()
      router.replace('/survey-sale')
    }
  }, [searchParams])

  useEffect(() => {
    if (isLoadingSurveyList || !session.isLoggedIn) 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, isLoadingSurveyList, searchParams])

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

  return (
    <>
      <SearchForm memberRole={session?.role ?? ''} userId={session?.userId ?? ''} />
      <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">
                    {survey.srlNo?.startsWith('一時保存') ? (
                      <div className="sale-data-num">{survey.srlNo}</div>
                    ) : (
                      <div className="sale-item-num">{survey.srlNo}</div>
                    )}
                    <div className="sale-item-date">{formatDate(survey.regDt)}</div>
                  </div>
                  <div className="sale-item-tit">{survey.buildingName === null ? '-' : survey.buildingName}</div>
                  <div className="sale-item-customer">{survey.customerName === null ? '-' : survey.customerName}</div>
                  <div className="sale-item-update-bx">
                    <div className="sale-item-name">{survey.representative}</div>
                    <div className="sale-item-update">{formatDateTime(survey.uptDt)}</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>
    </>
  )
}
