'use client'

import { useState } from 'react'
import { Hazard, SuggestedMeasure, REDUCTION_TYPES } from './types'

export function SuggestMeasuresModal({
  hazards,
  projectId,
  onAddMeasure,
  onClose,
}: {
  hazards: Hazard[]
  projectId: string
  onAddMeasure: (title: string, description: string, reductionType: string, hazardId: string) => void
  onClose: () => void
}) {
  const [selectedHazard, setSelectedHazard] = useState<string>('')
  const [suggested, setSuggested] = useState<SuggestedMeasure[]>([])
  const [loadingSuggestions, setLoadingSuggestions] = useState(false)

  const riskColors: Record<string, string> = {
    not_acceptable: 'border-red-400 bg-red-50',
    very_high: 'border-red-300 bg-red-50',
    critical: 'border-red-300 bg-red-50',
    high: 'border-orange-300 bg-orange-50',
    medium: 'border-yellow-300 bg-yellow-50',
    low: 'border-green-300 bg-green-50',
  }

  async function handleSelectHazard(hazardId: string) {
    setSelectedHazard(hazardId)
    setSuggested([])
    if (!hazardId) return

    setLoadingSuggestions(true)
    try {
      const res = await fetch(`/api/sdk/v1/iace/projects/${projectId}/hazards/${hazardId}/suggest-measures`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
      })
      if (res.ok) {
        const json = await res.json()
        setSuggested(json.suggested_measures || [])
      }
    } catch (err) {
      console.error('Failed to suggest measures:', err)
    } finally {
      setLoadingSuggestions(false)
    }
  }

  const groupedByType = {
    design: suggested.filter(m => m.reduction_type === 'design'),
    protection: suggested.filter(m => m.reduction_type === 'protection'),
    information: suggested.filter(m => m.reduction_type === 'information'),
  }

  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">Massnahmen-Vorschlaege</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>
          <p className="text-sm text-gray-500 mb-3">
            Waehlen Sie eine Gefaehrdung, um passende Massnahmen vorgeschlagen zu bekommen.
          </p>
          <div className="flex flex-wrap gap-2">
            {hazards.map(h => (
              <button
                key={h.id}
                onClick={() => handleSelectHazard(h.id)}
                className={`px-3 py-1.5 text-xs rounded-lg border transition-colors ${
                  selectedHazard === h.id
                    ? 'border-purple-400 bg-purple-50 text-purple-700 font-medium'
                    : `${riskColors[h.risk_level] || 'border-gray-200 bg-white'} text-gray-700 hover:border-purple-300`
                }`}
              >
                {h.name}
              </button>
            ))}
          </div>
        </div>

        <div className="flex-1 overflow-auto p-6">
          {loadingSuggestions ? (
            <div className="flex items-center justify-center py-12">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600" />
            </div>
          ) : suggested.length > 0 ? (
            <div className="space-y-6">
              {(['design', 'protection', 'information'] as const).map(type => {
                const items = groupedByType[type]
                if (items.length === 0) return null
                const config = REDUCTION_TYPES[type]
                return (
                  <div key={type}>
                    <div className={`flex items-center gap-2 px-3 py-2 rounded-lg ${config.headerColor} mb-3`}>
                      {config.icon}
                      <span className="text-sm font-semibold">{config.label}</span>
                      <span className="ml-auto text-sm font-bold">{items.length}</span>
                    </div>
                    <div className="space-y-2">
                      {items.map(m => (
                        <div key={m.id} className="border border-gray-200 rounded-lg p-3 hover:bg-gray-50 transition-colors">
                          <div className="flex items-start justify-between">
                            <div className="flex-1">
                              <div className="flex items-center gap-2 mb-1">
                                <span className="text-xs font-mono text-gray-400">{m.id}</span>
                                {m.sub_type && (
                                  <span className="text-xs px-1.5 py-0.5 rounded bg-gray-100 text-gray-600">{m.sub_type}</span>
                                )}
                              </div>
                              <div className="text-sm font-medium text-gray-900 dark:text-white">{m.name}</div>
                              <div className="text-xs text-gray-500 mt-0.5">{m.description}</div>
                            </div>
                            <button
                              onClick={() => onAddMeasure(m.name, m.description, m.reduction_type, selectedHazard)}
                              className="ml-3 px-3 py-1.5 text-xs bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors flex-shrink-0"
                            >
                              Uebernehmen
                            </button>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                )
              })}
            </div>
          ) : selectedHazard ? (
            <div className="text-center py-12 text-gray-500">
              Keine Vorschlaege fuer diese Gefaehrdung gefunden.
            </div>
          ) : (
            <div className="text-center py-12 text-gray-500">
              Waehlen Sie eine Gefaehrdung aus, um Vorschlaege zu erhalten.
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
