'use client'

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

export function AutoSuggestPanel({ matchResult, applying, onApply, onClose }: {
  projectId: string
  matchResult: MatchOutput
  applying: boolean
  onApply: (acceptedHazardCats: string[], acceptedMeasureIds: string[], acceptedEvidenceIds: string[], patternIds: string[]) => void
  onClose: () => void
}) {
  const [selectedHazards, setSelectedHazards] = useState<Set<string>>(
    new Set((matchResult.suggested_hazards || []).map(h => h.category))
  )
  const [selectedMeasures, setSelectedMeasures] = useState<Set<string>>(
    new Set((matchResult.suggested_measures || []).map(m => m.measure_id))
  )
  const [selectedEvidence, setSelectedEvidence] = useState<Set<string>>(
    new Set((matchResult.suggested_evidence || []).map(e => e.evidence_id))
  )

  function toggle<T>(set: Set<T>, setSet: (s: Set<T>) => void, key: T) {
    const next = new Set(set)
    if (next.has(key)) next.delete(key)
    else next.add(key)
    setSet(next)
  }

  const totalSelected = selectedHazards.size + selectedMeasures.size + selectedEvidence.size

  return (
    <div className="bg-white dark:bg-gray-800 rounded-xl border-2 border-purple-300 p-6 space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-lg font-semibold text-gray-900 dark:text-white">Pattern-Matching Ergebnisse</h3>
          <p className="text-sm text-gray-500">
            {matchResult.matched_patterns.length} Patterns erkannt, {matchResult.resolved_tags.length} Tags aufgeloest
          </p>
        </div>
        <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>
        <h4 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
          Erkannte Patterns ({matchResult.matched_patterns.length})
        </h4>
        <div className="flex flex-wrap gap-2">
          {matchResult.matched_patterns.sort((a, b) => b.priority - a.priority).map(p => (
            <span key={p.pattern_id} className="inline-flex items-center gap-1 px-2 py-1 rounded-lg text-xs bg-purple-50 text-purple-700 border border-purple-200">
              <span className="font-mono">{p.pattern_id}</span>
              <span>{p.pattern_name}</span>
              <span className="text-purple-400">P:{p.priority}</span>
            </span>
          ))}
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
        <div className="border border-orange-200 rounded-lg p-3 bg-orange-50/50">
          <h4 className="text-sm font-semibold text-orange-800 mb-2">Gefaehrdungen ({matchResult.suggested_hazards.length})</h4>
          <div className="space-y-2 max-h-48 overflow-auto">
            {matchResult.suggested_hazards.map(h => (
              <label key={h.category} className="flex items-start gap-2 cursor-pointer">
                <input type="checkbox" checked={selectedHazards.has(h.category)}
                  onChange={() => toggle(selectedHazards, setSelectedHazards, h.category)}
                  className="mt-0.5 accent-purple-600" />
                <div>
                  <div className="text-xs font-medium text-gray-900">{CATEGORY_LABELS[h.category] || h.category}</div>
                  <div className="text-xs text-gray-500">Konfidenz: {Math.round(h.confidence * 100)}%</div>
                </div>
              </label>
            ))}
          </div>
        </div>

        <div className="border border-green-200 rounded-lg p-3 bg-green-50/50">
          <h4 className="text-sm font-semibold text-green-800 mb-2">Massnahmen ({matchResult.suggested_measures.length})</h4>
          <div className="space-y-2 max-h-48 overflow-auto">
            {matchResult.suggested_measures.map(m => (
              <label key={m.measure_id} className="flex items-start gap-2 cursor-pointer">
                <input type="checkbox" checked={selectedMeasures.has(m.measure_id)}
                  onChange={() => toggle(selectedMeasures, setSelectedMeasures, m.measure_id)}
                  className="mt-0.5 accent-purple-600" />
                <div>
                  <div className="text-xs font-medium text-gray-900 font-mono">{m.measure_id}</div>
                  <div className="text-xs text-gray-500">von {m.source_patterns.length} Pattern(s)</div>
                </div>
              </label>
            ))}
          </div>
        </div>

        <div className="border border-blue-200 rounded-lg p-3 bg-blue-50/50">
          <h4 className="text-sm font-semibold text-blue-800 mb-2">Nachweise ({matchResult.suggested_evidence.length})</h4>
          <div className="space-y-2 max-h-48 overflow-auto">
            {matchResult.suggested_evidence.map(e => (
              <label key={e.evidence_id} className="flex items-start gap-2 cursor-pointer">
                <input type="checkbox" checked={selectedEvidence.has(e.evidence_id)}
                  onChange={() => toggle(selectedEvidence, setSelectedEvidence, e.evidence_id)}
                  className="mt-0.5 accent-purple-600" />
                <div>
                  <div className="text-xs font-medium text-gray-900 font-mono">{e.evidence_id}</div>
                  <div className="text-xs text-gray-500">von {e.source_patterns.length} Pattern(s)</div>
                </div>
              </label>
            ))}
          </div>
        </div>
      </div>

      {matchResult.resolved_tags.length > 0 && (
        <div>
          <h4 className="text-xs font-semibold text-gray-500 mb-1">Aufgeloeste Tags</h4>
          <div className="flex flex-wrap gap-1">
            {matchResult.resolved_tags.map(tag => (
              <span key={tag} className="text-xs px-1.5 py-0.5 rounded bg-gray-100 text-gray-500">{tag}</span>
            ))}
          </div>
        </div>
      )}

      <div className="flex items-center justify-between pt-2 border-t border-gray-200">
        <span className="text-sm text-gray-500">{totalSelected} Elemente ausgewaehlt</span>
        <div className="flex gap-3">
          <button onClick={onClose} className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors">
            Abbrechen
          </button>
          <button
            onClick={() => onApply(
              Array.from(selectedHazards),
              Array.from(selectedMeasures),
              Array.from(selectedEvidence),
              matchResult.matched_patterns.map(p => p.pattern_id),
            )}
            disabled={totalSelected === 0 || applying}
            className={`px-6 py-2 rounded-lg font-medium transition-colors ${totalSelected > 0 && !applying ? 'bg-purple-600 text-white hover:bg-purple-700' : 'bg-gray-200 text-gray-400 cursor-not-allowed'}`}>
            {applying ? (
              <span className="flex items-center gap-2">
                <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white" />
                Wird uebernommen...
              </span>
            ) : `${totalSelected} uebernehmen`}
          </button>
        </div>
      </div>
    </div>
  )
}
