import Image from 'next/image'
import { usePopupController } from '@/store/popupController'
import { useParams } from 'next/navigation'
import { useServey } from '@/hooks/useSurvey'
import { useState } from 'react'
import { useSessionStore } from '@/store/session'

interface SubmitFormData {
  store: string
  sender: string
  receiver: string
  reference: string
  title: string
  contents: string
}

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

const FORM_FIELDS: FormField[] = [
  { 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 },
]

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

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

  const { submitSurvey, isSubmittingSurvey } = useServey(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].trim()) {
        const element = document.getElementById(field.id)
        if (element) {
          element.focus()
        }
        alert(`${field.name}は必須入力項目です。`)
        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 = (field.id === 'store' && session?.role !== 'Partner') || (field.id === 'receiver' && session?.role !== 'Partner')
    const isReadOnly = false

    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)}
            />
          ) : (
            <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>
  )
}
