import React, { useMemo } from 'react'
import { Activity, BarChart3, Clock, TrendingUp } from 'lucide-react'
import { calculateTotal } from '../utils/patCalculations'
import { useTranslation } from '../i18n/LanguageContext'

const formatDate = (value) => {
  if (!value) return '—'
  const parsed = new Date(value)
  if (Number.isNaN(parsed.getTime())) return value
  return new Intl.DateTimeFormat('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric' }).format(parsed)
}

export default function LiveOverview({ assessments, loading = false, error }) {
  const t = useTranslation()

  const stats = useMemo(() => {
    if (loading || !assessments) {
      return {
        total: 0,
        average: 0,
        latest: null,
        best: null
      }
    }

    if (!assessments?.length) {
      return {
        total: 0,
        average: 0,
        latest: null,
        best: null
      }
    }

    const scored = assessments.map((entry) => ({
      ...entry,
      totalPoints: Math.round(calculateTotal(entry.exercises || []))
    }))

    const average =
      scored.reduce((sum, item) => sum + (item.totalPoints || 0), 0) / (scored.length || 1)

    const latest = scored[0]
    const best = scored.reduce((top, current) =>
      !top || (current.totalPoints || 0) > (top.totalPoints || 0) ? current : top,
    null)

    return {
      total: scored.length,
      average: Math.round(average),
      latest,
      best
    }
  }, [assessments])

  return (
    <div className="bg-white/90 dark:bg-gray-900/80 border border-gray-100 dark:border-gray-800 rounded-2xl shadow-lg p-6 mb-6">
      <div className="flex items-center justify-between flex-wrap gap-3 mb-4">
        <div>
          <p className="text-xs uppercase tracking-[0.2em] text-emerald-600 dark:text-emerald-300">{t('live.title')}</p>
          <h2 className="text-xl font-bold text-gray-900 dark:text-gray-100">{t('live.stats_title')}</h2>
          <p className="text-sm text-gray-600 dark:text-gray-400">{t('live.basis')}</p>
        </div>
        <span className="rounded-full border border-emerald-200/70 dark:border-emerald-700 px-3 py-1 text-xs font-semibold text-emerald-700 dark:text-emerald-200 bg-emerald-50 dark:bg-emerald-900/40">
          {loading ? t('live.loading') : t('live.timestamp')}
        </span>
      </div>

      {error && (
        <div className="mb-3 rounded-lg border border-red-200 dark:border-red-800 bg-red-50 dark:bg-red-900/30 p-3 text-sm text-red-700 dark:text-red-200">
          {error}
        </div>
      )}

      {loading ? (
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
          {[1, 2, 3, 4].map((key) => (
            <div key={key} className="h-28 rounded-2xl border border-gray-200/60 dark:border-gray-800 bg-gray-100 dark:bg-gray-800 animate-pulse" />
          ))}
        </div>
      ) : stats.total === 0 ? (
        <div className="rounded-xl border border-dashed border-gray-200 dark:border-gray-800 bg-gray-50 dark:bg-gray-800/60 p-4 text-sm text-gray-600 dark:text-gray-300">
          {t('live.no_data')}
        </div>
      ) : (
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
          <div className="rounded-2xl border border-emerald-200/70 dark:border-emerald-800 bg-gradient-to-br from-emerald-50 via-white to-emerald-50 dark:from-emerald-900/30 dark:via-gray-900 dark:to-emerald-900/20 p-4 shadow-sm">
            <div className="flex items-center justify-between">
              <p className="text-sm font-semibold text-emerald-700 dark:text-emerald-200">{t('live.count')}</p>
              <Activity className="h-4 w-4 text-emerald-600 dark:text-emerald-300" aria-hidden="true" />
            </div>
            <p className="mt-3 text-3xl font-bold text-emerald-800 dark:text-emerald-100">{stats.total}</p>
            <p className="text-xs text-emerald-700/80 dark:text-emerald-200/70">{t('live.count_desc')}</p>
          </div>

          <div className="rounded-2xl border border-sky-200/70 dark:border-sky-800 bg-gradient-to-br from-sky-50 via-white to-sky-50 dark:from-sky-900/30 dark:via-gray-900 dark:to-sky-900/20 p-4 shadow-sm">
            <div className="flex items-center justify-between">
              <p className="text-sm font-semibold text-sky-700 dark:text-sky-200">{t('live.avg_points')}</p>
              <TrendingUp className="h-4 w-4 text-sky-600 dark:text-sky-300" aria-hidden="true" />
            </div>
            <p className="mt-3 text-3xl font-bold text-sky-800 dark:text-sky-100">{stats.average}</p>
            <p className="text-xs text-sky-700/80 dark:text-sky-200/70">{t('live.avg_desc')}</p>
          </div>

          <div className="rounded-2xl border border-indigo-200/70 dark:border-indigo-800 bg-gradient-to-br from-indigo-50 via-white to-indigo-50 dark:from-indigo-900/30 dark:via-gray-900 dark:to-indigo-900/20 p-4 shadow-sm">
            <div className="flex items-center justify-between">
              <p className="text-sm font-semibold text-indigo-700 dark:text-indigo-200">{t('live.last')}</p>
              <Clock className="h-4 w-4 text-indigo-600 dark:text-indigo-300" aria-hidden="true" />
            </div>
            <p className="mt-3 text-lg font-semibold text-indigo-900 dark:text-indigo-100">
              {stats.latest?.name || stats.latest?.patType || t('live.unnamed')}
            </p>
            <p className="text-xs text-indigo-700/80 dark:text-indigo-200/70">
              {formatDate(stats.latest?.datum)} · {stats.latest?.patType || 'PAT'}
            </p>
          </div>

          <div className="rounded-2xl border border-amber-200/70 dark:border-amber-800 bg-gradient-to-br from-amber-50 via-white to-amber-50 dark:from-amber-900/30 dark:via-gray-900 dark:to-amber-900/20 p-4 shadow-sm">
            <div className="flex items-center justify-between">
              <p className="text-sm font-semibold text-amber-700 dark:text-amber-200">{t('live.top')}</p>
              <BarChart3 className="h-4 w-4 text-amber-600 dark:text-amber-300" aria-hidden="true" />
            </div>
            <p className="mt-3 text-3xl font-bold text-amber-800 dark:text-amber-100">
              {stats.best?.totalPoints ?? 0}
            </p>
            <p className="text-xs text-amber-700/80 dark:text-amber-200/70">
              {stats.best?.name || stats.best?.patType || '—'} · {stats.best?.patType || 'PAT'}
            </p>
          </div>
        </div>
      )}
    </div>
  )
}
