'use client'

import { useParams } from 'next/navigation'
import { useFMEA, type FMEARow } from './_hooks/useFMEA'

const COMP_TYPE_LABELS: Record<string, string> = {
  mechanical: 'Mechanisch', electrical: 'Elektrisch', sensor: 'Sensor',
  actuator: 'Aktor', software: 'Software', firmware: 'Firmware',
  ai_model: 'KI-Modell', hmi: 'HMI', network: 'Netzwerk',
  hydraulic: 'Hydraulik', pneumatic: 'Pneumatik', safety: 'Sicherheit',
}

function rpzColor(rpz: number): string {
  if (rpz > 200) return 'bg-red-100 text-red-800 border-red-200'
  if (rpz > 100) return 'bg-orange-100 text-orange-800 border-orange-200'
  if (rpz > 50) return 'bg-yellow-100 text-yellow-800 border-yellow-200'
  return 'bg-green-100 text-green-800 border-green-200'
}

function rpzLabel(rpz: number): string {
  if (rpz > 200) return 'Kritisch'
  if (rpz > 100) return 'Handlungsbedarf'
  if (rpz > 50) return 'Beobachten'
  return 'Akzeptabel'
}

export default function FMEAPage() {
  const { projectId } = useParams<{ projectId: string }>()
  const { rows, loading, stats } = useFMEA(projectId)

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600" />
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-xl font-bold text-gray-900 dark:text-white">FMEA-Worksheet</h1>
        <p className="text-sm text-gray-500 dark:text-gray-400 mt-0.5">
          Fehlermoeglich&shy;keits- und Einflussanalyse — RPZ = Severity x Occurrence x Detection
        </p>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-4 gap-3">
        <StatCard label="Gesamt" value={stats.total} color="gray" />
        <StatCard label="Kritisch (RPZ &gt; 200)" value={stats.critical} color="red" />
        <StatCard label="Handlungsbedarf (RPZ &gt; 100)" value={stats.actionRequired} color="orange" />
        <StatCard label="Akzeptabel (RPZ &le; 100)" value={stats.acceptable} color="green" />
      </div>

      {/* RPZ Threshold Info */}
      <div className="p-3 rounded-lg bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 text-xs text-amber-800 dark:text-amber-300">
        <strong>RPZ-Schwellen:</strong> Kritisch &gt; 200 | Handlungsbedarf &gt; 100 | Beobachten &gt; 50 | Akzeptabel &le; 50.
        Massnahmen sind erforderlich ab RPZ &gt; 100.
      </div>

      {/* FMEA Table */}
      {rows.length === 0 ? (
        <div className="text-center py-12 text-gray-500">
          Keine Failure Modes gefunden. Bitte zuerst Komponenten erfassen.
        </div>
      ) : (
        <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="bg-gray-50 dark:bg-gray-750 border-b border-gray-200 dark:border-gray-700">
                  <th className="px-3 py-2.5 text-left text-xs font-medium text-gray-500 uppercase">Komponente</th>
                  <th className="px-3 py-2.5 text-left text-xs font-medium text-gray-500 uppercase">Typ</th>
                  <th className="px-3 py-2.5 text-left text-xs font-medium text-gray-500 uppercase">Fehlerart</th>
                  <th className="px-3 py-2.5 text-left text-xs font-medium text-gray-500 uppercase">Auswirkung</th>
                  <th className="px-3 py-2.5 text-center text-xs font-medium text-gray-500 uppercase w-12">S</th>
                  <th className="px-3 py-2.5 text-center text-xs font-medium text-gray-500 uppercase w-12">O</th>
                  <th className="px-3 py-2.5 text-center text-xs font-medium text-gray-500 uppercase w-12">D</th>
                  <th className="px-3 py-2.5 text-center text-xs font-medium text-gray-500 uppercase w-16">RPZ</th>
                  <th className="px-3 py-2.5 text-left text-xs font-medium text-gray-500 uppercase">Bewertung</th>
                  <th className="px-3 py-2.5 text-left text-xs font-medium text-gray-500 uppercase">Erkennung</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
                {rows.map((row, idx) => (
                  <FMEATableRow key={`${row.component.id}-${row.failureMode.id}-${idx}`} row={row} />
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  )
}

function FMEATableRow({ row }: { row: FMEARow }) {
  const color = rpzColor(row.rpz)
  return (
    <tr className={`hover:bg-gray-50 dark:hover:bg-gray-750 transition-colors ${row.rpz > 100 ? 'bg-red-50/30 dark:bg-red-900/10' : ''}`}>
      <td className="px-3 py-2.5 text-sm font-medium text-gray-900 dark:text-white">{row.component.name}</td>
      <td className="px-3 py-2.5">
        <span className="text-xs px-2 py-0.5 rounded bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300">
          {COMP_TYPE_LABELS[row.component.component_type] || row.component.component_type}
        </span>
      </td>
      <td className="px-3 py-2.5">
        <div className="text-sm text-gray-900 dark:text-white">{row.failureMode.name_de}</div>
        <div className="text-[10px] text-gray-400">{row.failureMode.id}</div>
      </td>
      <td className="px-3 py-2.5 text-xs text-gray-600 dark:text-gray-400 max-w-[200px] truncate" title={row.failureMode.effect}>
        {row.failureMode.effect}
      </td>
      <td className="px-3 py-2.5 text-sm text-center font-medium text-gray-900 dark:text-white">{row.severity}</td>
      <td className="px-3 py-2.5 text-sm text-center font-medium text-gray-900 dark:text-white">{row.occurrence}</td>
      <td className="px-3 py-2.5 text-sm text-center font-medium text-gray-900 dark:text-white">{row.detection}</td>
      <td className="px-3 py-2.5 text-center">
        <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-sm font-bold border ${color}`}>
          {row.rpz}
        </span>
      </td>
      <td className="px-3 py-2.5">
        <span className={`text-xs px-2 py-0.5 rounded-full ${color}`}>{rpzLabel(row.rpz)}</span>
      </td>
      <td className="px-3 py-2.5 text-xs text-gray-500 dark:text-gray-400 max-w-[150px] truncate" title={row.failureMode.detection_hint}>
        {row.failureMode.detection_hint || '-'}
      </td>
    </tr>
  )
}

function StatCard({ label, value, color }: { label: string; value: number; color: string }) {
  const colors: Record<string, string> = {
    gray: 'bg-gray-50 text-gray-700 border-gray-200',
    red: 'bg-red-50 text-red-700 border-red-200',
    orange: 'bg-orange-50 text-orange-700 border-orange-200',
    green: 'bg-green-50 text-green-700 border-green-200',
  }
  return (
    <div className={`rounded-xl border p-4 ${colors[color] || colors.gray}`}>
      <div className="text-2xl font-bold">{value}</div>
      <div className="text-xs mt-1">{label}</div>
    </div>
  )
}
