'use client'

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

interface ButtonFormProps {
  mode: Mode
  setMode: (mode: Mode) => void
  data: {
    basic: SurveyBasicRequest
    roof: SurveyDetailRequest
  }
}

interface PermissionState {
  isSubmiter: boolean
  isWriter: boolean
  isReceiver: boolean
}

interface SaveData extends SurveyBasicRequest {
  detailInfo: SurveyDetailRequest
}

export default function ButtonForm({ mode, setMode, data }: ButtonFormProps) {
  const router = useRouter()
  const { session } = useSessionStore()

  const params = useParams()
  const id = Number(params.id)
  const popupController = usePopupController()

  const [saveData, setSaveData] = useState<SaveData>({
    ...data.basic,
    detailInfo: data.roof,
  })

  const [permissions, setPermissions] = useState<PermissionState>({
    isSubmiter: false,
    isWriter: false,
    isReceiver: false,
  })

  const isSubmit = data.basic.submissionStatus

  const { deleteSurvey, updateSurvey, isDeletingSurvey, isUpdatingSurvey } = useSurvey(id)
  const { validateSurveyDetail, createSurvey, isCreatingSurvey } = useSurvey()

  useEffect(() => {
    if (!session?.isLoggedIn) return

    const newPermissions = calculatePermissions(session, data.basic)
    setPermissions(newPermissions)

    setSaveData({
      ...data.basic,
      detailInfo: data.roof,
    })
  }, [session, data])

  /** 권한 정리 로직 - 작성자(담당자), 제출 권한자, 제출 수신자*/
  const calculatePermissions = (session: any, basicData: SurveyBasicRequest): PermissionState => {
    const isSubmiter = calculateSubmitPermission(session, basicData)
    const isWriter = session.userId === basicData.representativeId
    const isReceiver = session?.storeId === basicData.submissionTargetId

    return { isSubmiter, isWriter, isReceiver }
  }

  /** 제출 권한 체크 */
  const calculateSubmitPermission = (session: any, basicData: SurveyBasicRequest): boolean => {
    switch (session?.role) {
      case 'T01':
        return false
      case 'Admin':
      case 'Admin_Sub':
        return session.storeNm === basicData.store && session.builderId === basicData.constructionPointId
      case 'Builder':
      case 'Partner':
        return session.builderId === basicData.constructionPointId
      default:
        return false
    }
  }

  /** 저장 로직 */
  const handleSave = (isTemporary: boolean, isSubmitProcess: boolean) => {
    const emptyField = validateSurveyDetail(data.roof)

    if (isTemporary) {
      tempSaveProcess()
    } else {
      saveProcess(emptyField, isSubmitProcess)
    }
  }

  /** 임시 저장 로직 */
  const tempSaveProcess = async () => {
    /**route 에 id 가 있는 경우 업데이트, 없는 경우 생성 */
    if (!Number.isNaN(id)) {
      await updateSurvey({ survey: saveData, isTemporary: true })
      if (!isUpdatingSurvey) {
        setMode('READ')
      }
    } else {
      const updatedData = {
        ...saveData,
        srlNo: '一時保存',
      }
      const savedId = await createSurvey(updatedData)
      if (!isCreatingSurvey) {
        router.push(`/survey-sale/${savedId}`)
      }
    }
    alert('一時保存されました。')
  }

  /** 입력 필드 포커스 처리 */
  const focusInput = (field: keyof SurveyDetailInfo) => {
    const input = document.getElementById(field)
    input?.focus()
  }

  /** 저장 로직 */
  const saveProcess = async (emptyField: string | null, isSubmitProcess?: boolean) => {
    if (emptyField?.trim() === '') {
      await handleSuccessfulSave(isSubmitProcess)
    } else {
      handleFailedSave(emptyField)
    }
  }

  /** 저장 성공 로직 */
  const handleSuccessfulSave = async (isSubmitProcess?: boolean) => {
    /** route 에 id 가 있는 경우 업데이트, 없는 경우 생성 */
    if (!Number.isNaN(id)) {
      await updateSurvey({
        survey: saveData,
        isTemporary: false,
        storeId: session?.role === 'Partner' ? session?.builderId ?? null : session?.storeId ?? null,
      })
      if (!isUpdatingSurvey) {
        setMode('READ')
        if (isSubmitProcess) {
          popupController.setSurveySaleSubmitPopup(true)
        }
      }
    } else {
      /** 제출 로직인 경우 search param 추가 */
      const savedId = await createSurvey(saveData)
      if (isSubmitProcess) {
        await router.push(`/survey-sale/${savedId}?show=true`)
      } else {
        await router.push(`/survey-sale/${savedId}`)
        alert('保存されました。')
      }
    }
  }

  /** 필수값 미입력 처리 */
  const handleFailedSave = (emptyField: string | null) => {
    if (emptyField?.includes('Unit')) {
      alert('電気契約容量の単位を入力してください。')
    } else {
      alert(requiredFields.find((field) => field.field === emptyField)?.name + ' 項目が空です。')
    }
    focusInput(emptyField as keyof SurveyDetailInfo)
  }

  /** 삭제 로직 */
  const handleDelete = async () => {
    if (!Number.isNaN(id)) {
      window.neoConfirm('削除しますか？', async () => {
        await deleteSurvey()
        if (!isDeletingSurvey) {
          alert('削除されました。')
          router.push('/survey-sale')
        }
      })
    }
  }

  /** 제출 로직 */
  const handleSubmit = async () => {
    if (data.basic.srlNo?.startsWith('一時保存') && Number.isNaN(id)) {
      alert('一時保存されたデータは提出できません。')
      return
    }

    if (mode === 'READ') {
      window.neoConfirm('提出しますか？', async () => {
        popupController.setSurveySaleSubmitPopup(true)
      })
    } else {
      window.neoConfirm('記入した情報を保存して送信しますか？', async () => {
        handleSave(false, true)
      })
    }
  }

  /** 로그인 여부 체크 */
  if (!session?.isLoggedIn) return null

  /** 읽기 모드, 제출 된 데이터, 제출 권한자는 리스트 버튼만 표시 */
  if (mode === 'READ' && isSubmit && permissions.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 />
            {(permissions.isWriter || permissions.isSubmiter || (permissions.isReceiver && isSubmit)) && <EditButton setMode={setMode} />}
            {(permissions.isWriter || (permissions.isReceiver && isSubmit)) && <DeleteButton handleDelete={handleDelete} />}
            {!isSubmit && permissions.isSubmiter && <SubmitButton handleSubmit={handleSubmit} />}
          </div>
        </div>
      )}

      {/* 수정, 작성 모드 */}
      {/* 작성자 - 임시저장, 저장, 제출(미제출인 매물) 버튼 표시 */}
      {/* 제출권한자 - 임시저장, 저장, 제출(미제출인 매물) 버튼 표시 */}
      {/* 제출수신자 - 임시저장, 저장 버튼 표시 */}
      {(mode === 'CREATE' || mode === 'EDIT') && (
        <div className="sale-form-btn-wrap">
          <div className="btn-flex-wrap">
            <ListButton />
            <TempButton handleSave={() => handleSave(true, false)} />
            <SaveButton handleSave={() => handleSave(false, false)} />
            {session?.role === 'T01' || isSubmit ? null : <SubmitButton handleSubmit={handleSubmit} />}
          </div>
        </div>
      )}
    </>
  )
}

/** Button Components */
const 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>
  )
}

const EditButton = ({ setMode }: { setMode: (mode: Mode) => void }) => {
  return (
    <div className="btn-bx">
      <button
        className="btn-frame n-blue icon"
        onClick={() => {
          setMode('EDIT')
        }}
      >
        修正<i className="btn-arr"></i>
      </button>
    </div>
  )
}

const SubmitButton = ({ handleSubmit }: { handleSubmit: () => void }) => (
  <div className="btn-bx">
    <button className="btn-frame red icon" onClick={handleSubmit}>
      提出<i className="btn-arr"></i>
    </button>
  </div>
)

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

const SaveButton = ({ handleSave }: { handleSave: () => void }) => (
  <div className="btn-bx">
    <button className="btn-frame n-blue icon" onClick={handleSave}>
      保存<i className="btn-arr"></i>
    </button>
  </div>
)

const TempButton = ({ handleSave }: { handleSave: () => void }) => (
  <div className="btn-bx">
    <button className="btn-frame n-blue icon" onClick={handleSave}>
      一時保存<i className="btn-arr"></i>
    </button>
  </div>
)
