'use client'

import React, { useState, useMemo, useCallback } from 'react'
import { useParams } from 'next/navigation'
import { HazardForm } from './_components/HazardForm'
import { HazardTable } from './_components/HazardTable'
import { HazardBlockView } from './_components/HazardBlockView'
import { BlockAwareRiskTable } from './_components/BlockAwareRiskTable'
import { RiskAssessmentTable } from './_components/RiskAssessmentTable'
import { ResidualRiskPanel, getResidualStatus } from './_components/ResidualRiskPanel'
import type { ResidualFilter } from './_components/ResidualRiskPanel'
import { LibraryModal } from './_components/LibraryModal'
import { AutoSuggestPanel } from './_components/AutoSuggestPanel'
import { CustomHazardModal } from './_components/CustomHazardModal'
import { LLMGapReviewModal } from './_components/LLMGapReviewModal'
import { useHazards } from './_hooks/useHazards'

type ViewMode = 'list' | 'risk' | 'blocks'

export default function HazardsPage() {
  const params = useParams()
  const projectId = params.projectId as string
  const h = useHazards(projectId)
  const [view, setView] = useState<ViewMode>('risk')
  const [showCustomModal, setShowCustomModal] = useState(false)
  const [showGapReview, setShowGapReview] = useState(false)
  const [residualFilter, setResidualFilter] = useState<ResidualFilter>('all')
  const [decisions, setDecisions] = useState<Record<string, boolean | null>>({})

  const handleDecision = useCallback(async (hazardId: string, acceptable: boolean | null) => {
    setDecisions(prev => ({ ...prev, [hazardId]: acceptable }))
    if (acceptable !== null) {
      try {
        await fetch(`/api/sdk/v1/iace/projects/${projectId}/hazards/${hazardId}/reassess`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ hazard_id: hazardId, is_acceptable: acceptable }),
        })
      } catch (err) { console.error('Decision save failed:', err) }
    }
  }, [projectId])

  const filteredHazards = useMemo(() => {
    if (residualFilter === 'all') return h.hazards
    return h.hazards.filter(hz => {
      const status = getResidualStatus(hz, decisions[hz.id] ?? null)
      return status === residualFilter
    })
  }, [h.hazards, decisions, residualFilter])

  if (h.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">
      <div className="flex items-start justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Hazard Log</h1>
          <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
            Gefaehrdungsanalyse mit 4-Faktor-Risikobewertung (S x F x P x A).
          </p>
          <div className="mt-2 flex rounded-lg border border-gray-200 dark:border-gray-600 overflow-hidden text-xs">
            <button onClick={() => setView('list')}
              className={`px-3 py-1.5 font-medium transition-colors ${view === 'list' ? 'bg-purple-600 text-white' : 'bg-white dark:bg-gray-800 text-gray-600 dark:text-gray-400 hover:bg-gray-50'}`}>
              Hazard-Liste
            </button>
            <button onClick={() => setView('risk')}
              className={`px-3 py-1.5 font-medium transition-colors border-l border-gray-200 dark:border-gray-600 ${view === 'risk' ? 'bg-purple-600 text-white' : 'bg-white dark:bg-gray-800 text-gray-600 dark:text-gray-400 hover:bg-gray-50'}`}>
              Risikobewertung
            </button>
            <button onClick={() => setView('blocks')}
              className={`px-3 py-1.5 font-medium transition-colors border-l border-gray-200 dark:border-gray-600 ${view === 'blocks' ? 'bg-purple-600 text-white' : 'bg-white dark:bg-gray-800 text-gray-600 dark:text-gray-400 hover:bg-gray-50'}`}>
              Bloecke
            </button>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <button onClick={h.handlePatternMatching} disabled={h.matchingPatterns}
            title="Erkennt automatisch Gefaehrdungen anhand der Komponenten-Tags und Lebensphasen"
            className="flex items-center gap-2 px-3 py-2 border border-green-300 text-green-700 rounded-lg hover:bg-green-50 transition-colors disabled:opacity-50 text-sm">
            {h.matchingPatterns ? (
              <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-green-600" />
            ) : (
              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 3v2m6-2v2M9 19v2m6-2v2M5 9H3m2 6H3m18-6h-2m2 6h-2M7 19h10a2 2 0 002-2V7a2 2 0 00-2-2H7a2 2 0 00-2 2v10a2 2 0 002 2zM9 9h6v6H9V9z" />
              </svg>
            )}
            Gefaehrdungen erkennen
          </button>
          <button onClick={h.fetchLibrary}
            className="flex items-center gap-2 px-3 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors text-sm">
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253" />
            </svg>
            Aus Bibliothek
          </button>
          <button onClick={() => setShowCustomModal(true)}
            className="flex items-center gap-2 px-3 py-2 border border-orange-300 text-orange-700 rounded-lg hover:bg-orange-50 transition-colors text-sm">
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
            </svg>
            Eigene Gefaehrdung
          </button>
          <button
            onClick={() => setShowGapReview(true)}
            title="LLM (Qwen/Claude) prueft auf fehlende Gefaehrdungen und Massnahmen — Vorschlaege sind unverbindlich."
            className="flex items-center gap-2 px-3 py-2 border border-indigo-300 text-indigo-700 rounded-lg hover:bg-indigo-50 transition-colors text-sm">
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
            </svg>
            KI-Gap-Review
          </button>
          <button onClick={() => h.setShowForm(true)}
            className="flex items-center gap-2 px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors text-sm">
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
            </svg>
            Manuell hinzufuegen
          </button>
        </div>
      </div>

      {h.matchResult && h.matchResult.matched_patterns?.length > 0 && (
        <AutoSuggestPanel projectId={projectId} matchResult={h.matchResult} applying={h.applyingPatterns}
          onApply={h.handleApplyPatterns} onClose={() => h.setMatchResult(null)} />
      )}

      {h.matchResult && (!h.matchResult.matched_patterns || h.matchResult.matched_patterns.length === 0) && (
        <div className="bg-yellow-50 border border-yellow-200 rounded-xl p-4 flex items-start gap-3">
          <svg className="w-5 h-5 text-yellow-600 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
          <div>
            <p className="text-sm text-yellow-800">
              Keine Patterns erkannt. Fuegen Sie zuerst Komponenten aus der Bibliothek hinzu,
              damit die automatische Erkennung Gefaehrdungen ableiten kann.
            </p>
            <button onClick={() => h.setMatchResult(null)} className="text-xs text-yellow-600 hover:text-yellow-700 mt-1">
              Schliessen
            </button>
          </div>
        </div>
      )}

      {h.hazards.length > 0 && (
        <div className="grid grid-cols-2 md:grid-cols-7 gap-3">
          {[
            { label: 'Gesamt', count: h.hazards.length, color: 'border-gray-200', textColor: 'text-gray-900 dark:text-white', labelColor: 'text-gray-500' },
            { label: 'Nicht akzeptabel', count: h.hazards.filter(x => x.risk_level === 'not_acceptable').length, color: 'border-red-300', textColor: 'text-red-800', labelColor: 'text-red-800' },
            { label: 'Sehr hoch/Kritisch', count: h.hazards.filter(x => x.risk_level === 'very_high' || x.risk_level === 'critical').length, color: 'border-red-200', textColor: 'text-red-600', labelColor: 'text-red-600' },
            { label: 'Hoch', count: h.hazards.filter(x => x.risk_level === 'high').length, color: 'border-orange-200', textColor: 'text-orange-600', labelColor: 'text-orange-600' },
            { label: 'Mittel', count: h.hazards.filter(x => x.risk_level === 'medium').length, color: 'border-yellow-200', textColor: 'text-yellow-600', labelColor: 'text-yellow-600' },
            { label: 'Niedrig', count: h.hazards.filter(x => x.risk_level === 'low').length, color: 'border-green-200', textColor: 'text-green-600', labelColor: 'text-green-600' },
            { label: 'Vernachlaessigbar', count: h.hazards.filter(x => x.risk_level === 'negligible').length, color: 'border-gray-200', textColor: 'text-gray-500', labelColor: 'text-gray-500' },
          ].map(({ label, count, color, textColor, labelColor }) => (
            <div key={label} className={`bg-white dark:bg-gray-800 rounded-lg border ${color} p-4 text-center`}>
              <div className={`text-2xl font-bold ${textColor}`}>{count}</div>
              <div className={`text-xs ${labelColor}`}>{label}</div>
            </div>
          ))}
        </div>
      )}

      {h.showForm && (
        <HazardForm onSubmit={h.handleSubmit} onCancel={() => h.setShowForm(false)}
          lifecyclePhases={h.lifecyclePhases} roles={h.roles} />
      )}

      {h.showLibrary && (
        <LibraryModal library={h.library} onAdd={h.handleAddFromLibrary} onClose={() => h.setShowLibrary(false)} />
      )}

      {showCustomModal && (
        <CustomHazardModal roles={h.roles}
          onSubmit={async (data) => { await h.handleSubmit(data); setShowCustomModal(false) }}
          onClose={() => setShowCustomModal(false)} />
      )}

      {showGapReview && (
        <LLMGapReviewModal
          projectId={projectId}
          onClose={() => setShowGapReview(false)}
        />
      )}

      {h.hazards.length > 0 ? (
        view === 'risk' ? (
          <>
            <ResidualRiskPanel hazards={h.hazards} decisions={decisions}
              activeFilter={residualFilter} onFilterChange={setResidualFilter} />
            <BlockAwareRiskTable projectId={projectId} hazards={filteredHazards}
              onReassess={h.refetch} decisions={decisions} onDecision={handleDecision} />
          </>
        ) : view === 'blocks' ? (
          <HazardBlockView />
        ) : (
          <HazardTable hazards={h.hazards} lifecyclePhases={h.lifecyclePhases} onDelete={h.handleDelete} />
        )
      ) : (
        !h.showForm && (
          <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-12 text-center">
            <div className="w-16 h-16 mx-auto bg-orange-100 dark:bg-orange-900/30 rounded-full flex items-center justify-center mb-4">
              <svg className="w-8 h-8 text-orange-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
              </svg>
            </div>
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white">Kein Hazard Log vorhanden</h3>
            <p className="mt-2 text-gray-500 max-w-md mx-auto">
              Beginnen Sie mit der systematischen Erfassung von Gefaehrdungen. Nutzen Sie die Bibliothek,
              KI-Vorschlaege oder die automatische Erkennung als Ausgangspunkt.
            </p>
            <div className="mt-6 flex items-center justify-center gap-3">
              <button onClick={h.handlePatternMatching} disabled={h.matchingPatterns}
                className="px-6 py-3 border border-green-300 text-green-700 rounded-lg hover:bg-green-50 transition-colors disabled:opacity-50">
                {h.matchingPatterns ? 'Erkennung laeuft...' : 'Auto-Erkennung starten'}
              </button>
              <button onClick={() => h.setShowForm(true)}
                className="px-6 py-3 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors">
                Manuell hinzufuegen
              </button>
              <button onClick={h.fetchLibrary}
                className="px-6 py-3 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors">
                Bibliothek oeffnen
              </button>
            </div>
          </div>
        )
      )}
    </div>
  )
}
