'use client'

import React from 'react'
import type { LineDashboard } from '../../_types'

interface AggregatePanelProps {
  dashboard: LineDashboard
}

const RISK_DOTS = [
  { key: 'critical', label: 'Kritisch', dotColor: 'bg-red-500' },
  { key: 'high', label: 'Hoch', dotColor: 'bg-orange-500' },
  { key: 'medium', label: 'Mittel', dotColor: 'bg-yellow-500' },
  { key: 'low', label: 'Niedrig', dotColor: 'bg-green-500' },
]

export function AggregatePanel({ dashboard }: AggregatePanelProps) {
  const { line, stations, aggregate } = dashboard

  const totalHazards = stations.reduce((sum, s) => sum + s.hazard_count, 0)
  const totalMitigations = stations.reduce((sum, s) => sum + s.mitigation_count, 0)
  const stationCount = stations.length

  return (
    <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6">
      {/* Title row */}
      <div className="flex items-start justify-between mb-3">
        <div>
          <h1 className="text-xl font-bold text-gray-900 dark:text-white">
            {line.name}
          </h1>
          {line.description && (
            <p className="text-sm text-gray-500 dark:text-gray-400 mt-0.5">
              {line.description}
            </p>
          )}
        </div>
        <div className="flex items-center gap-2 text-xs text-gray-400 dark:text-gray-500">
          <span>Erstellt: {new Date(line.created_at).toLocaleDateString('de-DE')}</span>
        </div>
      </div>

      {/* Stats row */}
      <div className="flex flex-wrap items-center gap-6 mb-3">
        <StatPill label="Stationen" value={stationCount} />
        <StatPill label="Gefaehrdungen" value={totalHazards} />
        <StatPill label="Massnahmen" value={totalMitigations} />
      </div>

      {/* Risk dots row */}
      <div className="flex flex-wrap items-center gap-4">
        {RISK_DOTS.map((rd) => {
          const count = aggregate[rd.key] || 0
          return (
            <span key={rd.key} className="flex items-center gap-1.5 text-xs text-gray-600 dark:text-gray-300">
              <span className={`w-2.5 h-2.5 rounded-full ${rd.dotColor}`} />
              <span className="font-semibold">{count}</span>
              <span>{rd.label}</span>
            </span>
          )
        })}
      </div>
    </div>
  )
}

function StatPill({ label, value }: { label: string; value: number }) {
  return (
    <div className="flex items-center gap-1.5 text-sm">
      <span className="font-bold text-gray-900 dark:text-white">{value}</span>
      <span className="text-gray-500 dark:text-gray-400">{label}</span>
    </div>
  )
}
