import type { ChunkDetail } from './types'

interface ResultsListProps {
  results: ChunkDetail[]
  selectedChunk: ChunkDetail | null
  searchQuery: string
  onSelect: (chunk: ChunkDetail) => void
}

function highlightText(text: string, query: string) {
  if (!query) return text
  const words = query.toLowerCase().split(' ').filter(w => w.length > 2)
  let result = text
  words.forEach(word => {
    const regex = new RegExp(`(${word})`, 'gi')
    result = result.replace(regex, '<mark class="bg-yellow-200 dark:bg-yellow-800 px-0.5 rounded">$1</mark>')
  })
  return result
}

export function ResultsList({ results, selectedChunk, searchQuery, onSelect }: ResultsListProps) {
  return (
    <div className="bg-white dark:bg-slate-800 rounded-lg shadow p-4">
      <h3 className="text-md font-semibold text-gray-900 dark:text-white mb-4">
        Gefundene Chunks ({results.length})
      </h3>
      <div className="space-y-3 max-h-[600px] overflow-y-auto">
        {results.map((result, idx) => (
          <div
            key={idx}
            onClick={() => onSelect(result)}
            className={`p-4 border rounded-lg cursor-pointer transition-all ${
              selectedChunk?.text === result.text
                ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
                : 'border-gray-200 dark:border-slate-700 hover:border-gray-300 dark:hover:border-slate-600'
            }`}
          >
            {/* Header */}
            <div className="flex items-center justify-between mb-2">
              <div className="flex items-center gap-2">
                <span className="text-xs font-medium px-2 py-0.5 bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400 rounded">
                  {result.regulation_code}
                </span>
                {result.article && (
                  <span className="text-xs text-gray-500 dark:text-gray-400">
                    Art. {result.article}
                    {result.paragraph && ` Abs. ${result.paragraph}`}
                  </span>
                )}
              </div>
              <span className="text-xs text-gray-400">
                Score: {(result.score || 0).toFixed(3)}
              </span>
            </div>

            {/* Text Preview */}
            <p
              className="text-sm text-gray-700 dark:text-gray-300 line-clamp-4"
              dangerouslySetInnerHTML={{
                __html: highlightText(result.text.substring(0, 400) + (result.text.length > 400 ? '...' : ''), searchQuery)
              }}
            />

            {/* Metadata */}
            <div className="mt-2 flex items-center gap-4 text-xs text-gray-400">
              <span>Chunk #{result.chunk_index || idx}</span>
              <span>{result.text.length} Zeichen</span>
            </div>
          </div>
        ))}
      </div>
    </div>
  )
}
