'use client'

import { useSurveySaleTabState } from '@/store/surveySaleTabState'
import { usePathname, useRouter, useSearchParams, useParams } from 'next/navigation'
import { useEffect } from 'react'

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

  const searchParams = useSearchParams()
  const id = searchParams.get('id')
  const isTemp = searchParams.get('isTemp')

  const params = useParams()
  const detailId = params.id

  const { basicInfoSelected, roofInfoSelected, reset, setBasicInfoSelected, setRoofInfoSelected } = useSurveySaleTabState()

  useEffect(() => {
    return () => {
      reset()
    }
  }, [reset])

  if (pathname === '/survey-sale') {
    return null
  }

  const scrollSection = (section: string) => {
    const sectionElement = document.getElementById(section)
    if (sectionElement) {
      sectionElement.scrollIntoView({ behavior: 'smooth' })
    }
  }

  const handleBasicInfoClick = () => {
    // if (id) {
    //   router.push(`/survey-sale/basic-info?id=${id}`)
    //   return
    // }
    if (detailId) {
      router.push(`/survey-sale/${detailId}`)
      return
    }
    scrollSection('basic-form-section')

    setBasicInfoSelected()
  }

  const handleRoofInfoClick = () => {
    // if (id) {
    //   if (isTemp === 'true') {
    //     alert('基本情報が一時保存された状態です。')
    //     return
    //   }
    //   router.push(`/survey-sale/roof-info?id=${id}`)
    //   return
    // }
    if (detailId) {
      router.push(`/survey-sale/${detailId}?tab=roof-info`)
      return
    }
    if (pathname === '/survey-sale/basic-info') {
      alert('基本情報を先に保存してください。')
      return null
    }
    // if (pathname === '/survey-sale/regist') {
    scrollSection('roof-form-section')
    // }
    setRoofInfoSelected()
  }

  return (
    <>
      <div className="sale-detail-tab-relative">
        <div className="sale-detail-tab-wrap">
          <div className="sale-detail-tab-inner">
            <button className={`sale-detail-tab ${basicInfoSelected ? 'act' : ''}`} onClick={handleBasicInfoClick}>
              基本情報
            </button>
            <button className={`sale-detail-tab ${roofInfoSelected ? 'act' : ''}`} onClick={handleRoofInfoClick}>
              電気 / 屋根情報
            </button>
          </div>
        </div>
      </div>
    </>
  )
}
