'use client'

import { useState } from 'react'
import { VERIFICATION_METHODS, type SuggestedEvidence } from './verification-types'

export function SuggestEvidenceModal({
  mitigations, projectId, onAddEvidence, onClose,
}: {
  mitigations: { id: string; title: string }[]
  projectId: string
  onAddEvidence: (title: string, description: string, method: string, mitigationId: string) => void
  onClose: () => void
}) {
  const [selectedMitigation, setSelectedMitigation] = useState<string>('')
  const [suggested, setSuggested] = useState<SuggestedEvidence[]>([])
  const [loadingSuggestions, setLoadingSuggestions] = useState(false)
  const [search, setSearch] = useState('')

  const filtered = search.trim()
    ? mitigations.filter(m => (m.title || '').toLowerCase().includes(search.toLowerCase()))
    : mitigations
  const displayed = filtered.slice(0, 20) // Show max 20 at a time

  async function handleSelectMitigation(mitigationId: string) {
    setSelectedMitigation(mitigationId)
    setSuggested([])
    if (!mitigationId) return
    setLoadingSuggestions(true)
    try {
      const res = await fetch(`/api/sdk/v1/iace/projects/${projectId}/mitigations/${mitigationId}/suggest-evidence`, {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
      })
      if (res.ok) { const json = await res.json(); setSuggested(json.suggested_evidence || []) }
    } catch (err) { console.error('Failed to suggest evidence:', err) }
    finally { setLoadingSuggestions(false) }
  }

  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">Nachweise vorschlagen</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-2">
            Waehlen Sie eine Massnahme ({mitigations.length} gesamt). Suchen Sie nach Name:
          </p>
          <input
            type="text" value={search} onChange={e => setSearch(e.target.value)}
            placeholder="Massnahme suchen..."
            className="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg mb-3 focus:ring-2 focus:ring-purple-400 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
          />
          <div className="max-h-[200px] overflow-auto space-y-1">
            {displayed.map(m => (
              <button
                key={m.id} onClick={() => handleSelectMitigation(m.id)}
                className={`w-full text-left px-3 py-2 text-xs rounded-lg border transition-colors ${
                  selectedMitigation === m.id
                    ? 'border-purple-400 bg-purple-50 text-purple-700 font-medium'
                    : 'border-gray-100 bg-white text-gray-700 hover:border-purple-300 hover:bg-gray-50'
                }`}
              >
                {m.title || '(Ohne Titel)'}
              </button>
            ))}
            {filtered.length > 20 && (
              <p className="text-xs text-gray-400 text-center py-1">
                {filtered.length - 20} weitere — Suchbegriff eingeben um zu filtern
              </p>
            )}
            {filtered.length === 0 && (
              <p className="text-xs text-gray-400 text-center py-2">Keine Massnahmen gefunden</p>
            )}
          </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-3">
              {suggested.map(ev => (
                <div key={ev.id} className="border border-gray-200 rounded-lg p-4 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">{ev.id}</span>
                        {ev.method && (
                          <span className="text-xs px-1.5 py-0.5 rounded bg-blue-50 text-blue-600">
                            {VERIFICATION_METHODS.find(m => m.value === ev.method)?.label || ev.method}
                          </span>
                        )}
                      </div>
                      <div className="text-sm font-medium text-gray-900 dark:text-white">{ev.name}</div>
                      <div className="text-xs text-gray-500 mt-0.5">{ev.description}</div>
                    </div>
                    <button
                      onClick={() => onAddEvidence(ev.name, ev.description, ev.method || 'test_report', selectedMitigation)}
                      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>
          ) : selectedMitigation ? (
            <div className="text-center py-12 text-gray-500">Keine Vorschlaege fuer diese Massnahme gefunden.</div>
          ) : (
            <div className="text-center py-12 text-gray-500">Waehlen Sie eine Massnahme aus, um Nachweise vorgeschlagen zu bekommen.</div>
          )}
        </div>
      </div>
    </div>
  )
}
