'use client'

import { useMemo } from 'react'
import { Hazard } from './types'

export type ResidualFilter = 'all' | 'open' | 'acceptable' | 'not_acceptable'

interface ResidualRiskPanelProps {
  hazards: Hazard[]
  /** Explicit accept/reject decisions keyed by hazard ID. */
  decisions: Record<string, boolean | null>
  activeFilter: ResidualFilter
  onFilterChange: (f: ResidualFilter) => void
}

// RPZ thresholds matching RiskAssessmentTable logic
function rpz(h: Hazard): number {
  return h.r_inherent || h.severity * h.exposure * h.probability * (h.avoidance >= 1 ? h.avoidance : 1)
}

type ResidualStatus = 'acceptable' | 'not_acceptable' | 'open'

export function getResidualStatus(h: Hazard, decision: boolean | null | undefined): ResidualStatus {
  if (decision === true) return 'acceptable'
  if (decision === false) return 'not_acceptable'
  // No explicit decision -- derive from RPZ
  const r = rpz(h)
  if (r <= 20) return 'acceptable'
  if (r <= 60) return 'open' // conditional -- needs explicit decision
  return 'not_acceptable'
}

export function ResidualRiskPanel({ hazards, decisions, activeFilter, onFilterChange }: ResidualRiskPanelProps) {
  const stats = useMemo(() => {
    let assessed = 0, acceptable = 0, open = 0
    for (const h of hazards) {
      const status = getResidualStatus(h, decisions[h.id] ?? null)
      if (status === 'acceptable') { assessed++; acceptable++ }
      else if (status === 'not_acceptable') { assessed++ }
      else { open++ }
    }
    return { total: hazards.length, assessed, acceptable, open, notAcceptable: assessed - acceptable }
  }, [hazards, decisions])

  const pct = stats.total > 0 ? Math.round((stats.assessed / stats.total) * 100) : 0

  const filters: { key: ResidualFilter; label: string; count: number }[] = [
    { key: 'all', label: 'Alle', count: stats.total },
    { key: 'open', label: 'Offen', count: stats.open },
    { key: 'acceptable', label: 'Akzeptabel', count: stats.acceptable },
    { key: 'not_acceptable', label: 'Nicht akzeptabel', count: stats.notAcceptable },
  ]

  return (
    <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-4 space-y-4">
      <div className="flex items-center justify-between">
        <h2 className="text-sm font-semibold text-gray-900 dark:text-white">
          Restrisiko-Iteration
        </h2>
        <span className="text-xs text-gray-500 dark:text-gray-400">ISO 12100 Schritt 3</span>
      </div>

      {/* Summary stats */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-3 text-center text-xs">
        <div className="bg-gray-50 dark:bg-gray-750 rounded-lg p-2">
          <div className="text-lg font-bold text-gray-900 dark:text-white">{stats.assessed}/{stats.total}</div>
          <div className="text-gray-500">Bewertet</div>
        </div>
        <div className="bg-green-50 dark:bg-green-900/20 rounded-lg p-2">
          <div className="text-lg font-bold text-green-700 dark:text-green-400">{stats.acceptable}</div>
          <div className="text-green-600 dark:text-green-500">Akzeptabel</div>
        </div>
        <div className="bg-red-50 dark:bg-red-900/20 rounded-lg p-2">
          <div className="text-lg font-bold text-red-700 dark:text-red-400">{stats.notAcceptable}</div>
          <div className="text-red-600 dark:text-red-500">Nicht akzeptabel</div>
        </div>
        <div className="bg-yellow-50 dark:bg-yellow-900/20 rounded-lg p-2">
          <div className="text-lg font-bold text-yellow-700 dark:text-yellow-400">{stats.open}</div>
          <div className="text-yellow-600 dark:text-yellow-500">Offen</div>
        </div>
      </div>

      {/* Progress bar */}
      <div>
        <div className="flex items-center justify-between text-xs text-gray-500 mb-1">
          <span>{stats.assessed} von {stats.total} Gefaehrdungen bewertet</span>
          <span>{pct}%</span>
        </div>
        <div className="w-full h-2 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden">
          <div
            className="h-full rounded-full transition-all duration-300 bg-gradient-to-r from-purple-500 to-purple-600"
            style={{ width: `${pct}%` }}
          />
        </div>
      </div>

      {/* Filter buttons */}
      <div className="flex gap-2 flex-wrap">
        {filters.map(f => (
          <button
            key={f.key}
            onClick={() => onFilterChange(f.key)}
            className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${
              activeFilter === f.key
                ? 'bg-purple-600 text-white'
                : 'bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'
            }`}
          >
            {f.label} ({f.count})
          </button>
        ))}
      </div>
    </div>
  )
}
