'use client'

import type { Mode, SurveyBasicRequest, SurveyDetailInfo, SurveyDetailRequest } from '@/types/Survey'
import { useSessionStore } from '@/store/session'
import { useEffect, useState } from 'react'
import { useParams, useRouter, useSearchParams } from 'next/navigation'
import { requiredFields, useServey } from '@/hooks/useSurvey'

export default function ButtonForm(props: {
  mode: Mode
  setMode: (mode: Mode) => void
  data: { basic: SurveyBasicRequest; roof: SurveyDetailRequest }
}) {
  // 라우터
  const router = useRouter()
  const { mode, setMode } = props
  const { session } = useSessionStore()

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

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

  // ------------------------------------------------------------
  const [saveData, setSaveData] = useState({
    ...props.data.basic,
    detailInfo: props.data.roof,
  })

  // !!!!!!!!!!
  const [tempTargetId, setTempTargetId] = useState('')
  // --------------------------------------------------------------
  // 권한

  // 제출권한 ㅇ
  const [isSubmiter, setIsSubmiter] = useState(false)
  // 작성자
  const [isWriter, setIsWriter] = useState(false)
  const isSubmit = props.data.basic.submissionStatus

  useEffect(() => {
    if (session?.isLoggedIn) {
      switch (session?.role) {
        // T01 제출권한 없음
        case 'T01':
          setIsSubmiter(false)
          break
        // 1차 판매점(Order) + 2차 판매점(Musubi) => 같은 판매점 제출권한
        case 'Admin':
        case 'Admin_Sub':
          setIsSubmiter(session.storeNm === props.data.basic.store && session.builderNo === props.data.basic.constructionPoint)
          break
        // 시공권한 User(Musubi) + Partner => 같은 시공ID 제출권한
        case 'Builder':
        case 'Partner':
          setIsSubmiter(session.builderNo === props.data.basic.constructionPoint)
          break
        default:
          setIsSubmiter(false)
          break
      }

      setIsWriter(session.userNm === props.data.basic.representative)
    }
    setSaveData({
      ...props.data.basic,
      detailInfo: props.data.roof,
    })
  }, [session, props.data])

  // ------------------------------------------------------------
  // 저장/임시저장/수정
  const id = Number(routeId) ? Number(routeId) : Number(idParam)

  const { deleteSurvey, submitSurvey, updateSurvey } = useServey(Number(id))
  const { validateSurveyDetail, createSurvey } = useServey()

  const handleSave = (isTemporary: boolean, isSubmitProcess = false) => {
    const emptyField = validateSurveyDetail(props.data.roof)
    const hasEmptyField = emptyField?.trim() !== ''

    if (isTemporary) {
      hasEmptyField ? tempSaveProcess() : saveProcess(emptyField, false)
    } else {
      saveProcess(emptyField, isSubmitProcess)
    }
  }

  const tempSaveProcess = async () => {
    if (idParam) {
      await updateSurvey({ survey: saveData, isTemporary: true })
      router.push(`/survey-sale/${idParam}`)
    } else {
      const updatedData = {
        ...saveData,
        srlNo: '一時保存',
      }
      const id = await createSurvey(updatedData)
      router.push(`/survey-sale/${id}`)
    }
    alert('一時保存されました。')
  }

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

  const saveProcess = async (emptyField: string | null, isSubmitProcess?: boolean) => {
    if (emptyField?.trim() === '') {
      if (idParam) {
        if (isSubmitProcess) {
          const updatedData = {
            ...saveData,
            submissionStatus: true,
            submissionDate: new Date().toISOString(),
            submissionTargetId: tempTargetId,
          }
          await updateSurvey({ survey: updatedData, isTemporary: false, storeId: session.storeId ?? '' })
          router.push(`/survey-sale/${idParam}`)
        } else {
          await updateSurvey({ survey: saveData, isTemporary: false, storeId: session.storeId ?? '' })
          router.push(`/survey-sale/${idParam}`)
        }
      } else {
        if (isSubmitProcess) {
          const updatedData = {
            ...saveData,
            submissionStatus: true,
            submissionDate: new Date().toISOString(),
            submissionTargetId: tempTargetId,
          }
          const id = await createSurvey(updatedData)
          submitProcess(id)
        } else {
          const id = await createSurvey(saveData)
          router.push(`/survey-sale/${id}`)
        }
      }
      alert('保存されました。')
    } else {
      if (emptyField?.includes('Unit')) {
        alert('電気契約容量の単位を入力してください。')
        focusInput(emptyField as keyof SurveyDetailInfo)
      } else {
        alert(requiredFields.find((field) => field.field === emptyField)?.name + ' 項目が空です。')
        focusInput(emptyField as keyof SurveyDetailInfo)
      }
    }
  }
  // ------------------------------------------------------------
  // 삭제/제출

  const handleDelete = async () => {
    if (routeId) {
      window.neoConfirm('削除しますか？', async () => {
        await deleteSurvey()
        router.push('/survey-sale')
      })
    }
  }

  const handleSubmit = async () => {
    if (props.data.basic.srlNo?.startsWith('一時保存')) {
      alert('一時保存されたデータは提出できません。')
      return
    }
    if (tempTargetId.trim() === '') {
      alert('提出対象店舗を入力してください。')
      return
    }
    window.neoConfirm('提出しますか？', async () => {
      if (Number(routeId)) {
        submitProcess()
      } else {
        handleSave(false, true)
      }
    })
  }

  const submitProcess = async (saveId?: number) => {
    await submitSurvey({ saveId: saveId, targetId: tempTargetId, storeId: session.storeId ?? '', srlNo: '一時保存' })
    alert('提出されました。')
    router.push('/survey-sale')
  }
  // ------------------------------------------------------------

  if (mode === 'READ' && isSubmit && isSubmiter) {
    return (
      <>
        <div className="sale-form-btn-wrap">
          <div className="btn-flex-wrap">
            <ListButton />
          </div>
        </div>
      </>
    )
  }

  return (
    <>
      {mode === 'READ' && (
        <div className="sale-form-btn-wrap">
          <div className="btn-flex-wrap">
            <ListButton />
            <EditButton setMode={setMode} id={id.toString()} mode={mode} />
            {(isWriter || !isSubmiter) && <DeleteButton handleDelete={handleDelete} />}
            {!isSubmit && isSubmiter && <SubmitButton handleSubmit={handleSubmit} setTempTargetId={setTempTargetId} />}
          </div>
        </div>
      )}

      {(mode === 'CREATE' || mode === 'EDIT') && (
        <div className="sale-form-btn-wrap">
          <div className="btn-flex-wrap">
            <ListButton />
            <TempButton setMode={setMode} handleSave={handleSave} />
            <SaveButton handleSave={handleSave} />
            {session?.role !== 'T01' && <SubmitButton handleSubmit={handleSubmit} setTempTargetId={setTempTargetId} />}{' '}
          </div>
        </div>
      )}
    </>
  )
}

