import { useState } from 'react'
import './Admin.css'

interface Response {
  id: string
  name: string
  alcohol: string | null
  food: string | null
  with_partner: boolean
  partner_name: string | null
  partner_alcohol: string | null
  partner_food: string | null
  created_at: string
}

export default function Admin() {
  const [password, setPassword] = useState('')
  const [authed, setAuthed] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [responses, setResponses] = useState<Response[]>([])
  const [loading, setLoading] = useState(false)

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault()
    setLoading(true)
    setError(null)
    try {
      const res = await fetch('/api/admin/responses', {
        headers: { 'x-admin-password': password },
      })
      if (res.status === 401) { setError('Неверный пароль'); return }
      if (!res.ok) throw new Error(`Ошибка сервера: ${res.status}`)
      setResponses(await res.json())
      setAuthed(true)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Не удалось подключиться к серверу')
    } finally {
      setLoading(false)
    }
  }

  if (!authed) {
    return (
      <div className="admin-gate">
        <form className="admin-gate-form" onSubmit={handleLogin}>
          <h1 className="admin-gate-title">Админ</h1>
          <input
            className="admin-gate-input"
            type="password"
            placeholder="Пароль"
            value={password}
            onChange={e => setPassword(e.target.value)}
            autoFocus
          />
          {error && <p className="admin-gate-error">{error}</p>}
          <button className="admin-gate-btn" type="submit" disabled={loading}>
            {loading ? 'Загрузка...' : 'Войти'}
          </button>
        </form>
      </div>
    )
  }

  const total = responses.length
  const totalGuests = responses.reduce((acc, r) => acc + (r.with_partner ? 2 : 1), 0)

  return (
    <div className="admin">
      <div className="admin-header">
        <h1 className="admin-title">Ответы гостей</h1>
        <div className="admin-stats">
          <span className="admin-stat"><b>{total}</b> анкет</span>
          <span className="admin-stat"><b>{totalGuests}</b> гостей</span>
        </div>
      </div>

      {responses.length === 0 ? (
        <p className="admin-empty">Ответов пока нет</p>
      ) : (
        <div className="admin-cards">
          {responses.map(r => (
            <div key={r.id} className="admin-card">
              <div className="admin-card-header">
                <span className="admin-card-name">{r.name}</span>
                <span className="admin-card-date">
                  {new Date(r.created_at).toLocaleDateString('ru-RU', {
                    day: 'numeric', month: 'long', hour: '2-digit', minute: '2-digit'
                  })}
                </span>
              </div>
              <div className="admin-card-fields">
                {r.alcohol && <div className="admin-field"><span className="admin-field-label">Алкоголь</span><span>{r.alcohol}</span></div>}
                {r.food && <div className="admin-field"><span className="admin-field-label">Не ест</span><span>{r.food}</span></div>}
              </div>
              {r.with_partner && (
                <div className="admin-card-partner">
                  <span className="admin-partner-label">Пара: {r.partner_name}</span>
                  <div className="admin-card-fields">
                    {r.partner_alcohol && <div className="admin-field"><span className="admin-field-label">Алкоголь</span><span>{r.partner_alcohol}</span></div>}
                    {r.partner_food && <div className="admin-field"><span className="admin-field-label">Не ест</span><span>{r.partner_food}</span></div>}
                  </div>
                </div>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  )
}
