import Image from 'next/image'
import { usePopupController } from '@/store/popupController'
import { useParams } from 'next/navigation'
import { useSurvey } from '@/hooks/useSurvey'
import { useEffect, useState } from 'react'
import { useSessionStore } from '@/store/session'
import { useCommCode } from '@/hooks/useCommCode'
import { CommCode } from '@/types/CommCode'

interface SubmitFormData {
  saleBase: string | null
  store: string
  sender: string
  receiver: string[]
  reference: string | null
  title: string
  contents: string
}

interface FormField {
  id: keyof SubmitFormData
  name: string
  required: boolean
}

export default function SurveySaleSubmitPopup() {
  const popupController = usePopupController()
  const { session } = useSessionStore()
  const params = useParams()
  const routeId = params.id

  const [commCodeList, setCommCodeList] = useState<CommCode[]>([])

  const { getCommCode } = useCommCode()

  useEffect(() => {
    if (session?.isLoggedIn && session?.role === 'Admin') {
      getCommCode('SALES_OFFICE_CD').then((codes) => {
        setCommCodeList(codes)
      })
    }
  }, [session])

  const FORM_FIELDS: FormField[] = [
    { id: 'saleBase', name: '提出地点選択', required: session?.role === 'Admin' },
    { id: 'store', name: '提出販売店', required: true },
    { id: 'sender', name: '発送者', required: true },
    { id: 'receiver', name: '受信者', required: true },
    { id: 'reference', name: '参考', required: false },
    { id: 'title', name: 'タイトル', required: true },
    { id: 'contents', name: '内容', required: true },
  ]

  const [submitData, setSubmitData] = useState<SubmitFormData>({
    saleBase: null,
    store: '',
    sender: session?.email ?? '',
    receiver: [],
    reference: null,
    title: '[HANASYS現地調査] 調査物件が提出.',
    contents: '',
  })

  const { submitSurvey, isSubmittingSurvey } = useSurvey(Number(routeId))

  const handleInputChange = (field: keyof SubmitFormData, value: string) => {
    setSubmitData((prev) => ({ ...prev, [field]: value }))
  }

  const validateData = (data: SubmitFormData): boolean => {
    const requiredFields = FORM_FIELDS.filter((field) => field.required)

    for (const field of requiredFields) {
      if (data[field.id]?.length === 0) {
        alert(`${field.name}は必須入力項目です。`)
        const element = document.getElementById(field.id)
        if (element) {
          element.focus()
        }
        return false
      }
    }
    return true
  }

  const handleSubmit = () => {
    if (validateData(submitData)) {
      window.neoConfirm('送信しますか？ 送信後は変更・修正することはできません。', () => {
        submitSurvey({ targetId: submitData.store })
        if (!isSubmittingSurvey) {
          popupController.setSurveySaleSubmitPopup(false)
        }
      })
    }
  }

  const handleClose = () => {
    popupController.setSurveySaleSubmitPopup(false)
  }

  const renderFormField = (field: FormField) => {
    const isReadOnly = false

    if (field.id === 'saleBase' && session?.role !== 'Admin') {
      return null
    }

    return (
      <div className="data-input-form-bx" key={field.id}>
        <div className="data-input-form-tit">
          {field.name} {field.required && <i className="import">*</i>}
        </div>
        <div className="data-input">
          {field.id === 'contents' ? (
            <textarea
              className="textarea-form"
              id={field.id}
              value={submitData[field.id] ?? ''}
              onChange={(e) => handleInputChange(field.id, e.target.value)}
            />
          ) : (
            <>
              {field.id === 'saleBase' && session?.role === 'Admin' ? (
                <select
                  className="select-form"
                  id={field.id}
                  value={submitData[field.id] ?? ''}
                  onChange={(e) => {
                    const selectedOffice = commCodeList.find((item) => item.code === e.target.value)
                    if (selectedOffice) {
                      //@ts-ignore
                      const receiver = selectedOffice.REF_CHR1.split(';')
                      setSubmitData((prev) => ({ ...prev, receiver: receiver, saleBase: e.target.value }))
                    }
                  }}
                >
                  <option value="">選択してください</option>
                  {commCodeList.map((item) => (
                    <option key={item.code} value={item.code}>
                      {item.codeJp}
                    </option>
                  ))}
                </select>
              ) : (
                <input
                  className="input-frame"
                  type="text"
                  id={field.id}
                  value={submitData[field.id] ?? ''}
                  onChange={(e) => handleInputChange(field.id, e.target.value)}
                  readOnly={isReadOnly}
                />
              )}
            </>
          )}
        </div>
      </div>
    )
  }

  return (
    <div className="modal-popup">
      <div className="modal-dialog">
        <div className="modal-content">
          <div className="modal-header">
            <div className="modal-header-inner">
              <div className="modal-name-wrap">
                <div className="modal-img">
                  <Image src="/assets/images/layout/modal_header_icon04.svg" width={19} height={22} alt="" />
                </div>
                <div className="modal-name">調査物件の提出</div>
              </div>
              <button className="modal-close" onClick={handleClose}></button>
            </div>
          </div>
          <div className="modal-body">
            <div className="data-form-wrap">{FORM_FIELDS.map(renderFormField)}</div>
            <div className="btn-flex-wrap">
              <div className="btn-bx">
                <button className="btn-frame n-blue icon" onClick={handleClose}>
                  閉じる<i className="btn-arr"></i>
                </button>
              </div>
              <div className="btn-bx">
                <button className="btn-frame red icon" onClick={handleSubmit} disabled={isSubmittingSurvey}>
                  転送<i className="btn-arr"></i>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
