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

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 searchParams = useSearchParams()
  const idParam = searchParams.get('id')
  const params = useParams()
  const routeId = 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 id = Number(routeId) ? Number(routeId) : Number(idParam)

  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.userNm === basicData.representative
    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)
    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 })
      if (!isUpdatingSurvey) {
        router.push(`/survey-sale/${idParam}`)
      }
    } else {
      const updatedData = {
        ...saveData,
        srlNo: '一時保存',
      }
      const id = await createSurvey(updatedData)
      if (!isCreatingSurvey) {
        router.push(`/survey-sale/${id}`)
      }
    }
    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) => {
    if (idParam) {
      await updateSurvey({ survey: saveData, isTemporary: false, storeId: session.storeId ?? '' })
      if (!isUpdatingSurvey) {
        router.push(`/survey-sale/${idParam}`)
      }
    } else {
      const id = await createSurvey(saveData)
      if (!isCreatingSurvey) {
        router.push(`/survey-sale/${id}`)
      }
    }

    if (isSubmitProcess) {
      if (!isCreatingSurvey && !isUpdatingSurvey) {
        await popupController.setSurveySaleSubmitPopup(true)
      }
    } else {
      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 (routeId) {
      window.neoConfirm('削除しますか？', async () => {
        await deleteSurvey()
        if (!isDeletingSurvey) {
          alert('削除されました。')
          router.push('/survey-sale')
        }
      })
    }
  }

  const handleSubmit = async () => {
    if (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 (!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} id={id.toString()} />
            )}
            {(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, id }: { setMode: (mode: Mode) => void; id: string }) => {
  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>
  )
}

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