'use client'

import { useServey } from '@/hooks/useSurvey'
import { SurveyBasicRequest } from '@/types/Survey'
import { useRouter, useSearchParams } from 'next/navigation'
import { useState, useEffect } from 'react'
import { useSurveySaleTabState } from '@/store/surveySaleTabState'
import { usePopupController } from '@/store/popupController'
import { useAddressStore } from '@/store/addressStore'
import { useSessionStore } from '@/store/session'
// import { useUserType } from '@/hooks/useUserType'

const defaultBasicInfoForm: SurveyBasicRequest = {
  REPRESENTATIVE: '',
  STORE: null,
  CONSTRUCTION_POINT: null,
  INVESTIGATION_DATE: new Date().toLocaleDateString('en-CA'),
  BUILDING_NAME: null,
  CUSTOMER_NAME: null,
  POST_CODE: null,
  ADDRESS: null,
  ADDRESS_DETAIL: null,
  SUBMISSION_STATUS: false,
  SUBMISSION_DATE: null,
}

const REQUIRED_FIELDS: (keyof SurveyBasicRequest)[] = ['REPRESENTATIVE', 'BUILDING_NAME', 'CUSTOMER_NAME']

export default function BasicForm() {
  const searchParams = useSearchParams()
  const id = searchParams.get('id')
  const router = useRouter()

  const { setBasicInfoSelected } = useSurveySaleTabState()
  const { surveyDetail, createSurvey, isCreatingSurvey, updateSurvey, isUpdatingSurvey } = useServey(Number(id))

  const [basicInfoData, setBasicInfoData] = useState<SurveyBasicRequest>(defaultBasicInfoForm)

  const { addressData } = useAddressStore()
  const { session } = useSessionStore()

  const popupController = usePopupController()

  useEffect(() => {
    if (surveyDetail) {
      const { ID, UPT_DT, REG_DT, DETAIL_INFO, ...rest } = surveyDetail
      setBasicInfoData(rest)
    }
    if (addressData) {
      setBasicInfoData({
        ...basicInfoData,
        POST_CODE: addressData.post_code,
        ADDRESS: addressData.address,
        ADDRESS_DETAIL: addressData.address_detail,
      })
    }
    if (session?.isLoggedIn) {
      setBasicInfoData((prev) => ({
        ...prev,
        REPRESENTATIVE: session?.userId ?? '',
        STORE: session?.storeNm ?? '',
        CONSTRUCTION_POINT: session?.builderNo ?? '',
      }))
    }
    setBasicInfoSelected()
  }, [surveyDetail, addressData, session?.isLoggedIn, session?.userId, session?.storeNm, session?.builderNo])

  const focusInput = (input: keyof SurveyBasicRequest) => {
    const inputElement = document.getElementById(input)
    if (inputElement) {
      inputElement.focus()
    }
  }

  const validateSurvey = (basicInfoData: SurveyBasicRequest) => {
    const emptyField = REQUIRED_FIELDS.find((field) => !basicInfoData[field])
    if (emptyField) {
      focusInput(emptyField)
      return false
    }
    return true
  }

  const handleChange = (key: keyof SurveyBasicRequest, value: string) => {
    setBasicInfoData({ ...basicInfoData, [key]: value })
  }

  const handleSave = async (isTemporary: boolean) => {
    if (id) {
      // updateSurvey(basicInfoData)
      alert('保存しました。')
      // router.push(`/survey-sale/${id}?tab=basic-info`)
    }
    if (isTemporary) {
      // const saveId = await createSurvey(basicInfoData)
      alert('一時保存されました。')
      // router.push(`/survey-sale/${saveId}?tab=basic-info`)
    } else {
      if (validateSurvey(basicInfoData)) {
        // const saveId = await createSurvey(basicInfoData)
        alert('保存しました。')
        // router.push(`/survey-sale/${saveId}?tab=basic-info`)
      }
    }
  }

  if (isCreatingSurvey || isUpdatingSurvey) {
    return <div>Loading...</div>
  }

  return (
    <>
      <div className="sale-frame">
        <div className="data-form-wrap">
          <div className="data-input-form-bx">
            <div className="data-input-form-tit">担当者名</div>
            <input
              type="text"
              className="input-frame"
              id="representative"
              value={session?.userId ? session?.userId : basicInfoData.REPRESENTATIVE}
              onChange={(e) => handleChange('REPRESENTATIVE', e.target.value)}
            />
          </div>
          {(session?.role === 'Builder' || session?.role?.includes('Admin')) && (
            <>
              <div className="data-input-form-bx">
                <div className="data-input-form-tit">販売店</div>
                <input
                  type="text"
                  className="input-frame"
                  id="store"
                  value={session?.storeNm ? session?.storeNm : basicInfoData.STORE ?? ''}
                  onChange={(e) => handleChange('STORE', e.target.value)}
                />
              </div>
            </>
          )}
          {(session?.role === 'Partner' || session?.role === 'Builder') && (
            <div className="data-input-form-bx">
              <div className="data-input-form-tit">施工店</div>
              <input
                type="text"
                className="input-frame"
                id="construction_point"
                value={session?.builderNo ? session?.builderNo : basicInfoData.CONSTRUCTION_POINT ?? ''}
                onChange={(e) => handleChange('CONSTRUCTION_POINT', e.target.value)}
              />
            </div>
          )}
        </div>
      </div>

      <div className="sale-frame">
        <div className="data-form-wrap">
          <div className="data-input-form-bx">
            <div className="data-input-form-tit">現地調査日</div>
            <div className="date-input">
              <button className="date-btn">
                <i className="date-icon"></i>
              </button>
              <input
                type="date"
                className="date-frame"
                id="INVESTIGATION_DATE"
                value={basicInfoData.INVESTIGATION_DATE ?? ''}
                onChange={(e) => handleChange('INVESTIGATION_DATE', e.target.value)}
              />
            </div>
          </div>
          <div className="data-input-form-bx">
            <div className="data-input-form-tit">建物名</div>
            <input
              type="text"
              className="input-frame"
              id="BUILDING_NAME"
              value={basicInfoData.BUILDING_NAME ?? ''}
              onChange={(e) => handleChange('BUILDING_NAME', e.target.value)}
            />
          </div>
          <div className="data-input-form-bx">
            <div className="data-input-form-tit">顧客名</div>
            <input
              type="text"
              className="input-frame"
              id="CUSTOMER_NAME"
              value={basicInfoData.CUSTOMER_NAME ?? ''}
              onChange={(e) => handleChange('CUSTOMER_NAME', e.target.value)}
            />
          </div>
          <div className="data-input-form-bx">
            <div className="data-input-form-tit">建物の住所</div>
            <div className="form-flex">
              <div className="form-bx">
                <input type="text" className="input-frame" id="POST_CODE" value={basicInfoData.POST_CODE ?? ''} readOnly />
              </div>
              <div className="form-bx">
              <input
                type="text"
                className="input-frame"
                name="address"
                id="ADDRESS"
                value={basicInfoData.ADDRESS ?? ''}
              />
              </div>
            </div>
            <div className="form-btn">
              <button className="btn-frame n-blue icon" onClick={() => popupController.setZipCodePopup(true)}>
                郵便番号<i className="btn-arr"></i>
              </button>
            </div>
          </div>
          <div className="data-input-form-bx">
            <div className="data-input-form-tit">市区町村名, 以後の住所</div>
            <input
              type="text"
              className="input-frame"
              id="ADDRESS_DETAIL"
              value={basicInfoData.ADDRESS_DETAIL ?? ''}
              onChange={(e) => handleChange('ADDRESS_DETAIL', e.target.value)}
            />
          </div>
        </div>
        <div className="btn-flex-wrap">
          <div className="btn-bx">
            <button className="btn-frame n-blue icon" onClick={() => handleSave(true)}>
              一時保存<i className="btn-arr"></i>
            </button>
          </div>
          <div className="btn-bx">
            <button className="btn-frame red icon" onClick={() => handleSave(false)}>
              保存<i className="btn-arr"></i>
            </button>
          </div>
          <div className="btn-bx">
            <button className="btn-frame n-blue icon" onClick={() => router.push('/survey-sale')}>
              リスト<i className="btn-arr"></i>
            </button>
          </div>
        </div>
      </div>
    </>
  )
}
