'use client'

import type { Mode, SurveyBasicRequest, SurveyDetailRequest } from '@/types/Survey'
import { useEffect, useState } from 'react'
import ButtonForm from './ButtonForm'
import BasicForm from './BasicForm'
import RoofForm from './RoofForm'
import { useParams, useRouter, useSearchParams, usePathname } from 'next/navigation'
import { useSurvey } from '@/hooks/useSurvey'
import { useSessionStore } from '@/store/session'
import DataTable from './DataTable'
import { usePopupController } from '@/store/popupController'

const roofInfoForm: SurveyDetailRequest = {
  contractCapacity: null,
  retailCompany: null,
  supplementaryFacilities: null,
  supplementaryFacilitiesEtc: null,
  installationSystem: null,
  installationSystemEtc: null,
  constructionYear: null,
  constructionYearEtc: null,
  roofMaterial: null,
  roofMaterialEtc: null,
  roofShape: null,
  roofShapeEtc: null,
  roofSlope: null,
  houseStructure: '1',
  houseStructureEtc: null,
  rafterMaterial: '1',
  rafterMaterialEtc: null,
  rafterSize: null,
  rafterSizeEtc: null,
  rafterPitch: null,
  rafterPitchEtc: null,
  rafterDirection: '1',
  openFieldPlateKind: null,
  openFieldPlateKindEtc: null,
  openFieldPlateThickness: null,
  leakTrace: false,
  waterproofMaterial: null,
  waterproofMaterialEtc: null,
  insulationPresence: '1',
  insulationPresenceEtc: null,
  structureOrder: null,
  structureOrderEtc: null,
  installationAvailability: null,
  installationAvailabilityEtc: null,
  memo: null,
}

const basicInfoForm: SurveyBasicRequest = {
  representative: '',
  representativeId: null,
  store: null,
  storeId: null,
  constructionPoint: null,
  constructionPointId: null,
  investigationDate: new Date().toLocaleDateString('en-CA'),
  buildingName: null,
  customerName: null,
  postCode: null,
  address: null,
  addressDetail: null,
  submissionStatus: false,
  submissionDate: null,
  submissionTargetId: null,
  submissionTargetNm: null,
  srlNo: null,
}

export default function DetailForm() {
  const id = useParams().id

  const modeset = !Number.isNaN(Number(id)) ? 'READ' : 'CREATE'

  const { surveyDetail, isLoadingSurveyDetail } = useSurvey(Number(id))
  const { session } = useSessionStore()
  const searchParams = useSearchParams()
  const popupController = usePopupController()
  const router = useRouter()
  const pathname = usePathname()

  const [mode, setMode] = useState<Mode>(modeset)

  const [basicInfoData, setBasicInfoData] = useState<SurveyBasicRequest>(() => ({
    ...basicInfoForm,
    representative: session?.userNm ?? '',
    representativeId: session?.userId ?? null,
    store: session?.storeNm ?? null,
    storeId: session?.storeId ?? null,
    constructionPoint: session?.builderNm ?? null,
    constructionPointId: session?.builderId ?? null,
  }))
  const [roofInfoData, setRoofInfoData] = useState<SurveyDetailRequest>(roofInfoForm)

  /** 제출 팝업 처리 - createSurvey 이후 popup 처리 시 노드 삽입 오류로 인해 별도 처리 */
  useEffect(() => {
    const show = searchParams.get('show')
    if (show === 'true' && !isLoadingSurveyDetail) {
      popupController.setSurveySaleSubmitPopup(true)
      router.replace(pathname)
    }
  }, [searchParams, pathname, isLoadingSurveyDetail])

  /** 세션 데이터가 변경될 때 기본 정보 업데이트 */
  useEffect(() => {
    if (!session?.isLoggedIn) return
    setBasicInfoData((prev) => ({
      ...prev,
      representative: session.userNm ?? '',
      representativeId: session.userId ?? null,
      store: session.storeNm ?? null,
      storeId: session.storeId ?? null,
      constructionPoint: session.builderNm ?? null,
      constructionPointId: session.builderId ?? null,
    }))
  }, [session?.isLoggedIn])

  /** 조사매물 상세 데이터 업데이트 */
  useEffect(() => {
    if (!isLoadingSurveyDetail && surveyDetail && (mode === 'EDIT' || mode === 'READ')) {
      const { id, uptDt, regDt, detailInfo, ...rest } = surveyDetail
      setBasicInfoData((prev) => ({
        ...prev,
        ...rest,
      }))

      if (detailInfo) {
        const { id, uptDt, regDt, basicInfoId, ...rest } = detailInfo
        setRoofInfoData(rest)
      }
    }
  }, [mode, isLoadingSurveyDetail, surveyDetail])

  const data = {
    basic: basicInfoData,
    roof: roofInfoData,
  }

  const buttonFormProps = { mode, setMode, data }

  return (
    <>
      {mode === 'READ' && surveyDetail && <DataTable surveyDetail={surveyDetail} />}
      <div className="sale-detail-toggle-wrap">
        <BasicForm basicInfo={basicInfoData} setBasicInfo={setBasicInfoData} mode={mode} session={session} />
        <RoofForm roofInfo={roofInfoData} setRoofInfo={setRoofInfoData} mode={mode} />
        <ButtonForm {...buttonFormProps} />
      </div>
    </>
  )
}
