'use client'

import { useEffect, useState } from 'react'
import type { SurveyBasicRequest } from '@/types/Survey'
import type { Mode } from 'fs'
import { usePopupController } from '@/store/popupController'
import { useAddressStore } from '@/store/addressStore'
import { SessionData } from '@/types/Auth'

interface BasicFormProps {
  basicInfo: SurveyBasicRequest
  setBasicInfo: (basicInfo: SurveyBasicRequest) => void
  mode: Mode
  session: SessionData
}

export default function BasicForm({ basicInfo, setBasicInfo, mode, session }: BasicFormProps) {
  const [isFlip, setIsFlip] = useState<boolean>(true)
  const { addressData, resetAddressData } = useAddressStore()
  const popupController = usePopupController()

  useEffect(() => {
    if (!addressData) return
    setBasicInfo({
      ...basicInfo,
      postCode: addressData.post_code.slice(0, 3) + '-' + addressData.post_code.slice(3),
      address: addressData.address,
      addressDetail: addressData.address_detail,
    })
    resetAddressData()
  }, [addressData])

  const handleAddressInitiate = () => {
    setBasicInfo({
      ...basicInfo,
      postCode: null,
      address: null,
      addressDetail: null,
    })
  }

  return (
    <>
      <div className={`sale-detail-toggle-bx ${isFlip ? 'act' : ''}`}>
        <div className="sale-detail-toggle-head" onClick={() => setIsFlip(!isFlip)}>
          <div className="sale-detail-toggle-name">基本情報</div>
          <div className="sale-detail-toggle-btn-wrap">
            <button className="sale-detail-toggle-btn"></button>
          </div>
        </div>
        <div className="sale-detail-toggle-cont">
          <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"
                  readOnly
                  value={basicInfo?.representative ?? ''}
                  onChange={(e) => setBasicInfo({ ...basicInfo, representative: e.target.value })}
                />
              </div>
              {/* 페이지 모드 별, 권한 별 판매점, 시공점 입력 여부 처리 */}
              {mode === 'CREATE' &&
                (session?.role === 'Builder' ? (
                  <>
                    {storeInput(basicInfo, setBasicInfo, mode)}
                    {builderInput(basicInfo, setBasicInfo, mode, session)}
                  </>
                ) : session?.role === 'Partner' ? (
                  <>{builderInput(basicInfo, setBasicInfo, mode, session)}</>
                ) : (
                  <>{storeInput(basicInfo, setBasicInfo, mode)}</>
                ))}
              {(mode === 'READ' || mode === 'EDIT') && (
                <>
                  {basicInfo?.store && storeInput(basicInfo, setBasicInfo, mode)}
                  {(basicInfo?.constructionPoint || (session?.role === 'Builder' && mode === 'EDIT')) &&
                    builderInput(basicInfo, setBasicInfo, mode, session)}
                </>
              )}
            </div>
          </div>
          <div className="sale-frame">
            <div className="data-form-wrap">
              <div className="data-input-form-bx">
                {/* 현지 조사일*/}
                <div className="data-input-form-tit">現地調査日</div>
                {['CREATE', 'EDIT'].includes(mode as 'CREATE' | 'EDIT') ? (
                  <div className="date-input">
                    <button className="date-btn">
                      <i className="date-icon"></i>
                    </button>
                    <input
                      id="investigationDate"
                      type="date"
                      className="date-frame"
                      value={basicInfo?.investigationDate?.toString() ?? ''}
                      onChange={(e) => setBasicInfo({ ...basicInfo, investigationDate: e.target.value })}
                    />
                  </div>
                ) : (
                  <input type="text" className="input-frame" readOnly value={basicInfo?.investigationDate?.toString() ?? ''} />
                )}
              </div>
              <div className="data-input-form-bx">
                {/* 건물명 */}
                <div className="data-input-form-tit">建物名</div>
                <input
                  type="text"
                  className="input-frame"
                  readOnly={mode === 'READ'}
                  value={basicInfo?.buildingName ?? ''}
                  onChange={(e) => setBasicInfo({ ...basicInfo, buildingName: e.target.value })}
                />
              </div>
              <div className="data-input-form-bx">
                {/* 고객명 */}
                <div className="data-input-form-tit">お客様名</div>
                <input
                  type="text"
                  className="input-frame"
                  readOnly={mode === 'READ'}
                  value={basicInfo?.customerName ?? ''}
                  onChange={(e) => setBasicInfo({ ...basicInfo, customerName: 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" readOnly={true} value={basicInfo?.postCode ?? ''} />
                  </div>
                  {/* 도도부현 */}
                  <div className="form-bx">
                    <input
                      type="text"
                      className="input-frame"
                      readOnly={mode === 'READ'}
                      value={basicInfo?.address ?? ''}
                      onChange={(e) => setBasicInfo({ ...basicInfo, address: e.target.value })}
                    />
                  </div>
                </div>
                {/* 주소 */}
                {mode !== 'READ' && (
                  <div className="form-flex mt5">
                    <button className="btn-frame n-blue icon" onClick={() => popupController.setZipCodePopup(true)}>
                      郵便番号<i className="btn-arr"></i>
                    </button>
                    <button className="btn-frame red reset" onClick={() => handleAddressInitiate()}></button>
                  </div>
                )}
              </div>

              <div className="data-input-form-bx">
                <div className="data-input-form-tit">市区町村名, 以後の住所</div>
                <input
                  type="text"
                  className="input-frame"
                  value={basicInfo?.addressDetail ?? ''}
                  readOnly={mode === 'READ'}
                  onChange={(e) => setBasicInfo({ ...basicInfo, addressDetail: e.target.value })}
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  )
}

/** 판매점 입력 창 */
const storeInput = (basicInfo: SurveyBasicRequest, setBasicInfo: (basicInfo: SurveyBasicRequest) => void, mode: Mode) => {
  return (
    <div className="data-input-form-bx">
      <div className="data-input-form-tit">販売店</div>
      <input
        type="text"
        className="input-frame"
        readOnly
        value={basicInfo?.store ?? ''}
        onChange={(e) => setBasicInfo({ ...basicInfo, store: e.target.value })}
      />
    </div>
  )
}

/** 시공점 입력 창 - 2차점 시공권한 유저이지만(Builder) 시공점ID가 없는 경우에만 작성 가능 */
const builderInput = (basicInfo: SurveyBasicRequest, setBasicInfo: (basicInfo: SurveyBasicRequest) => void, mode: Mode, session: SessionData) => {
  const isWriteable = mode !== 'READ' && session?.role === 'Builder' && session?.builderId === null
  return (
    <div className="data-input-form-bx">
      <div className="data-input-form-tit">施工店</div>
      <input
        type="text"
        className="input-frame"
        readOnly={!isWriteable}
        value={basicInfo?.constructionPoint ?? ''}
        onChange={(e) => setBasicInfo({ ...basicInfo, constructionPoint: e.target.value })}
      />
    </div>
  )
}
