import { useEffect, useState } from 'react'
import { api } from '../../api/client'
import type { AbsenceComment } from '../../types/absence'

interface Props {
  absenceId: string
  onClose: () => void
}

export function AbsenceCommentsModal({ absenceId, onClose }: Props) {
  const [comments, setComments] = useState<AbsenceComment[]>([])
  const [body, setBody] = useState('')
  const [loading, setLoading] = useState(true)
  const [sending, setSending] = useState(false)
  const [error, setError] = useState('')

  const load = async () => {
    setLoading(true)
    try {
      setComments(await api.get<AbsenceComment[]>(`/absences/${absenceId}/comments`))
    } catch (e: unknown) {
      setError(e instanceof Error ? e.message : 'Fehler beim Laden')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => { load() }, [absenceId]) // eslint-disable-line react-hooks/exhaustive-deps

  const send = async () => {
    if (!body.trim()) return
    setSending(true)
    setError('')
    try {
      await api.post(`/absences/${absenceId}/comments`, { body: body.trim() })
      setBody('')
      await load()
    } catch (e: unknown) {
      setError(e instanceof Error ? e.message : 'Fehler beim Senden')
    } finally {
      setSending(false)
    }
  }

  return (
    <div className='fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4' onClick={onClose}>
      <div className='bg-white rounded-xl shadow-xl w-full max-w-lg max-h-[80vh] flex flex-col' onClick={e => e.stopPropagation()}>
        <div className='flex items-center justify-between px-5 py-3 border-b'>
          <h3 className='font-semibold text-gray-800'>Kommentare & Verlauf</h3>
          <button onClick={onClose} className='text-gray-400 hover:text-gray-600 text-xl leading-none'>×</button>
        </div>

        <div className='flex-1 overflow-y-auto px-5 py-4 space-y-3'>
          {loading && <p className='text-sm text-gray-400'>Lädt…</p>}
          {!loading && comments.length === 0 && <p className='text-sm text-gray-400'>Noch keine Kommentare.</p>}
          {comments.map(c => (
            <div key={c.id} className={`text-sm rounded-lg px-3 py-2 ${c.is_system ? 'bg-gray-50 text-gray-500 italic' : 'bg-blue-50 text-gray-700'}`}>
              <div className='flex justify-between gap-2 mb-0.5'>
                <span className='font-medium'>{c.is_system ? '⚙ System' : (c.author_name ?? 'Unbekannt')}</span>
                <span className='text-xs text-gray-400'>{new Date(c.created_at).toLocaleString('de-DE')}</span>
              </div>
              <p className='whitespace-pre-wrap'>{c.body}</p>
            </div>
          ))}
        </div>

        {error && <p className='px-5 text-xs text-red-500'>{error}</p>}
        <div className='px-5 py-3 border-t flex gap-2'>
          <input
            type='text' value={body} onChange={e => setBody(e.target.value)}
            onKeyDown={e => { if (e.key === 'Enter') send() }}
            placeholder='Kommentar schreiben…'
            className='flex-1 border border-gray-300 rounded px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-400'
          />
          <button onClick={send} disabled={sending || !body.trim()}
            className='px-4 py-1.5 bg-blue-600 text-white text-sm rounded disabled:opacity-50'>
            Senden
          </button>
        </div>
      </div>
    </div>
  )
}