// 목록 버튼
function ListButton() {
  const router = useRouter()
  return (
    <div className="btn-bx">
      {/* 목록 */}
      <button className="btn-frame n-blue icon" onClick={() => router.push('/survey-sale')}>
        リスト<i className="btn-arr"></i>
      </button>
    </div>
  )
}

function EditButton(props: { setMode: (mode: Mode) => void; id: string; mode: Mode }) {
  const { setMode, id, mode } = props
  const router = useRouter()
  return (
    <div className="btn-bx">
      {/* 수정 */}
      <button
        className="btn-frame n-blue icon"
        onClick={() => {
          router.push(`/survey-sale/regist?id=${id}`)
          setMode('EDIT')
        }}
      >
        修正<i className="btn-arr"></i>
      </button>
    </div>
  )
}

function SubmitButton(props: { handleSubmit: () => void; setTempTargetId: (targetId: string) => void }) {
  const { handleSubmit, setTempTargetId } = props
  return (
    <>
      <div className="btn-bx">
        {/* 제출 */}
        <button className="btn-frame red icon" onClick={handleSubmit}>
          提出<i className="btn-arr"></i>
        </button>
      </div>
      <div>
        <input type="text" placeholder="temp target id" onChange={(e) => setTempTargetId(e.target.value)} />
      </div>
    </>
  )
}

function DeleteButton(props: { handleDelete: () => void }) {
  const { handleDelete } = props
  return (
    <div className="btn-bx">
      {/* 삭제 */}
      <button className="btn-frame n-blue icon" onClick={handleDelete}>
        削除<i className="btn-arr"></i>
      </button>
    </div>
  )
}

function SaveButton(props: { handleSave: (isTemporary: boolean) => void }) {
  const { handleSave } = props
  return (
    <div className="btn-bx">
      {/* 저장 */}
      <button className="btn-frame n-blue icon" onClick={() => handleSave(false)}>
        保存<i className="btn-arr"></i>
      </button>
    </div>
  )
}

function TempButton(props: { setMode: (mode: Mode) => void; handleSave: (isTemporary: boolean) => void }) {
  const { setMode, handleSave } = props
  const router = useRouter()

  return (
    <div className="btn-bx">
      {/* 임시저장 */}
      <button
        className="btn-frame n-blue icon"
        onClick={() => {
          handleSave(true)
        }}
      >
        一時保存<i className="btn-arr"></i>
      </button>
    </div>
  )
}
