import { useState, useRef, useEffect } from 'react'
import './Survey.css'

interface FormData {
  name: string
  alcohol: string
  food: string
  withPartner: boolean
  partnerName: string
  partnerAlcohol: string
  partnerFood: string
}

export default function Survey() {
  const [form, setForm] = useState<FormData>({
    name: '',
    alcohol: '',
    food: '',
    withPartner: false,
    partnerName: '',
    partnerAlcohol: '',
    partnerFood: '',
  })

  const partnerRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    if (form.withPartner && partnerRef.current) {
      partnerRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' })
    }
  }, [form.withPartner])

  const [submitted, setSubmitted] = useState(false)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const set = (field: keyof FormData) => (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.type === 'checkbox' ? e.target.checked : e.target.value
    setForm(prev => ({ ...prev, [field]: value }))
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setLoading(true)
    setError(null)
    try {
      const res = await fetch('/api/submit', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: form.name,
          alcohol: form.alcohol || null,
          food: form.food || null,
          with_partner: form.withPartner,
          partner_name: form.withPartner ? form.partnerName || null : null,
          partner_alcohol: form.withPartner ? form.partnerAlcohol || null : null,
          partner_food: form.withPartner ? form.partnerFood || null : null,
        }),
      })
      if (!res.ok) throw new Error('Ошибка сервера')
      setSubmitted(true)
    } catch {
      setError('Не удалось отправить. Попробуйте ещё раз.')
    } finally {
      setLoading(false)
    }
  }

  if (submitted) {
    return (
      <div className="survey-thanks">
        <p className="survey-thanks-title">Спасибо!</p>
        <p className="survey-thanks-sub">Мы получили ваши ответы и очень рады вас ждать.</p>
      </div>
    )
  }

  return (
    <form className="survey" onSubmit={handleSubmit}>
      <div className="survey-field">
        <label className="survey-label">Ваши фамилия и имя</label>
        <input
          className="survey-input"
          type="text"
          value={form.name}
          onChange={set('name')}
          required
        />
      </div>

      <div className="survey-field">
        <label className="survey-label">Ваши предпочтения по алкоголю</label>
        <input
          className="survey-input"
          type="text"
          value={form.alcohol}
          onChange={set('alcohol')}
        />
      </div>

      <div className="survey-field">
        <label className="survey-label">Какую еду вы не едите?</label>
        <input
          className="survey-input"
          type="text"
          value={form.food}
          onChange={set('food')}
        />
      </div>

      <div
        className="survey-checkbox-row"
        onClick={() => setForm(prev => ({ ...prev, withPartner: !prev.withPartner }))}
      >
        <span className={`survey-checkbox-box ${form.withPartner ? 'checked' : ''}`} />
        <span className="survey-checkbox-label">Я приду не один(а)</span>
      </div>

      {form.withPartner && (
        <div className="survey-partner" ref={partnerRef}>
          <div className="survey-field">
            <label className="survey-label">Фамилия и имя партнера</label>
            <input
              className="survey-input"
              type="text"
              value={form.partnerName}
              onChange={set('partnerName')}
              required
            />
          </div>

          <div className="survey-field">
            <label className="survey-label">Предпочтения по алкоголю вашего партнера</label>
            <input
              className="survey-input"
              type="text"
              value={form.partnerAlcohol}
              onChange={set('partnerAlcohol')}
            />
          </div>

          <div className="survey-field">
            <label className="survey-label">Какую еду не ест ваш партнер</label>
            <input
              className="survey-input"
              type="text"
              value={form.partnerFood}
              onChange={set('partnerFood')}
            />
          </div>
        </div>
      )}

      {error && <p className="survey-error">{error}</p>}

      <button className="survey-submit" type="submit" disabled={loading}>
        {loading ? 'Отправка...' : 'Отправить'}
      </button>
    </form>
  )
}
