'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, useSurvey } from '@/hooks/useSurvey'
import { usePopupController } from '@/store/popupController'

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 popupController = usePopupController()
  // ------------------------------------------------------------
  const [saveData, setSaveData] = useState({
    ...props.data.basic,
    detailInfo: props.data.roof,
  })
  // --------------------------------------------------------------
  // 권한

  // 제출권한 ㅇ
  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, updateSurvey, isDeletingSurvey, isUpdatingSurvey } = useSurvey(Number(id))
  const { validateSurveyDetail, createSurvey, isCreatingSurvey } = useSurvey()

  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) {
        await updateSurvey({ survey: saveData, isTemporary: false, storeId: session.storeId ?? '' })
        router.push(`/survey-sale/${idParam}`)
      } else {
        const id = await createSurvey(saveData)
        router.push(`/survey-sale/${id}`)
      }
      if (isSubmitProcess) {
        if (!isCreatingSurvey && !isUpdatingSurvey) {
          popupController.setSurveySaleSubmitPopup(true)
        }
      } else {
        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()
        if (!isDeletingSurvey) {
          alert('削除されました。')
          router.push('/survey-sale')
        }
      })
    }
  }

  const handleSubmit = async () => {
    if (props.data.basic.srlNo?.startsWith('一時保存') && Number(routeId)) {
      alert('一時保存されたデータは提出できません。')
      return
    }
    if (Number(routeId)) {
      window.neoConfirm('提出しますか？', async () => {
        popupController.setSurveySaleSubmitPopup(true)
      })
    } else {
      window.neoConfirm('記入した情報を保存して送信しますか？', async () => {
        handleSave(false, true)
      })
    }
  }

  // ------------------------------------------------------------

  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} />}
          </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} />}
          </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 }) {
  const { handleSubmit } = props
  return (
    <>
      <div className="btn-bx">
        {/* 제출 */}
        <button className="btn-frame red icon" onClick={handleSubmit}>
          提出<i className="btn-arr"></i>
        </button>
      </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>
  )
}
