"use client";

import { useState, useRef, useEffect } from "react";
import { Search as SearchIcon, X, Loader2, MessageSquare, ChevronRight } from "lucide-react";
import { motion, AnimatePresence } from "framer-motion";
import { formatDistanceToNow } from "date-fns";
import Image from "next/image";
import Link from "next/link";
import { useDebounce } from "use-debounce";

interface SearchResult {
    id: string;
    conversationId: string;
    conversationTitle: string;
    content: string;
    sender: {
        id: string;
        name: string | null;
        avatar_url: string | null;
    };
    createdAt: string;
}

export function SearchOverlay({
    isOpen,
    onClose,
    conversationId
}: {
    isOpen: boolean;
    onClose: () => void;
    conversationId?: string;
}) {
    const [query, setQuery] = useState("");
    const [debouncedQuery] = useDebounce(query, 500);
    const [results, setResults] = useState<SearchResult[]>([]);
    const [isLoading, setIsLoading] = useState(false);
    const inputRef = useRef<HTMLInputElement>(null);

    useEffect(() => {
        if (isOpen && inputRef.current) {
            setTimeout(() => inputRef.current?.focus(), 100);
        }
    }, [isOpen]);

    useEffect(() => {
        const fetchResults = async () => {
            if (!debouncedQuery.trim()) {
                setResults([]);
                setIsLoading(false);
                return;
            }

            setIsLoading(true);
            try {
                let url = `/api/messages/search?q=${encodeURIComponent(debouncedQuery)}`;
                if (conversationId) {
                    url += `&conversationId=${encodeURIComponent(conversationId)}`;
                }

                const res = await fetch(url);
                if (res.ok) {
                    const data = await res.json();
                    setResults(data.results || []);
                }
            } catch (error) {
                console.error("Search failed:", error);
            } finally {
                setIsLoading(false);
            }
        };

        fetchResults();
    }, [debouncedQuery, conversationId]);

    // Handle escape key
    useEffect(() => {
        const handleKeyDown = (e: KeyboardEvent) => {
            if (e.key === 'Escape' && isOpen) {
                onClose();
            }
        };
        window.addEventListener('keydown', handleKeyDown);
        return () => window.removeEventListener('keydown', handleKeyDown);
    }, [isOpen, onClose]);

    if (!isOpen) return null;

    // Highlight search terms
    const highlightText = (text: string, highlight: string) => {
        if (!highlight.trim()) return <span>{text}</span>;

        const parts = text.split(new RegExp(`(${highlight})`, 'gi'));
        return (
            <span>
                {parts.map((part, i) =>
                    part.toLowerCase() === highlight.toLowerCase()
                        ? <span key={i} className="bg-yellow-200 text-yellow-900 rounded-[2px] px-0.5">{part}</span>
                        : <span key={i}>{part}</span>
                )}
            </span>
        );
    };

    return (
        <div className="fixed inset-0 z-50 flex items-start justify-center pt-[10vh] sm:pt-[15vh] px-4">
            {/* Backdrop */}
            <motion.div
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                className="fixed inset-0 bg-slate-900/40 backdrop-blur-sm"
                onClick={onClose}
            />

            {/* Search Dialog */}
            <motion.div
                initial={{ opacity: 0, scale: 0.95, y: -20 }}
                animate={{ opacity: 1, scale: 1, y: 0 }}
                exit={{ opacity: 0, scale: 0.95, y: -20 }}
                transition={{ duration: 0.2 }}
                className="relative w-full max-w-2xl bg-white rounded-2xl shadow-2xl border border-slate-200 overflow-hidden flex flex-col max-h-[70vh]"
            >
                {/* Search Header */}
                <div className="flex items-center gap-3 px-4 py-3 border-b border-slate-100 bg-white z-10">
                    <SearchIcon className={`h-5 w-5 ${isLoading ? 'text-primary animate-pulse' : 'text-slate-400'}`} />
                    <input
                        ref={inputRef}
                        type="text"
                        value={query}
                        onChange={(e) => setQuery(e.target.value)}
                        placeholder={conversationId ? "Search in this conversation..." : "Search across all messages..."}
                        className="flex-1 bg-transparent border-none text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-0 text-[15px]"
                    />
                    {query && (
                        <button
                            onClick={() => setQuery("")}
                            className="p-1 text-slate-400 hover:text-slate-600 rounded-full hover:bg-slate-100 transition-colors"
                        >
                            <X className="h-4 w-4" />
                        </button>
                    )}
                    <div className="h-6 w-px bg-slate-200 mx-1"></div>
                    <button
                        onClick={onClose}
                        className="text-[13px] font-medium text-slate-500 hover:text-slate-800 px-2 py-1 rounded-md hover:bg-slate-100 transition-colors"
                    >
                        ESC
                    </button>
                </div>

                {/* Search Results */}
                <div className="flex-1 overflow-y-auto bg-slate-50/50">
                    {!query.trim() ? (
                        <div className="p-12 text-center flex flex-col items-center justify-center h-full text-slate-500">
                            <MessageSquare className="h-10 w-10 mb-3 text-slate-300" />
                            <p className="text-[15px] font-medium">Search your messages</p>
                            <p className="text-sm text-slate-400 mt-1 max-w-[250px] mx-auto">
                                Find specific keywords or phrases in your chat history
                            </p>
                        </div>
                    ) : isLoading && results.length === 0 ? (
                        <div className="p-12 flex items-center justify-center">
                            <Loader2 className="h-6 w-6 text-primary animate-spin" />
                        </div>
                    ) : results.length === 0 ? (
                        <div className="p-12 text-center text-slate-500">
                            <p className="text-[15px] font-medium text-slate-800">No results found</p>
                            <p className="text-sm mt-1 text-slate-500">
                                We couldn't find anything matching "{query}"
                            </p>
                        </div>
                    ) : (
                        <div className="divide-y divide-slate-100">
                            {results.map((result) => (
                                <Link
                                    key={result.id}
                                    href={`?conversation=${result.conversationId}&message=${result.id}`}
                                    onClick={onClose}
                                    className="flex items-start gap-4 p-4 hover:bg-white transition-colors group cursor-pointer"
                                >
                                    {/* Avatar */}
                                    <div className="flex-shrink-0 relative">
                                        {result.sender.avatar_url ? (
                                            <Image
                                                src={result.sender.avatar_url}
                                                alt={result.sender.name || "User"}
                                                width={40}
                                                height={40}
                                                className="rounded-full object-cover ring-2 ring-white"
                                            />
                                        ) : (
                                            <div className="w-10 h-10 rounded-full bg-primary/10 text-primary flex items-center justify-center font-bold tracking-tight text-sm ring-2 ring-white">
                                                {result.sender.name ? result.sender.name.charAt(0).toUpperCase() : "?"}
                                            </div>
                                        )}
                                    </div>

                                    {/* Content */}
                                    <div className="flex-1 min-w-0">
                                        <div className="flex items-baseline justify-between gap-2 mb-1">
                                            <div className="flex items-center gap-2 truncate">
                                                <span className="font-semibold tracking-tight text-slate-900 text-[14px]">
                                                    {result.sender.name || "Unknown User"}
                                                </span>
                                                <span className="text-[13px] text-slate-500 truncate hidden sm:inline-block">
                                                    in {result.conversationTitle}
                                                </span>
                                            </div>
                                            <span className="text-[11px] font-medium text-slate-400 flex-shrink-0 uppercase tracking-wider">
                                                {formatDistanceToNow(new Date(result.createdAt), { addSuffix: true })}
                                            </span>
                                        </div>
                                        <div className="text-[14px] text-slate-600 leading-relaxed line-clamp-2 pr-8">
                                            {highlightText(result.content, debouncedQuery)}
                                        </div>
                                    </div>

                                    {/* Arrow */}
                                    <div className="opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0 self-center">
                                        <ChevronRight className="h-5 w-5 text-slate-400" />
                                    </div>
                                </Link>
                            ))}
                        </div>
                    )}
                </div>

                {/* Footer */}
                {results.length > 0 && !isLoading && (
                    <div className="px-4 py-2 bg-white border-t border-slate-100 text-[12px] font-medium text-slate-400 text-center">
                        Showing {results.length} result{results.length !== 1 ? 's' : ''}
                    </div>
                )}
            </motion.div>
        </div>
    );
}
