'use client'

import { useEffect, useState } from 'react'
import { useTheme } from '@/lib/ThemeContext'
import { calendarApi } from '@/lib/schulkalender/api'
import type { NotificationLogRow } from '@/app/schulkalender/types'

interface NotificationStatusProps {
  eventId: string
}

const STATUS_ICON: Record<string, string> = {
  sent: '✓',
  failed: '✗',
  skipped: '⏱',
}

export function NotificationStatus({ eventId }: NotificationStatusProps) {
  const { isDark } = useTheme()
  const [rows, setRows] = useState<NotificationLogRow[]>([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    calendarApi.listEventNotifications(eventId)
      .then(r => { setRows(r || []); setLoading(false) })
      .catch(() => setLoading(false))
  }, [eventId])

  if (loading || rows.length === 0) return null

  return (
    <div className={`mt-2 pt-2 border-t text-xs ${isDark ? 'border-white/10' : 'border-black/10'}`} data-testid={`notif-status-${eventId}`}>
      <div className={`font-medium mb-1 ${isDark ? 'text-white/70' : 'text-slate-600'}`}>Erinnerungen</div>
      <div className="flex flex-wrap gap-2">
        {rows.map((r, i) => (
          <span
            key={i}
            title={r.error_message || `${r.status} ${r.run_date}`}
            className={`px-2 py-0.5 rounded ${
              r.status === 'sent' ? (isDark ? 'bg-emerald-500/30 text-emerald-100' : 'bg-emerald-100 text-emerald-900') :
              r.status === 'failed' ? (isDark ? 'bg-red-500/30 text-red-100' : 'bg-red-100 text-red-900') :
              (isDark ? 'bg-amber-500/30 text-amber-100' : 'bg-amber-100 text-amber-900')
            }`}
          >
            {STATUS_ICON[r.status]} {r.lead_days === 0 ? 'Heute' : r.lead_days === 1 ? '1 Tag' : `${r.lead_days} Tage`}
            {' · '}{r.audience === 'parents' ? 'Eltern' : 'Schueler'}
            {' · '}{r.channel}
          </span>
        ))}
      </div>
    </div>
  )
}
