'use client'

import { useState } from 'react'
import { LibraryHazard, HAZARD_CATEGORIES, CATEGORY_LABELS } from './types'

export function LibraryModal({ library, onAdd, onClose }: {
  library: LibraryHazard[]
  onAdd: (item: LibraryHazard) => void
  onClose: () => void
}) {
  const [search, setSearch] = useState('')
  const [filterCat, setFilterCat] = useState('')
  const [expandedId, setExpandedId] = useState<string | null>(null)

  const filtered = library.filter((h) => {
    const matchSearch = !search || h.name.toLowerCase().includes(search.toLowerCase()) || h.description.toLowerCase().includes(search.toLowerCase())
    const matchCat = !filterCat || h.category === filterCat
    return matchSearch && matchCat
  })

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white dark:bg-gray-800 rounded-xl w-full max-w-3xl max-h-[85vh] flex flex-col">
        <div className="p-6 border-b border-gray-200 dark:border-gray-700">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white">Gefaehrdungsbibliothek ({filtered.length} Eintraege)</h3>
            <button onClick={onClose} className="p-1 text-gray-400 hover:text-gray-600 rounded">
              <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>
          <div className="flex gap-3">
            <input type="text" value={search} onChange={(e) => setSearch(e.target.value)}
              placeholder="Suchen..."
              className="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent dark:bg-gray-700 dark:border-gray-600 dark:text-white" />
            <select value={filterCat} onChange={(e) => setFilterCat(e.target.value)}
              className="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <option value="">Alle Kategorien</option>
              {HAZARD_CATEGORIES.map((cat) => <option key={cat} value={cat}>{CATEGORY_LABELS[cat] || cat}</option>)}
            </select>
          </div>
        </div>
        <div className="flex-1 overflow-auto p-4 space-y-2">
          {filtered.length > 0 ? (
            filtered.map((item) => (
              <div key={item.id} className="rounded-lg border border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-750">
                <div className="flex items-center justify-between p-3">
                  <div className="flex-1 min-w-0 mr-3 cursor-pointer"
                    onClick={() => setExpandedId(expandedId === item.id ? null : item.id)}>
                    <div className="text-sm font-medium text-gray-900 dark:text-white">{item.name}</div>
                    <div className="text-xs text-gray-500 truncate">{item.description}</div>
                    <div className="flex items-center gap-2 mt-1">
                      <span className="text-xs text-gray-400">{CATEGORY_LABELS[item.category] || item.category}</span>
                      <span className="text-xs text-gray-400">
                        S:{item.default_severity} F:{item.default_exposure || 3} P:{item.default_probability} A:{item.default_avoidance || 3}
                      </span>
                    </div>
                  </div>
                  <button onClick={() => onAdd(item)}
                    className="flex-shrink-0 px-3 py-1.5 text-xs bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors">
                    Hinzufuegen
                  </button>
                </div>
                {expandedId === item.id && (
                  <div className="px-3 pb-3 space-y-2 text-xs">
                    {item.typical_causes && item.typical_causes.length > 0 && (
                      <div><span className="font-medium text-gray-600">Typische Ursachen: </span>
                        <span className="text-gray-500">{item.typical_causes.join(', ')}</span></div>
                    )}
                    {item.typical_harm && (
                      <div><span className="font-medium text-gray-600">Typischer Schaden: </span>
                        <span className="text-gray-500">{item.typical_harm}</span></div>
                    )}
                    {item.recommended_measures_design && item.recommended_measures_design.length > 0 && (
                      <div><span className="font-medium text-blue-600">Konstruktiv: </span>
                        <span className="text-gray-500">{item.recommended_measures_design.join(', ')}</span></div>
                    )}
                    {item.recommended_measures_technical && item.recommended_measures_technical.length > 0 && (
                      <div><span className="font-medium text-green-600">Technisch: </span>
                        <span className="text-gray-500">{item.recommended_measures_technical.join(', ')}</span></div>
                    )}
                    {item.recommended_measures_information && item.recommended_measures_information.length > 0 && (
                      <div><span className="font-medium text-yellow-600">Information: </span>
                        <span className="text-gray-500">{item.recommended_measures_information.join(', ')}</span></div>
                    )}
                  </div>
                )}
              </div>
            ))
          ) : (
            <div className="text-center py-8 text-gray-500">Keine Eintraege gefunden</div>
          )}
        </div>
      </div>
    </div>
  )
}
