'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'

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', 'store', 'construction_point']

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 popupController = usePopupController()

  useEffect(() => {
    if (surveyDetail) {
      const { id, updated_at, created_at, detail_info, ...rest } = surveyDetail
      setBasicInfoData(rest)
    }
    if (addressData) {
      setBasicInfoData({
        ...basicInfoData,
        post_code: addressData.post_code,
        address: addressData.address,
        address_detail: addressData.address_detail,
      })
    }
    setBasicInfoSelected()
  }, [surveyDetail, addressData])

  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)
      router.push(`/survey-sale/${id}?tab=basic-info`)
    }
    if (isTemporary) {
      const saveId = await createSurvey(basicInfoData)
      alert('save success temporary id: ' + saveId)
      router.push(`/survey-sale/${saveId}?tab=basic-info`)
    } else {
      if (validateSurvey(basicInfoData)) {
        const saveId = await createSurvey(basicInfoData)
        alert('save success id: ' + saveId)
        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={basicInfoData.representative}
              onChange={(e) => handleChange('representative', e.target.value)}
              required
            />
          </div>
          <div className="data-input-form-bx">
            <div className="data-input-form-tit">販売店</div>
            <input
              type="text"
              className="input-frame"
              id="store"
              value={basicInfoData.store ?? ''}
              onChange={(e) => handleChange('store', e.target.value)}
              required
            />
          </div>
          <div className="data-input-form-bx">
            <div className="data-input-form-tit">施工店</div>
            <input
              type="text"
              className="input-frame"
              id="construction_point"
              value={basicInfoData.construction_point ?? ''}
              onChange={(e) => handleChange('construction_point', e.target.value)}
              required
            />
          </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 ?? ''}
                  onChange={(e) => handleChange('post_code', e.target.value)}
                />
              </div>
              <div className="form-bx">
                <select
                  className="select-form"
                  name="address"
                  id="address"
                  value={basicInfoData.address ?? ''}
                  onChange={(e) => handleChange('address', e.target.value)}
                >
                  <option value="">東京都</option>
                  <option value="">東京都</option>
                  <option value="">東京都</option>
                  <option value="">東京都</option>
                  <option value="">東京都</option>
                </select>
              </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>
    </>
  )
}
