import React from 'react';
import { type FileSearchResult } from '../api/server/files/betterFilesApi';

interface Props {
    results: FileSearchResult[];
    searchQuery: string;
    renderItem: (result: FileSearchResult, derivedDirectory: string) => React.ReactNode;
}

const renderHighlightedExcerpt = (excerpt: string, query: string) => {
    const needle = query.trim();
    if (!needle) return excerpt;

    const lowerExcerpt = excerpt.toLowerCase();
    const lowerNeedle = needle.toLowerCase();
    const parts: React.ReactNode[] = [];
    let cursor = 0;

    while (cursor < excerpt.length) {
        const index = lowerExcerpt.indexOf(lowerNeedle, cursor);
        if (index === -1) {
            parts.push(excerpt.slice(cursor));
            break;
        }

        if (index > cursor) {
            parts.push(excerpt.slice(cursor, index));
        }

        parts.push(
            <mark key={`${index}-${parts.length}`} className='rounded-sm bg-yellow-400/20 px-0.5 text-yellow-200'>
                {excerpt.slice(index, index + needle.length)}
            </mark>
        );
        cursor = index + needle.length;
    }

    return parts;
};

const SearchResultsList: React.FC<Props> = ({ results, searchQuery, renderItem }) => {
    if (results.length === 0) {
        return (
            <div className="flex flex-col items-center justify-center py-12 text-neutral-300">
                <svg className="w-16 h-16 mb-4 opacity-50" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                <p className="text-sm">No results found for "{searchQuery}"</p>
            </div>
        );
    }

    const visibleResults = results.filter(
        result => !result.path.split('/').includes('.trash-bin')
    );

    if (visibleResults.length === 0) {
        return (
            <div className="flex flex-col items-center justify-center py-12 text-neutral-300">
                <svg className="w-16 h-16 mb-4 opacity-50" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                <p className="text-sm">No results found for "{searchQuery}"</p>
            </div>
        );
    }

    return (
        <div className="space-y-0.5">
            <div className="px-3 py-2 text-xs text-neutral-300 font-semibold">
                Search Results ({visibleResults.length})
            </div>
            {visibleResults.map((result) => {
                const derivedDirectory = (() => {
                    if (result.directory && result.directory !== '/') {
                        return result.directory;
                    }
                    const lastSlash = result.path.lastIndexOf('/');
                    if (lastSlash <= 0) return '/';
                    return result.path.substring(0, lastSlash) || '/';
                })();

                const match = result.matches?.[0];

                return (
                    <React.Fragment key={result.path}>
                        {renderItem(result, derivedDirectory)}
                        {match && (
                            <div className='ml-8 mr-2 -mt-0.5 mb-1 min-w-0 rounded-sm border-l border-yellow-400/30 bg-yellow-400/5 px-2 py-1 text-[10px] leading-4 text-neutral-400'>
                                <span className='mr-2 font-mono text-yellow-300/80'>L{match.line}</span>
                                <span className='font-mono'>{renderHighlightedExcerpt(match.excerpt, searchQuery)}</span>
                            </div>
                        )}
                    </React.Fragment>
                );
            })}
        </div>
    );
};

export default SearchResultsList;
